Exemplo n.º 1
0
 public FieldToPropertyForwarder(ModuleWeaver moduleWeaver, FieldToPropertyConverter fieldToPropertyConverter, MsCoreReferenceFinder msCoreReferenceFinder, MethodFinder methodFinder)
 {
     this.moduleWeaver = moduleWeaver;
     this.msCoreReferenceFinder = msCoreReferenceFinder;
     this.methodFinder = methodFinder;
     forwardedFields = fieldToPropertyConverter.ForwardedFields;
 }
Exemplo n.º 2
0
        public WeaverHelper(string assemblyToProcess)
        {
            var assemblyFolder = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
            BeforeAssemblyPath = Path.Combine(assemblyFolder, assemblyToProcess);
            AfterAssemblyPath = BeforeAssemblyPath.Replace(".dll", "2.dll");

            File.Copy(BeforeAssemblyPath, AfterAssemblyPath, true);
            var moduleDefinition = ModuleDefinition.ReadModule(AfterAssemblyPath, new ReaderParameters());
            var weavingTask = new ModuleWeaver
            {
                ModuleDefinition = moduleDefinition,
                LogDebug = s => System.Diagnostics.Debug.WriteLine(s, "Debug"),
                LogInfo = s => System.Diagnostics.Debug.WriteLine(s, "Info"),
                LogWarning = s => System.Diagnostics.Debug.WriteLine(s, "Warning"),
                LogError = s => System.Diagnostics.Debug.WriteLine(s, "Error"),
            };

            weavingTask.Execute();

            moduleDefinition.Write(AfterAssemblyPath);

            //ProvideIlStepThrough(AfterAssemblyPath);

            Assembly = Assembly.LoadFile(AfterAssemblyPath);
        }
 public void False()
 {
     var xElement = XElement.Parse("<PropertyChanged InjectOnPropertyNameChanging='false'/>");
     var moduleWeaver = new ModuleWeaver { Config = xElement };
     moduleWeaver.ResolveOnPropertyNameChangingConfig();
     Assert.IsFalse(moduleWeaver.InjectOnPropertyNameChanging);
 }
Exemplo n.º 4
0
    public WithIncludesTests()
    {
        beforeAssemblyPath = Path.GetFullPath(Path.Combine(TestContext.CurrentContext.TestDirectory,@"..\..\..\AssemblyToProcess\bin\Debug\AssemblyToProcess.dll"));
#if (!DEBUG)
        beforeAssemblyPath = beforeAssemblyPath.Replace("Debug", "Release");
#endif

        afterAssemblyPath = beforeAssemblyPath.Replace(".dll", "3.dll");
        File.Copy(beforeAssemblyPath, afterAssemblyPath, true);

        var assemblyResolver = new MockAssemblyResolver
            {
                Directory = Path.GetDirectoryName(beforeAssemblyPath)
            };
        var moduleDefinition = ModuleDefinition.ReadModule(afterAssemblyPath,new ReaderParameters
            {
                AssemblyResolver = assemblyResolver
            });
        var weavingTask = new ModuleWeaver
                              {
                                  ModuleDefinition = moduleDefinition,
                                  AssemblyResolver = assemblyResolver,
                                  IncludeNamespaces = new List<string>{"MyNameSpace"},
                                  LogWarning =s => warnings.Add(s)
                              };

        weavingTask.Execute();
        moduleDefinition.Write(afterAssemblyPath);

        assembly = Assembly.LoadFile(afterAssemblyPath);
    }
Exemplo n.º 5
0
    public ExistingTests()
    {
        beforeAssemblyPath = Path.GetFullPath(Path.Combine(TestContext.CurrentContext.TestDirectory, @"..\..\..\AssemblyToProcessExistingAttribute\bin\Debug\AssemblyToProcessExistingAttribute.dll"));
#if (!DEBUG)
        beforeAssemblyPath = beforeAssemblyPath.Replace("Debug", "Release");
#endif

        afterAssemblyPath = beforeAssemblyPath.Replace(".dll", "2.dll");
        File.Copy(beforeAssemblyPath, afterAssemblyPath, true);

        var moduleDefinition = ModuleDefinition.ReadModule(afterAssemblyPath);
        var currentDirectory = AssemblyLocation.CurrentDirectory();
        var moduleWeaver = new ModuleWeaver
                           {
                               ModuleDefinition = moduleDefinition,
                               AddinDirectoryPath = currentDirectory,
                               SolutionDirectoryPath = currentDirectory,
                               AssemblyFilePath = afterAssemblyPath,
                           };

        moduleWeaver.Execute();
        moduleDefinition.Write(afterAssemblyPath);
        moduleWeaver.AfterWeaving();

        assembly = Assembly.LoadFile(afterAssemblyPath);
    }
Exemplo n.º 6
0
    public static Assembly WeaveAssembly()
    {
        var projectPath = Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, @"..\..\..\AssemblyToProcess\AssemblyToProcess.csproj"));
        var assemblyPath = Path.Combine(Path.GetDirectoryName(projectPath), @"bin\Debug\AssemblyToProcess.dll");

        var springBinPath = Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, @"..\..\..\Fody\bin\debug\"));
        #if (!DEBUG)
        assemblyPath = assemblyPath.Replace("Debug", "Release");
        springBinPath = springBinPath.Replace("Debug", "Release");
        #endif

        var newAssembly = assemblyPath.Replace(".dll", "2.dll");
        File.Copy(assemblyPath, newAssembly, true);

        var moduleDefinition = ModuleDefinition.ReadModule(newAssembly);
        var weavingTask = new ModuleWeaver
        {
            ModuleDefinition = moduleDefinition,
        };

        weavingTask.Execute();
        moduleDefinition.Write(newAssembly);

        return Assembly.LoadFile(newAssembly);
    }
Exemplo n.º 7
0
    public AssemblyWeaver(string assemblyPath, List<string> referenceAssemblyPaths = null)
    {
        if (referenceAssemblyPaths == null)
        {
            referenceAssemblyPaths  = new List<string>();
        }
        assemblyPath = FixAssemblyPath(assemblyPath);

        var newAssembly = assemblyPath.Replace(".dll", "2.dll");
        File.Copy(assemblyPath, newAssembly, true);

        var assemblyResolver = new MockAssemblyResolver();
        foreach (var referenceAssemblyPath in referenceAssemblyPaths)
        {
            var directoryName = Path.GetDirectoryName(referenceAssemblyPath);
            assemblyResolver.AddSearchDirectory(directoryName);
        }
        var readerParameters = new ReaderParameters
        {
            AssemblyResolver = assemblyResolver
        };
        var moduleDefinition = ModuleDefinition.ReadModule(newAssembly, readerParameters);
        var weavingTask = new ModuleWeaver
        {
            ModuleDefinition = moduleDefinition,
            AssemblyResolver = assemblyResolver,
            LogError = LogError,
            ReferenceCopyLocalPaths = referenceAssemblyPaths
        };

        weavingTask.Execute();
        moduleDefinition.Write(newAssembly);

        Assembly = Assembly.LoadFrom(newAssembly);
    }
        public static Assembly WeaveAssembly()
        {
            string configurationName = "Release";

            #if DEBUG
                configurationName = "Debug";
            #endif

            string assemblyPath = Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, @"..\..\..\AssemblyToProcess\bin", configurationName, "AssemblyToProcess.dll"));

            string newAssembly = assemblyPath.Replace(".dll", "2.dll");

            File.Copy(assemblyPath, newAssembly, true);

            ModuleDefinition moduleDefinition = ModuleDefinition.ReadModule(newAssembly);

            ModuleWeaver weavingTask = new ModuleWeaver
            {
                ModuleDefinition = moduleDefinition
            };

            weavingTask.Execute();

            moduleDefinition.Write(newAssembly);

            return Assembly.LoadFile(newAssembly);
        }
Exemplo n.º 9
0
 public void IncludeAndExcludeNamespacesAttribute()
 {
     var xElement = XElement.Parse(@"
     <Virtuosity IncludeNamespaces='Bar' ExcludeNamespaces='Foo'/>");
     var moduleWeaver = new ModuleWeaver { Config = xElement };
     moduleWeaver.ReadConfig();
 }
Exemplo n.º 10
0
        protected ProcessAssemblyBaseTest( string relativePath )
        {
            BeforeAssemblyPath = Path.GetFullPath( relativePath );
            #if !DEBUG
            BeforeAssemblyPath = BeforeAssemblyPath.Replace("Debug", "Release");
            #endif

            AfterAssemblyPath = BeforeAssemblyPath.Replace( ".dll", "2.dll" );
            File.Copy( BeforeAssemblyPath, AfterAssemblyPath, true );

            var moduleDefinition = ModuleDefinition.ReadModule( AfterAssemblyPath );

            var currentDirectory = AssemblyLocation.CurrentDirectory();
            PersistentInfo = PersistentInfo.LoadFromPath( currentDirectory );
            StandardInfo = new StandardInfo( PersistentInfo, moduleDefinition );

            var moduleWeaver = new ModuleWeaver
            {
                ModuleDefinition = moduleDefinition,
                AddinDirectoryPath = currentDirectory,
                SolutionDirectoryPath = currentDirectory,
                AssemblyFilePath = AfterAssemblyPath,
            };

            moduleWeaver.Execute();
            moduleDefinition.Write( AfterAssemblyPath );
            moduleWeaver.AfterWeaving();

            AfterAssembly = Assembly.LoadFile( AfterAssemblyPath );
        }
Exemplo n.º 11
0
    public IntegrationTests()
    {
        beforeAssemblyPath = Path.GetFullPath(@"..\..\..\AssemblyToProcess\bin\Debug\AssemblyToProcess.dll");
        #if (!DEBUG)

        beforeAssemblyPath = beforeAssemblyPath.Replace("Debug", "Release");
        #endif

        afterAssemblyPath = beforeAssemblyPath.Replace(".dll", "2.dll");
        File.Copy(beforeAssemblyPath, afterAssemblyPath, true);

        var assemblyResolver = new MockAssemblyResolver
            {
                Directory = Path.GetDirectoryName(beforeAssemblyPath)
            };
        var moduleDefinition = ModuleDefinition.ReadModule(afterAssemblyPath,new ReaderParameters
            {
                AssemblyResolver = assemblyResolver
            });
        var weavingTask = new ModuleWeaver
                              {
                                  ModuleDefinition = moduleDefinition,
                                  AssemblyResolver = assemblyResolver,
                              };

        weavingTask.Execute();
        moduleDefinition.Write(afterAssemblyPath);

        assembly = Assembly.LoadFile(afterAssemblyPath);
    }
Exemplo n.º 12
0
    public WeaverHelper(string projectPath)
    {
        this.projectPath = Path.GetFullPath(Path.Combine(TestContext.CurrentContext.TestDirectory, @"..\..\..\TestAssemblies", projectPath));

        GetAssemblyPath();

        AfterAssemblyPath = BeforeAssemblyPath.Replace(".dll", "2.dll");
        File.Copy(BeforeAssemblyPath, AfterAssemblyPath, true);

        var assemblyResolver = new TestAssemblyResolver(BeforeAssemblyPath, this.projectPath);
        var readerParameters = new ReaderParameters
        {
            AssemblyResolver = assemblyResolver
        };
        var moduleDefinition = ModuleDefinition.ReadModule(AfterAssemblyPath, readerParameters);
        var weavingTask = new ModuleWeaver
                              {
                                  ModuleDefinition = moduleDefinition,
                                  AssemblyResolver = assemblyResolver
                              };

        weavingTask.Execute();

        moduleDefinition.Write(AfterAssemblyPath);

        Assembly = Assembly.LoadFile(AfterAssemblyPath);
    }
Exemplo n.º 13
0
    static AssemblyWeaver()
    {
        BeforeAssemblyPath = Path.GetFullPath(@"..\..\..\AssemblyToProcess\bin\Debug\AssemblyToProcess.dll");
        BeforeAssemblyPathSymbols = Path.ChangeExtension(BeforeAssemblyPath, "pdb");

        #if (!DEBUG)
        BeforeAssemblyPath = BeforeAssemblyPath.Replace("Debug", "Release");
        BeforeAssemblyPathSymbols = BeforeAssemblyPathSymbols.Replace("Debug", "Release");
        #endif
        AfterAssemblyPath = BeforeAssemblyPath.Replace(".dll", "2.dll");
        AfterAssemblyPathSymbols = Path.ChangeExtension(AfterAssemblyPath, "pdb");

        File.Copy(BeforeAssemblyPath, AfterAssemblyPath, true);
        File.Copy(BeforeAssemblyPathSymbols, AfterAssemblyPathSymbols, true);

        var assemblyResolver = new MockAssemblyResolver();
        var moduleDefinition = ModuleDefinition.ReadModule(AfterAssemblyPath, new ReaderParameters { ReadSymbols = true });

        var weavingTask = new ModuleWeaver
        {
            ModuleDefinition = moduleDefinition,
            AssemblyResolver = assemblyResolver,
            LogError = LogError,
            LogInfo = LogInfo,
            DefineConstants = new[] { "DEBUG" }, // Always testing the debug weaver
        };

        weavingTask.Execute();
        moduleDefinition.Write(AfterAssemblyPath, new WriterParameters { WriteSymbols = true });

        Assembly = Assembly.LoadFile(AfterAssemblyPath);
    }
Exemplo n.º 14
0
    public IntegrationTests()
    {
        beforeAssemblyPath = Path.GetFullPath(Path.Combine(TestContext.CurrentContext.TestDirectory, @"..\..\..\AssemblyToProcess\bin\Debug\AssemblyToProcess.dll"));
#if (!DEBUG)
        beforeAssemblyPath = beforeAssemblyPath.Replace("Debug", "Release");
#endif

        afterAssemblyPath = beforeAssemblyPath.Replace(".dll", "2.dll");
        File.Copy(beforeAssemblyPath, afterAssemblyPath, true);

        var moduleDefinition = ModuleDefinition.ReadModule(afterAssemblyPath);
        var weavingTask = new ModuleWeaver
        {
            ModuleDefinition = moduleDefinition,
            AssemblyResolver = new MockAssemblyResolver(),
            LogWarning = s => warnings.Add(s),
            LogError = s => errors.Add(s),
            HideObsoleteMembers = true
        };

        weavingTask.Execute();
        moduleDefinition.Write(afterAssemblyPath);

        assembly = Assembly.LoadFile(afterAssemblyPath);
    }
Exemplo n.º 15
0
 public void TrueHideObsoleteMembers()
 {
     var xElement = XElement.Parse(@"<Obsolete HideObsoleteMembers='true'/>");
     var moduleWeaver = new ModuleWeaver {Config = xElement};
     moduleWeaver.ReadConfig();
     Assert.IsTrue(moduleWeaver.HideObsoleteMembers);
 }
Exemplo n.º 16
0
 public void ThrowsNotImplementedText()
 {
     var xElement = XElement.Parse(@"<Obsolete ThrowsNotImplementedText='Custom Text'/>");
     var moduleWeaver = new ModuleWeaver {Config = xElement};
     moduleWeaver.ReadConfig();
     Assert.AreEqual("Custom Text", moduleWeaver.ThrowsNotImplementedText);
 }
Exemplo n.º 17
0
 public void VersionIncrementThrows()
 {
     var xElement = XElement.Parse(@"<Obsolete VersionIncrement='1.0.1'/>");
     var moduleWeaver = new ModuleWeaver {Config = xElement};
     var exception = Assert.Throws<WeavingException>(moduleWeaver.ReadConfig);
     Assert.AreEqual("VersionIncrement is no longer supported. Use StepType instead.", exception.Message);
 }
Exemplo n.º 18
0
 public void CanParseStepType()
 {
     var xElement = XElement.Parse(@"<Obsolete StepType='Minor'/>");
     var moduleWeaver = new ModuleWeaver {Config = xElement};
     moduleWeaver.ReadConfig();
     Assert.AreEqual(StepType.Minor, moduleWeaver.StepType);
 }
Exemplo n.º 19
0
    public ModuleWeaverOperandTests()
    {
        var beforeAssemblyPath = Path.GetFullPath(Path.Combine(TestContext.CurrentContext.TestDirectory, @"..\..\..\AssemblyToProcess\bin\Debug\AssemblyToProcess.dll"));
        #if (!DEBUG)
        beforeAssemblyPath = beforeAssemblyPath.Replace("Debug", "Release");
        #endif
        var afterAssemblyPath = typeof(ModuleWeaverOperandTests).Name + ".dll";

        var moduleDefinition = ModuleDefinition.ReadModule(beforeAssemblyPath);
        AddConditionalBranchLong(moduleDefinition, moduleDefinition.Types.Single(t => t.Name == "TargetClass"));

        // Offset assignment happens on write
        // Having offsets assigned prior to weaving makes tracking down bugs easier
        moduleDefinition.Write(afterAssemblyPath);

        var weavingTask = new ModuleWeaver
        {
            ModuleDefinition = moduleDefinition,
        };
        weavingTask.Execute();

        moduleDefinition.Assembly.Name.Name += "ForOperand";
        moduleDefinition.Write(afterAssemblyPath);
        var assembly = Assembly.LoadFrom(afterAssemblyPath);
        var type = assembly.GetType("TargetClass", true);
        targetClass = Activator.CreateInstance(type);
    }
Exemplo n.º 20
0
 public PropertyWeaver(ModuleWeaver moduleWeaver, PropertyData propertyData, TypeNode typeNode, TypeSystem typeSystem )
 {
     this.moduleWeaver = moduleWeaver;
     this.propertyData = propertyData;
     this.typeNode = typeNode;
     this.typeSystem = typeSystem;
 }
Exemplo n.º 21
0
    public TaskTests()
    {
        beforeAssemblyPath = Path.GetFullPath(@"..\..\..\AssemblyToProcess\bin\Debug\AssemblyToProcess.dll");
#if (!DEBUG)
        beforeAssemblyPath = beforeAssemblyPath.Replace("Debug", "Release");
#endif

        afterAssemblyPath = beforeAssemblyPath.Replace(".dll", "2.dll");
        File.Copy(beforeAssemblyPath, afterAssemblyPath, true);

        var moduleDefinition = ModuleDefinition.ReadModule(afterAssemblyPath);
        var currentDirectory = AssemblyLocation.CurrentDirectory();
        var weavingTask = new ModuleWeaver
                          {
                              ModuleDefinition = moduleDefinition,
                              AddinDirectoryPath = currentDirectory,
                              SolutionDirectoryPath = currentDirectory,
                              AssemblyFilePath = afterAssemblyPath,
                              SvnHelper = new MockSvnHelper(),
                          };

        weavingTask.Execute();
        moduleDefinition.Write(afterAssemblyPath);
        weavingTask.AfterWeaving();

        assembly = Assembly.LoadFile(afterAssemblyPath);
    }
 public void False()
 {
     var xElement = XElement.Parse("<PropertyChanged CheckForEquality='false'/>");
     var moduleWeaver = new ModuleWeaver { Config = xElement };
     moduleWeaver.ResolveCheckForEqualityConfig();
     Assert.IsFalse(moduleWeaver.CheckForEquality);
 }
Exemplo n.º 23
0
    public void Simple()
    {
        var beforeAssemblyPath = Path.GetFullPath(Path.Combine(TestContext.CurrentContext.TestDirectory, @"..\..\..\AssemblyWithExcludes\bin\Debug\AssemblyWithExcludes.dll"));
        #if (!DEBUG)
        beforeAssemblyPath = beforeAssemblyPath.Replace("Debug", "Release");
        #endif

        var afterAssemblyPath = beforeAssemblyPath.Replace(".dll", "2.dll");
        File.Copy(beforeAssemblyPath, afterAssemblyPath, true);

        var moduleDefinition = ModuleDefinition.ReadModule(afterAssemblyPath);
        var weavingTask = new ModuleWeaver
        {
            ModuleDefinition = moduleDefinition,
            ExcludeNamespaces = new List<string> { "ExcludeNamespace"}
        };

        weavingTask.Execute();
        moduleDefinition.Write(afterAssemblyPath);

        var assembly = Assembly.LoadFile(afterAssemblyPath);

        var excludeType = assembly.GetType("ExcludeNamespace.ExcludeClass");
        Assert.IsFalse(excludeType.GetMethod("Method").IsVirtual);
        var includeType = assembly.GetType("IncludeNamespace.IncludeClass");
        Assert.IsTrue(includeType.GetMethod("Method").IsVirtual);

        var inNamespaceButWithAttributeType = assembly.GetType("IncludeNamespace.InNamespaceButWithAttributeClass");
        Assert.IsFalse(inNamespaceButWithAttributeType.GetMethod("Method").IsVirtual);
        var notInNamespaceButWithAttributeType = assembly.GetType("ExcludeNamespace.NotInNamespaceButWithAttributeClass");
        Assert.IsFalse(notInNamespaceButWithAttributeType.GetMethod("Method").IsVirtual);
        #if(DEBUG)
        Verifier.Verify(beforeAssemblyPath, afterAssemblyPath);
        #endif
    }
 public void True()
 {
     var xElement = XElement.Parse("<PropertyChanged InjectOnPropertyNameChanged='true'/>");
     var moduleWeaver = new ModuleWeaver {Config = xElement};
     moduleWeaver.ResolveOnPropertyNameChangedConfig();
     Assert.IsTrue(moduleWeaver.InjectOnPropertyNameChanged);
 }
Exemplo n.º 25
0
    public void VerifyAssembly(string assemblyPath)
    {

        Debug.WriteLine("Verifying " + assemblyPath);
        var cleanAssembly = assemblyPath.Replace(".dll", "2.dll");
        var newAssembly = assemblyPath.Replace(".dll", "3.dll");
        File.Copy(assemblyPath, cleanAssembly, true);
        File.Copy(assemblyPath, newAssembly, true);

        var assemblyResolver = new MockAssemblyResolver();
        var moduleDefinition = ModuleDefinition.ReadModule(cleanAssembly);
        var weavingTask = new ModuleWeaver
        {
            ModuleDefinition = moduleDefinition,
            AssemblyResolver = assemblyResolver,
        };
        moduleDefinition.Write(cleanAssembly);

        moduleDefinition = ModuleDefinition.ReadModule(newAssembly);
        weavingTask.ModuleDefinition = moduleDefinition;
        weavingTask.Execute();
        moduleDefinition.Write(newAssembly);

        Verifier.Verify(cleanAssembly, newAssembly);
    }
Exemplo n.º 26
0
    public void Setup()
    {
        var projectPath = Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, @"..\..\..\AssemblyToProcess\AssemblyToProcess.csproj"));
        assemblyPath = Path.Combine(Path.GetDirectoryName(projectPath), @"bin\Debug\AssemblyToProcess.dll");
#if (!DEBUG)
        assemblyPath = assemblyPath.Replace("Debug", "Release");
#endif

        newAssemblyPath = assemblyPath.Replace(".dll", "2.dll");
        shadowAssemblyPath = assemblyPath.Replace(".dll", "2shadow.dll");
        File.Copy(assemblyPath, newAssemblyPath, true);
        File.Copy(assemblyPath, shadowAssemblyPath, true);
        
        var moduleDefinition = ModuleDefinition.ReadModule(newAssemblyPath);
        var weavingTask = new ModuleWeaver
        {
            ModuleDefinition = moduleDefinition            
        };

        weavingTask.Execute();

        moduleDefinition.Write(newAssemblyPath);

        assembly = Assembly.LoadFile(newAssemblyPath);
    }
Exemplo n.º 27
0
    public static string Weave(string assemblyPath)
    {
        var newAssembly = assemblyPath.Replace(".dll", "2.dll");
        var oldPdb = assemblyPath.Replace(".dll", ".pdb");
        var newPdb = assemblyPath.Replace(".dll", "2.pdb");
        File.Copy(assemblyPath, newAssembly, true);
        File.Copy(oldPdb, newPdb, true);

        var assemblyResolver = new MockAssemblyResolver
            {
                Directory = Path.GetDirectoryName(assemblyPath)
            };

        using (var symbolStream = File.OpenRead(newPdb))
        {
            var readerParameters = new ReaderParameters
                {
                    ReadSymbols = true,
                    SymbolStream = symbolStream,
                    SymbolReaderProvider = new PdbReaderProvider()
                };
            var moduleDefinition = ModuleDefinition.ReadModule(newAssembly, readerParameters);

            var weavingTask = new ModuleWeaver
                {
                    ModuleDefinition = moduleDefinition,
                    AssemblyResolver = assemblyResolver
                };

            weavingTask.Execute();
            moduleDefinition.Write(newAssembly);

            return newAssembly;
        }
    }
        protected static string WeaveAssembly(Type assemblyType)
        {
            var normalizedPath = assemblyType.Assembly.CodeBase.Replace(@"file:///", string.Empty);

            var weaver = new ModuleWeaver();
            return WeavedAssemblyPath = weaver.WeaveToShadowFile(normalizedPath);
        }
Exemplo n.º 29
0
    public void VerifyRefError()
    {
        var errors = new List<string>();
        var assemblyPath = Path.GetFullPath(Path.Combine(TestContext.CurrentContext.TestDirectory, @"..\..\..\AssemblyToProcessWithErrors\bin\Debug\AssemblyToProcessWithErrors.dll"));
        #if (!DEBUG)
        assemblyPath = assemblyPath.Replace("Debug", "Release");
        #endif

        var moduleDefinition = ModuleDefinition.ReadModule(assemblyPath, new ReaderParameters
                                                                         {
                                                                             //SymbolStream = symbolStream,
                                                                             ReadSymbols = true
                                                                         });

        var weavingTask = new ModuleWeaver
                          {
                              ModuleDefinition = moduleDefinition,
                              LogErrorPoint = (s, p) => errors.Add(s)
                          };

        weavingTask.Execute();
        Assert.Contains("Method 'ClassUsingOutParam.Method' uses member 'ClassWithField.Member' as a 'ref' or 'out' parameter. This is not supported by Fielder. Please convert this field to a property manually.", errors);
        Assert.Contains("Method 'ClassUsingRefParam.Method' uses member 'ClassWithField.Member' as a 'ref' or 'out' parameter. This is not supported by Fielder. Please convert this field to a property manually.", errors);
        Assert.AreEqual(2, errors.Count);
    }
Exemplo n.º 30
0
    public ModuleWeaverOrdinalTests()
    {
        beforeAssemblyPath = Path.GetFullPath(Path.Combine(TestContext.CurrentContext.TestDirectory, @"..\..\..\AssemblyToProcess\bin\Debug\AssemblyToProcess.dll"));
#if (!DEBUG)
       beforeAssemblyPath = beforeAssemblyPath.Replace("Debug", "Release");
#endif
#if (!DEBUG)
        beforeAssemblyPath = beforeAssemblyPath.Replace("Debug", "Release");
#endif
        afterAssemblyPath = beforeAssemblyPath.Replace(".dll", "3.dll");
        File.Copy(beforeAssemblyPath, afterAssemblyPath, true);

        var moduleDefinition = ModuleDefinition.ReadModule(afterAssemblyPath);

        var weavingTask = new ModuleWeaver
            {
                Config = XElement.Parse(@"<Caseless StringComparison="" ordinal ""/>"),
                ModuleDefinition = moduleDefinition,
            };

        weavingTask.Execute();
        moduleDefinition.Assembly.Name.Name += "ForOrdinal";
        moduleDefinition.Write(afterAssemblyPath);
        var assembly = Assembly.LoadFrom(afterAssemblyPath);
        var type = assembly.GetType("TargetClass", true);
        targetClass = Activator.CreateInstance(type);
    }
Exemplo n.º 31
0
 public MethodWeaverHelper(ModuleWeaver moduleWeaver)
 {
     ModuleWeaver     = moduleWeaver;
     ModuleDefinition = moduleWeaver.ModuleDefinition;
 }
Exemplo n.º 32
0
        static ModuleWeaverTests()
        {
            var weavingTask = new ModuleWeaver();

            TestResult = weavingTask.ExecuteTestRun("InlineMethod.Tests.AssemblyToProcess.dll");
        }
Exemplo n.º 33
0
    static WithNopInterceptorTests()
    {
        var weavingTask = new ModuleWeaver();

        testResult = weavingTask.ExecuteTestRun("AssemblyWithNopInterceptor.dll");
    }
        private static void WeaveAssembly(Type type, ModuleWeaver weaver)
        {
            var normalizedPath = type.Assembly.CodeBase.Replace(@"file:///", string.Empty);

            WeavedAssemblyPath = weaver.WeaveToShadowFile(normalizedPath, ModuleHelper.AssemblyResolver);
        }
Exemplo n.º 35
0
 public OperatorBadCaseIntegrationTests()
 {
     weavingTask = new ModuleWeaver();
 }
Exemplo n.º 36
0
    static AssemblyWeaver()
    {
        var testDirectory = TestContext.CurrentContext.TestDirectory;

        BeforeAssemblyPath = Path.GetFullPath(Path.Combine(testDirectory, @"..\..\..\..\AssemblyToProcess\bin\Debug\net452\AssemblyToProcess.dll"));
        BeforeSymbolPath   = Path.ChangeExtension(BeforeAssemblyPath, "pdb");
#if (!DEBUG)
        BeforeAssemblyPath = BeforeAssemblyPath.Replace("Debug", "Release");
        BeforeSymbolPath   = BeforeSymbolPath.Replace("Debug", "Release");
#endif

        AfterAssemblyPath = BeforeAssemblyPath.Replace(".dll", "2.dll");
        AfterSymbolPath   = BeforeSymbolPath.Replace(".pdb", "2.pdb");

        if (File.Exists(AfterAssemblyPath))
        {
            File.Delete(AfterAssemblyPath);
        }
        if (File.Exists(AfterSymbolPath))
        {
            File.Delete(AfterSymbolPath);
        }

        var assemblyResolver = new MockAssemblyResolver();
        var readerParameters = new ReaderParameters {
            AssemblyResolver = assemblyResolver
        };
        var writerParameters = new WriterParameters();

        if (File.Exists(BeforeSymbolPath))
        {
            readerParameters.ReadSymbols          = true;
            readerParameters.SymbolReaderProvider = new PdbReaderProvider();
            readerParameters.SymbolStream         = new FileStream(BeforeSymbolPath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
            writerParameters.WriteSymbols         = true;
            writerParameters.SymbolWriterProvider = new PdbWriterProvider();
        }

        var moduleDefinition = ModuleDefinition.ReadModule(BeforeAssemblyPath, readerParameters);


        var weavingTask = new ModuleWeaver
        {
            Config = new XElement("NullGuard",
                                  new XAttribute("IncludeDebugAssert", false),
                                  new XAttribute("ExcludeRegex", "^ClassToExclude$")),
            ModuleDefinition = moduleDefinition,
            AssemblyResolver = assemblyResolver,
            LogInfo          = LogInfo,
            LogWarn          = LogWarn,
            LogError         = LogError,
            DefineConstants  = new List <string> {
                "DEBUG"
            }                                            // Always testing the debug weaver
        };

        weavingTask.Execute();

        moduleDefinition.Write(AfterAssemblyPath, writerParameters);

        Assembly = Assembly.LoadFile(AfterAssemblyPath);
    }
Exemplo n.º 37
0
    public AssemblyWeaver(List <string> referenceAssemblyPaths = null)
    {
        if (referenceAssemblyPaths is null)
        {
            referenceAssemblyPaths = new List <string>();
        }

        //Force ref since MSTest is a POS
        var type = typeof(ViewModelBaseTest);

        BeforeAssemblyPath = type.GetAssemblyEx().Location;
        //BeforeAssemblyPath =  Path.GetFullPath("Catel.Fody.TestAssembly.dll");
        AfterAssemblyPath = BeforeAssemblyPath.Replace(".dll", "2.dll");

        var oldPdb = Path.ChangeExtension(BeforeAssemblyPath, "pdb");
        var newPdb = Path.ChangeExtension(AfterAssemblyPath, "pdb");

        if (File.Exists(oldPdb))
        {
            File.Copy(oldPdb, newPdb, true);
        }

        Debug.WriteLine("Weaving assembly on-demand from '{0}' to '{1}'", BeforeAssemblyPath, AfterAssemblyPath);

        var assemblyResolver = new TestAssemblyResolver();
        //assemblyResolver.AddSearchDirectory(AssemblyDirectoryHelper.GetCurrentDirectory());
        //foreach (var referenceAssemblyPath in referenceAssemblyPaths)
        //{
        //    var directoryName = Path.GetDirectoryName(referenceAssemblyPath);
        //    assemblyResolver.AddSearchDirectory(directoryName);
        //}

        var metadataResolver = new MetadataResolver(assemblyResolver);

        var readerParameters = new ReaderParameters
        {
            AssemblyResolver = assemblyResolver,
            MetadataResolver = metadataResolver,
            ReadSymbols      = File.Exists(oldPdb),
        };

        using (var moduleDefinition = ModuleDefinition.ReadModule(BeforeAssemblyPath, readerParameters))
        {
            var weavingTask = new ModuleWeaver
            {
                ModuleDefinition   = moduleDefinition,
                AssemblyFilePath   = AfterAssemblyPath,
                AssemblyResolver   = assemblyResolver,
                Config             = XElement.Parse(@"<Weavers><Catel /></Weavers>"),
                AddinDirectoryPath = Path.Combine(AssemblyDirectoryHelper.GetCurrentDirectory(), "..", "..", "Catel.Fody")
            };

            weavingTask.Execute();
            moduleDefinition.Write(AfterAssemblyPath);
        }

//        if (Debugger.IsAttached)
//        {
//#if DEBUG
//            var output = "debug";
//#else
//            var output = "release";
//#endif

//            var targetFile = $@"C:\Source\Catel.Fody\output\{output}\Catel.Fody.Tests\Catel.Fody.TestAssembly2.dll";
//            var targetDirectory = Path.GetDirectoryName(targetFile);
//            Directory.CreateDirectory(targetDirectory);
//            File.Copy(AfterAssemblyPath, targetFile, true);
//        }

        Assembly = Assembly.LoadFile(AfterAssemblyPath);
    }
 public ReferenceSelector(ModuleWeaver moduleWeaver, ModuleDefinition moduleDefinition, Configuration configuration)
 {
     _moduleWeaver     = moduleWeaver;
     _moduleDefinition = moduleDefinition;
     _configuration    = configuration;
 }
Exemplo n.º 39
0
 public WeaverLogger(ModuleWeaver weaver)
 {
     _weaver = weaver ?? throw new ArgumentNullException(nameof(weaver));
 }
Exemplo n.º 40
0
    static BindableTests()
    {
        var weavingTask = new ModuleWeaver();

        __testResult = weavingTask.ExecuteTestRun("AssemblyToProcess.dll", runPeVerify: false);
    }
Exemplo n.º 41
0
    public static void InterceptConstructors(Builder builder)
    {
        if (!constructorInterceptionAttributes.Any())
        {
            return;
        }

        var constructors = builder
                           .FindMethodsByAttributes(constructorInterceptionAttributes)
                           .Where(x => !x.Method.OriginType.IsInterface)
                           .GroupBy(x => new MethodKey(x.Method, null))
                           .Select(x => new MethodBuilderInfo <MethodBuilderInfoItem <BuilderTypeIConstructorInterceptor> >(x.Key, x.Select(y => new MethodBuilderInfoItem <BuilderTypeIConstructorInterceptor>(y, BuilderTypes.IConstructorInterceptor))))
                           .ToArray();

        foreach (var constructor in constructors)
        {
            if (constructor.Items == null || constructor.Items.Length == 0)
            {
                continue;
            }

            var targetedConstrutor = constructor.Key.Method;

            if (!targetedConstrutor.IsCtor && !targetedConstrutor.IsCCtor)
            {
                continue;
            }

            builder.Log(LogTypes.Info, $"Implementing constructors interceptors: {constructor.Key.Method.DeclaringType.Name.PadRight(40, ' ')} {constructor.Key.Method.Name}({string.Join(", ", constructor.Key.Method.Parameters.Select(x => x.Name))})");

            if (constructor.RequiresSyncRootField)
            {
                builder.Log(LogTypes.Warning, targetedConstrutor, $"An interceptor applied to the constructor has implemented ISyncRoot. This is not supported. The interceptor may not work correctly.");
            }

            CodeBlock parametersArray = null;
            var       localVariables  = new LocalVariable[constructor.Items.Length];
            Coder InterceptorInit(Coder contextCoder, bool isBeforeInit)
            {
                parametersArray = contextCoder.GetParametersArray();

                for (int i = 0; i < constructor.Items.Length; i++)
                {
                    var item = constructor.Items[i];
                    localVariables[i] = contextCoder.AssociatedMethod.GetOrCreateVariable(item.Interface.BuilderType);

                    contextCoder.SetValue(localVariables[i], x => x.NewObj(item.Attribute));
                    contextCoder.Load(localVariables[i]).Call(item.Interface.GetMethod_OnBeforeInitialization(), targetedConstrutor.OriginType, targetedConstrutor, parametersArray);

                    item.Attribute.Remove();
                }

                return(contextCoder);
            }

            if (targetedConstrutor.IsCtor)
            {
                targetedConstrutor.NewCoder()
                .Context(x => InterceptorInit(x, true))
                .Insert(InsertionPosition.CtorBeforeInit);
            }

            targetedConstrutor.NewCoder()
            .Context(x =>
            {
                if (targetedConstrutor.IsCCtor)
                {
                    InterceptorInit(x, false);
                }

                for (int i = 0; i < constructor.Items.Length; i++)
                {
                    var item = constructor.Items[i];
                    ModuleWeaver.ImplementAssignMethodAttribute(builder, item.AssignMethodAttributeInfos, localVariables[i], item.Attribute.Attribute.Type, x);

                    item.Attribute.Remove();
                }

                return(x);
            })
            .Try(x =>
            {
                for (int i = 0; i < constructor.Items.Length; i++)
                {
                    var item = constructor.Items[i];
                    x.Load(localVariables[i]).Call(item.Interface.GetMethod_OnEnter(), targetedConstrutor.OriginType, CodeBlocks.This, targetedConstrutor, parametersArray);
                }

                return(x);
            })
            .Catch(BuilderTypes.Exception.BuilderType, (ex, e) =>
            {
                return(ex.If(x => x.Or(constructor.Items, (coder, y, i) => coder.Load(localVariables[i]).Call(y.Interface.GetMethod_OnException(), e())).Is(true),
                             then => ex.NewCoder().Rethrow())
                       .DefaultValue()
                       .Return());
            })
            .Finally(x =>
            {
                for (int i = 0; i < constructor.Items.Length; i++)
                {
                    x.Load(localVariables[i]).Call(constructor.Items[i].Interface.GetMethod_OnException());
                }
                return(x);
            })
            .EndTry()
            .Return()
            .Replace();
        }
    }
Exemplo n.º 42
0
    public void When_assembly_to_weave_does_not_reference_equals_assembly_weaving_should_not_fail()
    {
        var testResult = new ModuleWeaver().ExecuteTestRun("AssemblyToProcessWithoutReference.dll");

        Assert.NotNull(testResult.GetInstance("Foo"));
    }
Exemplo n.º 43
0
    public TestResult GetAssembly(string testCaseName, string configString)
    {
        if (!_assemblies.ContainsKey(configString))
        {
            var type = typeof(DummyDependencyInjectionClass);

            var assemblyPath = type.GetAssemblyEx().Location;

            var rootDirectory     = Directory.GetParent(assemblyPath).FullName;
            var testCaseDirectory = Path.Combine(rootDirectory, testCaseName);
            Directory.CreateDirectory(testCaseDirectory);

            var assemblyResolver = new TestAssemblyResolver();
            //assemblyResolver.AddSearchDirectory(testCaseDirectory);
            //assemblyResolver.AddSearchDirectory(rootDirectory);

            var metadataResolver = new MetadataResolver(assemblyResolver);

            var readerParameters = new ReaderParameters
            {
                AssemblyResolver = assemblyResolver,
                MetadataResolver = metadataResolver,
                ReadSymbols      = false,
            };

            using (var moduleDefinition = ModuleDefinition.ReadModule(assemblyPath, readerParameters))
            {
                // Important note: the test project can be on a completely different location (especially on a build agent)
                var projectName = Path.GetFileName(assemblyPath).Replace(".dll", string.Empty);

                // Check 1: fixed location from test
                var relativeCsProjectFilePath = Path.Combine(Directory.GetParent(assemblyPath).FullName, "..", "..", "..", "..", "src", projectName, $"{projectName}.csproj");
                var csProjectFilePath         = Path.GetFullPath(relativeCsProjectFilePath);

                if (!File.Exists(csProjectFilePath))
                {
                    // Check 2: Check 2 directories up, then search for the project file (happens on a build agent)
                    var searchDirectory = Path.Combine(Directory.GetParent(assemblyPath).FullName, "..", "..", "..", "Source");
                    var searchFileName  = $"{projectName}.csproj";
                    csProjectFilePath = Directory.GetFiles(searchDirectory, searchFileName, SearchOption.AllDirectories).FirstOrDefault();
                }

                if (!File.Exists(csProjectFilePath))
                {
                    throw new System.Exception($"Project file '{csProjectFilePath}' does not exist, make sure to check the paths since this is required for the unit tests");
                }

                var references = new string[]
                {
                    //"Catel.Core.dll",
                    //"Orc.FileSystem.dll"
                };

                var weavingTask = new ModuleWeaver
                {
                    Config                  = XElement.Parse(configString),
                    AssemblyResolver        = assemblyResolver,
                    ProjectFilePath         = csProjectFilePath,
                    ModuleDefinition        = moduleDefinition,
                    References              = string.Join(";", references.Select(r => Path.Combine(rootDirectory, r))),
                    ReferenceCopyLocalPaths = references.Select(r => Path.Combine(rootDirectory, r)).ToList(),
                };

                var testResult = weavingTask.ExecuteTestRun(assemblyPath,
                                                            assemblyName: testCaseName,
                                                            ignoreCodes: new[] { "0x80131869" },
                                                            runPeVerify: false);

                if (testResult.Errors.Count > 0)
                {
                    throw new System.Exception("Received errors while weaving");
                }

                _assemblies[configString] = testResult;
            }
        }

        return(_assemblies[configString]);
    }
Exemplo n.º 44
0
 public MsCoreReferenceFinder(ModuleWeaver moduleWeaver, IAssemblyResolver assemblyResolver)
 {
     this._moduleWeaver = moduleWeaver;
 }
Exemplo n.º 45
0
 public void SetUp()
 {
     stackOverflowChecker = new ModuleWeaver();
 }
Exemplo n.º 46
0
    public static void InterceptMethods(Builder builder)
    {
        if (!methodInterceptionAttributes.Any())
        {
            return;
        }

        var methods = builder
                      .FindMethodsByAttributes(methodInterceptionAttributes)
                      .Where(x => !x.Method.IsPropertyGetterSetter)
                      .GroupBy(x => new MethodKey(x.Method, x.AsyncMethod))
                      .Select(x => new MethodBuilderInfo <MethodBuilderInfoItem <BuilderTypeIMethodInterceptor, BuilderTypeISimpleMethodInterceptor> >(x.Key,
                                                                                                                                                       x.Select(y => new MethodBuilderInfoItem <BuilderTypeIMethodInterceptor, BuilderTypeISimpleMethodInterceptor>(y, BuilderTypes.IMethodInterceptor, BuilderTypes.ISimpleMethodInterceptor))))
                      .OrderBy(x => x.Key.Method.DeclaringType.Fullname)
                      .ToArray();

        foreach (var method in methods)
        {
            if (method.Items == null || method.Items.Length == 0 || method.Key.Method.IsAbstract)
            {
                continue;
            }

            builder.Log(LogTypes.Info, $"Implementing method interceptors: {method.Key.Method.DeclaringType.Name.PadRight(40, ' ')} {method.Key.Method.Name}({string.Join(", ", method.Key.Method.Parameters.Select(x => x.Name))})");

            var targetedMethod              = method.Key.AsyncMethod ?? method.Key.Method;
            var attributedMethod            = method.Key.Method;
            var hasSimpleMethodInterceptors = method.Items.Any(x => x.HasInterfaceB);
            var hasFullMethodInterceptors   = method.Items.Any(x => x.HasInterfaceA);

            if (method.RequiresSyncRootField)
            {
                if (method.SyncRoot.IsStatic)
                {
                    method.Key.Method.DeclaringType.CreateStaticConstructor().NewCoder()
                    .SetValue(method.SyncRoot, x => x.NewObj(builder.GetType(typeof(object)).Import().ParameterlessContructor))
                    .Insert(InsertionPosition.Beginning);
                }
                else
                {
                    foreach (var ctors in method.Key.Method.DeclaringType.GetRelevantConstructors().Where(x => x.Name == ".ctor"))
                    {
                        ctors.NewCoder().SetValue(method.SyncRoot, x => x.NewObj(builder.GetType(typeof(object)).Import().ParameterlessContructor))
                        .Insert(InsertionPosition.Beginning);
                    }
                }
            }

            var coder = targetedMethod
                        .NewCoder()
                        .Context(x =>
            {
                for (int i = 0; i < method.Items.Length; i++)
                {
                    var item = method.Items[i];
                    var alwaysCreateNewInstance = item.InterceptorInfo.AlwaysCreateNewInstance;
                    var methodCoder             = method.Key.Method.IsAsync ? method.Key.Method.NewCoder() : x;

                    Coder codeInterceptorInstance(Coder interceptorInstanceCoder)
                    {
                        interceptorInstanceCoder.SetValue(item.Interceptor, z => z.NewObj(item.Attribute));
                        if (item.HasSyncRootInterface)
                        {
                            interceptorInstanceCoder.Load <ICasting>(item.Interceptor).As(BuilderTypes.ISyncRoot).To <ICallMethod <CallCoder> >().Call(BuilderTypes.ISyncRoot.GetMethod_set_SyncRoot(), method.SyncRoot);
                        }

                        ModuleWeaver.ImplementAssignMethodAttribute(builder, method.Items[i].AssignMethodAttributeInfos, item.FieldOrVariable, item.Attribute.Attribute.Type, interceptorInstanceCoder);
                        return(interceptorInstanceCoder);
                    }

                    if (alwaysCreateNewInstance)
                    {
                        codeInterceptorInstance(methodCoder);
                    }
                    else
                    {
                        methodCoder.If(y => y.Load <IRelationalOperators>(item.Interceptor).IsNull(), y => codeInterceptorInstance(y));
                    }

                    if (method.Key.Method.IsAsync)
                    {
                        methodCoder.Insert(InsertionPosition.Beginning);
                    }
                    item.Attribute.Remove();
                }

                return(x);
            });

            if (hasSimpleMethodInterceptors)
            {
                var simpleMethodInterceptors = method.Items.Where(x => x.HasInterfaceB).ToArray();
                coder.Context(x =>
                {
                    if (method.Key.AsyncMethod != null)
                    {
                        x.If(num => num.Load(method.Key.Method.AsyncMethodHelper.StateVariable).Is(-1), then =>
                             ImplementOnEnterMethod(coder, x, then, method, attributedMethod, simpleMethodInterceptors, @interface => @interface.InterfaceB.GetMethod_OnEnter()));
                    }
                    else
                    {
                        ImplementOnEnterMethod(coder, x, method, attributedMethod, simpleMethodInterceptors, @interface => @interface.InterfaceB.GetMethod_OnEnter());
                    }

                    if (!hasFullMethodInterceptors)
                    {
                        return(x.OriginalBody());
                    }

                    return(x);
                });
            }

            var fullMethodInterceptors = method.Items.Where(x => x.HasInterfaceA).ToArray();
            if (hasFullMethodInterceptors)
            {
                if (method.Key.AsyncMethod != null)
                {
                    coder.Context(x => x.If(num => num.Load(method.Key.Method.AsyncMethodHelper.StateVariable).Is(-1), then =>
                                            ImplementOnEnterMethod(coder, x, then, method, attributedMethod, fullMethodInterceptors, @interface => @interface.InterfaceA.GetMethod_OnEnter()))
                                  .OriginalBody());
                }
                else
                {
                    coder.Try(x =>
                    {
                        ImplementOnEnterMethod(coder, x, method, attributedMethod, fullMethodInterceptors, @interface => @interface.InterfaceA.GetMethod_OnEnter());
                        return(x.OriginalBody());
                    })
                    .Catch(BuilderTypes.Exception.BuilderType, (eCoder, e) => eCoder.If(x =>
                    {
                        var or = x.Load <ICallMethod <BooleanExpressionCallCoder> >(fullMethodInterceptors[0].FieldOrVariable).Call(fullMethodInterceptors[0].InterfaceA.GetMethod_OnException(), e());
                        for (int i = 1; i < fullMethodInterceptors.Length; i++)
                        {
                            or.Or(y => y.Load <ICallMethod <CallCoder> >(fullMethodInterceptors[i].FieldOrVariable).Call(fullMethodInterceptors[i].InterfaceA.GetMethod_OnException(), e()));
                        }

                        return(or.Is(true));
                    }, then => eCoder.NewCoder().Rethrow()).DefaultValue().Return())
                    .Finally(x => ImplementOnExitMethod(x, method, fullMethodInterceptors))
                    .EndTry();
                }
            }

            coder.Return().Replace();

            if (method.Key.AsyncMethod != null && hasFullMethodInterceptors)
            {
                // Special case for async methods
                var exceptionBlock = method.Key.Method.AsyncMethodHelper.GetAsyncStateMachineExceptionBlock();
                targetedMethod
                .NewCoder().Context(context =>
                {
                    var exceptionVariable = method.Key.Method.AsyncMethodHelper.GetAsyncStateMachineExceptionVariable();

                    return(context.If(x =>
                    {
                        var or = x.Load(fullMethodInterceptors[0].FieldOrVariable as Field).Call(fullMethodInterceptors[0].InterfaceA.GetMethod_OnException(), exceptionVariable);

                        for (int i = 1; i < fullMethodInterceptors.Length; i++)
                        {
                            or.Or(y => y.Load(fullMethodInterceptors[i].FieldOrVariable as Field).Call(fullMethodInterceptors[i].InterfaceA.GetMethod_OnException(), exceptionVariable));
                        }

                        return or.Is(false);
                    }, x => x.Jump(exceptionBlock.Item1.End)));
                })
                .Insert(InsertionAction.After, exceptionBlock.Item1.Beginning);

                targetedMethod
                .NewCoder().Context(x => ImplementOnExitMethod(x, method, fullMethodInterceptors))
                .Insert(InsertionAction.Before, exceptionBlock.Item1.End.Previous);

                targetedMethod
                .NewCoder().Context(context => ImplementOnExitMethod(context, method, fullMethodInterceptors))
                .Insert(InsertionAction.After, exceptionBlock.Item1.End);
            }
        }
        ;
    }
Exemplo n.º 47
0
    public List <Instruction> MakeCode()
    {
        if (!IsEnd)
        {
            var codes = new List <Instruction>
            {
                Start,
                Processor.Create(OpCodes.Ldc_I4, Cmd),
                Processor.Create(OpCodes.Bne_Un_S, Next),
                Processor.Create(OpCodes.Ldarg_0)
            };

            int i = 0;
            foreach (var parmeter in Method.Parameters)
            {
                codes.Add(Processor.Create(OpCodes.Ldarg_2));
                codes.Add(Processor.Create(OpCodes.Ldc_I4, i));
                codes.Add(Processor.Create(OpCodes.Ldelem_Ref));
                ModuleWeaver.Convert(Processor, codes, ModuleWeaver.ModuleDefinition.ImportReference(typeof(object)), parmeter.ParameterType, true);
                i++;
            }

            codes.Add(Processor.Create(OpCodes.Call, Method));

            if (Method.ReturnType.Name != "Void")
            {
                codes.Add(Processor.Create(OpCodes.Ret));
            }
            else
            {
                codes.Add(End);
                codes.Add(Processor.Create(OpCodes.Ret));
            }

            int size = 0;
            foreach (var il in codes)
            {
                size += il.GetSize();
            }

            if (size > 120)
            {
                codes[2] = Processor.Create(OpCodes.Bne_Un, Next);
            }

            return(codes);
        }
        else
        {
            var codes = new List <Instruction>
            {
                Start,
                Processor.Create(OpCodes.Ldc_I4, Cmd),
                Processor.Create(OpCodes.Bne_Un_S, End),
                Processor.Create(OpCodes.Ldarg_0)
            };

            int i = 0;
            foreach (var parmeter in Method.Parameters)
            {
                codes.Add(Processor.Create(OpCodes.Ldarg_2));
                codes.Add(Processor.Create(OpCodes.Ldc_I4, i));
                codes.Add(Processor.Create(OpCodes.Ldelem_Ref));
                ModuleWeaver.Convert(Processor, codes, ModuleWeaver.ModuleDefinition.ImportReference(typeof(object)), parmeter.ParameterType, true);
                i++;
            }



            codes.Add(Processor.Create(OpCodes.Call, Method));

            if (Method.ReturnType.Name != "Void")
            {
                codes.Add(Processor.Create(OpCodes.Ret));
            }

            int size = 0;
            foreach (var il in codes)
            {
                size += il.GetSize();
            }

            if (size > 120)
            {
                codes[2] = Processor.Create(OpCodes.Bne_Un, End);
            }

            codes.Add(End);
            codes.Add(Processor.Create(OpCodes.Ret));

            return(codes);
        }
    }
Exemplo n.º 48
0
        void RuntimeWeaver()
        {
            var weaving = new ModuleWeaver();

            weaving.ExecuteTestRun(System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), "AssemblyToProcess.dll"));
        }
Exemplo n.º 49
0
        public static Assembly Weave(string code)
        {
            SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(code);

            string[] assemblyPaths =
            {
                typeof(Exception).Assembly.Location,
                typeof(DependencyObject).Assembly.Location,
                typeof(DependencyPropertyAttribute).Assembly.Location,
                typeof(FrameworkPropertyMetadataOptions).Assembly.Location,
                typeof(Console).GetTypeInfo().Assembly.Location,
                Path.Combine(Path.GetDirectoryName(typeof(System.Runtime.GCSettings).GetTypeInfo().Assembly.Location), "System.Runtime.dll")
            };

            PortableExecutableReference[] references = assemblyPaths.Select(x => MetadataReference.CreateFromFile(x)).ToArray();

            CSharpCompilation compilation = CSharpCompilation.Create(
                Guid.NewGuid() + ".dll",
                new[] { syntaxTree },
                references,
                new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

            using (MemoryStream stream = new MemoryStream())
            {
                EmitResult result = compilation.Emit(stream);

                if (!result.Success)
                {
                    Console.Error.WriteLine("Compilation failed!");

                    IEnumerable <Diagnostic> failures = result.Diagnostics.Where(diagnostic =>
                                                                                 diagnostic.IsWarningAsError ||
                                                                                 diagnostic.Severity == DiagnosticSeverity.Error);

                    foreach (Diagnostic diagnostic in failures)
                    {
                        Console.Error.WriteLine("\t{0}: {1}", diagnostic.Id, diagnostic.GetMessage());
                    }

                    Assert.That(result.Success);
                }

                stream.Seek(0, SeekOrigin.Begin);

                using (MemoryStream conversionStream = new MemoryStream())
                    using (ModuleDefinition module = ModuleDefinition.ReadModule(stream, new ReaderParameters {
                        InMemory = true
                    }))
                    {
                        ModuleWeaver weavingTask = new ModuleWeaver
                        {
                            ModuleDefinition = module
                        };

                        weavingTask.Execute();
                        module.Write(conversionStream);
                        conversionStream.Seek(0, SeekOrigin.Begin);

                        using (FileStream fileStream = File.Create($"{Guid.NewGuid()}.dll"))
                        {
                            conversionStream.CopyToAsync(fileStream);
                            conversionStream.Seek(0, SeekOrigin.Begin);
                        }

                        return(Assembly.Load(conversionStream.ToArray()));
                    }
            }
        }
Exemplo n.º 50
0
    public FSharpTest()
    {
        var weavingTask = new ModuleWeaver();

        testResult = weavingTask.ExecuteTestRun("AssemblyFSharp.dll", runPeVerify: false);
    }
Exemplo n.º 51
0
    public AssemblyWithBaseInDifferentModuleTests()
    {
        var weavingTask = new ModuleWeaver();

        testResult = weavingTask.ExecuteTestRun("AssemblyWithBaseInDifferentModule.dll", ignoreCodes: new[] { "0x80131869" });
    }
Exemplo n.º 52
0
        static AbleToWeaveTest()
        {
            var weavingTask = new ModuleWeaver();

            TestResult = weavingTask.ExecuteTestRun("AssemblyToProcess.dll", false);
        }
    public TypeFilterTests()
    {
        var weavingTask = new ModuleWeaver();

        testResult = weavingTask.ExecuteTestRun("AssemblyWithTypeFilter.dll");
    }
Exemplo n.º 54
0
 private static TypeReference Resolve(this ModuleWeaver weaver, string typename)
 => weaver.ModuleDefinition.ImportReference(weaver.FindTypeDefinition(typename) ?? throw new WeavingException($"Couldnt find {typename}!"));
        static Weaver_Test()
        {
            var weavingTask = new ModuleWeaver();

            testResult = weavingTask.ExecuteTestRun("AssemblyToProcess.dll");
        }
Exemplo n.º 56
0
    public AssemblyInfo GetAssembly(string testCaseName, string configString)
    {
        if (!_assemblies.ContainsKey(configString))
        {
            var type = typeof(DummyDependencyInjectionClass);

            var assemblyInfo = new AssemblyInfo
            {
                BeforeAssemblyPath = type.GetAssemblyEx().Location
            };

            var rootDirectory     = Directory.GetParent(assemblyInfo.BeforeAssemblyPath).FullName;
            var testCaseDirectory = Path.Combine(rootDirectory, testCaseName);
            Directory.CreateDirectory(testCaseDirectory);

            assemblyInfo.AfterAssemblyPath = Path.Combine(testCaseDirectory, Path.GetFileName(assemblyInfo.BeforeAssemblyPath));

            var oldPdb = Path.ChangeExtension(assemblyInfo.BeforeAssemblyPath, "pdb");
            var newPdb = Path.ChangeExtension(assemblyInfo.AfterAssemblyPath, "pdb");
            if (File.Exists(oldPdb))
            {
                File.Copy(oldPdb, newPdb, true);
            }

            Debug.WriteLine("Weaving assembly on-demand from '{0}' to '{1}'", assemblyInfo.BeforeAssemblyPath, assemblyInfo.AfterAssemblyPath);

            var assemblyResolver = new TestAssemblyResolver();
            //assemblyResolver.AddSearchDirectory(testCaseDirectory);
            //assemblyResolver.AddSearchDirectory(rootDirectory);

            var metadataResolver = new MetadataResolver(assemblyResolver);

            var readerParameters = new ReaderParameters
            {
                AssemblyResolver = assemblyResolver,
                MetadataResolver = metadataResolver,
                ReadSymbols      = File.Exists(oldPdb),
            };

            using (var moduleDefinition = ModuleDefinition.ReadModule(assemblyInfo.BeforeAssemblyPath, readerParameters))
            {
                // Important note: the test project can be on a completely different location (especially on a build agent)
                var projectName = Path.GetFileName(assemblyInfo.BeforeAssemblyPath).Replace(".dll", string.Empty);

                // Check 1: fixed location from test
                var relativeCsProjectFilePath = Path.Combine(Directory.GetParent(assemblyInfo.BeforeAssemblyPath).FullName, "..", "..", "..", "..", "src", projectName, $"{projectName}.csproj");
                var csProjectFilePath         = Path.GetFullPath(relativeCsProjectFilePath);

                if (!File.Exists(csProjectFilePath))
                {
                    // Check 2: Check 2 directories up, then search for the project file (happens on a build agent)
                    var searchDirectory = Path.Combine(Directory.GetParent(assemblyInfo.BeforeAssemblyPath).FullName, "..", "..", "..", "Source");
                    var searchFileName  = $"{projectName}.csproj";
                    csProjectFilePath = Directory.GetFiles(searchDirectory, searchFileName, SearchOption.AllDirectories).FirstOrDefault();
                }

                if (!File.Exists(csProjectFilePath))
                {
                    throw new System.Exception($"Project file '{csProjectFilePath}' does not exist, make sure to check the paths since this is required for the unit tests");
                }

                var weavingTask = new ModuleWeaver
                {
                    Config           = XElement.Parse(configString),
                    ModuleDefinition = moduleDefinition,
                    AssemblyResolver = assemblyResolver,
                    ProjectFilePath  = csProjectFilePath,
                    LogError         = (x) =>
                    {
                        assemblyInfo.Errors.Add(x);
                    },
                };

                weavingTask.Execute();
                moduleDefinition.Write(assemblyInfo.AfterAssemblyPath);
            }

            //        if (Debugger.IsAttached)
            //        {
            //#if DEBUG
            //            var output = "debug";
            //#else
            //            var output = "release";
            //#endif

            //            var targetFile = $@"C:\Source\Catel.Fody\output\{output}\Catel.Fody.Tests\Catel.Fody.TestAssembly2.dll";
            //            var targetDirectory = Path.GetDirectoryName(targetFile);
            //            Directory.CreateDirectory(targetDirectory);
            //            File.Copy(AfterAssemblyPath, targetFile, true);
            //        }

            assemblyInfo.Assembly = Assembly.LoadFile(assemblyInfo.AfterAssemblyPath);

            _assemblies[configString] = assemblyInfo;
        }

        return(_assemblies[configString]);
    }
Exemplo n.º 57
0
    private static void AddPropertySetterInterception(
        Builder builder,
        BuilderTypePropertyInterceptionInfo propertyInterceptionInfo,
        PropertyBuilderInfo member,
        Field propertyField,
        Method actionObjectCtor,
        Method propertySetter,
        Dictionary <string, Field> interceptorFields)
    {
        var syncRoot = BuilderTypes.ISyncRoot;
        var legalSetterInterceptors = member.InterceptorInfos.Where(x => x.InterfaceSetter != null).ToArray();

        member.Property.Setter
        .NewCoder()
        .Context(context =>
        {
            if (member.HasInitializer)
            {
                return(context);
            }

            for (int i = 0; i < legalSetterInterceptors.Length; i++)
            {
                var item = legalSetterInterceptors[i];
                var alwaysCreateNewInstance = item.InterceptorInfo.AlwaysCreateNewInstance && item.InterfaceInitializer == null;
                var fieldOrVariable         = interceptorFields[item.Attribute.Identification] as CecilatorBase ??
                                              context.AssociatedMethod.GetOrCreateVariable(item.Attribute.Attribute.Type, item.Attribute.Identification);

                Coder implementInterceptorInitialization(Coder coder)
                {
                    coder.SetValue(fieldOrVariable, x => x.NewObj(item.Attribute));

                    if (item.HasSyncRootInterface)
                    {
                        coder.Load <ICasting>(fieldOrVariable).As(syncRoot.BuilderType.Import()).To <ICallMethod <CallCoder> >().Call(syncRoot.GetMethod_set_SyncRoot(), member.SyncRoot);
                    }

                    ModuleWeaver.ImplementAssignMethodAttribute(builder, legalSetterInterceptors[i].AssignMethodAttributeInfos, fieldOrVariable, item.Attribute.Attribute.Type, coder);

                    return(coder);
                }

                if (alwaysCreateNewInstance)
                {
                    implementInterceptorInitialization(context);
                }
                else
                {
                    context.If(x => x.Load <IRelationalOperators>(fieldOrVariable).IsNull(), then => implementInterceptorInitialization(then));
                }

                item.Attribute.Remove();
            }

            return(context.If(x => x.Load(propertyField).IsNull(), then =>
                              then.SetValue(propertyField, x =>
                                            x.NewObj(propertyInterceptionInfo.GetMethod_ctor(),
                                                     member.Property.Getter,
                                                     member.Property.Setter,
                                                     member.Property.Name,
                                                     member.Property.ReturnType,
                                                     CodeBlocks.This,
                                                     member.Property.ReturnType.IsArray || member.Property.ReturnType.Implements(typeof(IEnumerable)) ? member.Property.ReturnType.ChildType : null,
                                                     propertySetter == null ? null : x.NewCoder().NewObj(actionObjectCtor, propertySetter.ThisOrNull(), propertySetter)))));
        })
        .Try(@try =>
        {
            if (member.Property.BackingField == null)
            {
                // If we don't have a backing field, we will try getting the value from the
                // getter itself... But in this case we have to watch out that we don't accidentally code a
                // StackOverFlow
                var oldvalue = member.Property.Getter == null ? null : member.Property.Setter.GetOrCreateVariable(member.Property.ReturnType);

                if (oldvalue != null)
                {
                    var getter = member.Property.Getter.Copy();
                    @try.SetValue(oldvalue, y => y.Call(getter));
                }

                for (int i = 0; i < legalSetterInterceptors.Length; i++)
                {
                    var item = legalSetterInterceptors[i];
                    var alwaysCreateNewInstance = item.InterceptorInfo.AlwaysCreateNewInstance && item.InterfaceInitializer == null;
                    var fieldOrVariable         = interceptorFields[item.Attribute.Identification] as CecilatorBase ?? @try.AssociatedMethod.GetVariable(item.Attribute.Identification);
                    @try.If(x =>
                            x.Load <ICasting>(fieldOrVariable)
                            .As(legalSetterInterceptors[i].InterfaceSetter)
                            .To <ICallMethod <BooleanExpressionCallCoder> >()
                            .Call(item.InterfaceSetter.GetMethod_OnSet(), propertyField, oldvalue, CodeBlocks.GetParameter(0))
                            .To <IRelationalOperators>()
                            .Is(false), then => then.OriginalBody(true));
                }
            }
            else
            {
                @try.If(x => x.And(legalSetterInterceptors,
                                   (coder, item, i) =>
                {
                    var fieldOrVariable = interceptorFields[item.Attribute.Identification] as CecilatorBase ?? @try.AssociatedMethod.GetVariable(item.Attribute.Identification);
                    return(coder.Load <ICasting>(fieldOrVariable)
                           .As(legalSetterInterceptors[i].InterfaceSetter)
                           .To <ICallMethod <BooleanExpressionCallCoder> >()
                           .Call(item.InterfaceSetter.GetMethod_OnSet(), propertyField, member.Property.BackingField, CodeBlocks.GetParameter(0)));
                }).Is(false), then => then.OriginalBody());
            }

            return(@try);
        })
        .Catch(typeof(Exception), (ex, e) =>
        {
            return(ex.If(x => x.Or(legalSetterInterceptors,
                                   (coder, y, i) =>
            {
                var fieldOrVariable = interceptorFields[y.Attribute.Identification] as CecilatorBase ?? ex.AssociatedMethod.GetVariable(y.Attribute.Identification);
                return coder.Load <ICasting>(fieldOrVariable)
                .As(legalSetterInterceptors[i].InterfaceSetter)
                .To <ICallMethod <BooleanExpressionCallCoder> >()
                .Call(legalSetterInterceptors[i].InterfaceSetter.GetMethod_OnException(), e());
            }).Is(true), then => ex.NewCoder().Rethrow())
                   .DefaultValue()
                   .Return());
        })
        .Finally(x =>
        {
            for (int i = 0; i < legalSetterInterceptors.Length; i++)
            {
                var item            = legalSetterInterceptors[i];
                var fieldOrVariable = interceptorFields[item.Attribute.Identification] as CecilatorBase ?? x.AssociatedMethod.GetVariable(item.Attribute.Identification);
                x.Load <ICasting>(fieldOrVariable)
                .As(legalSetterInterceptors[i].InterfaceSetter)
                .To <ICallMethod <CallCoder> >()
                .Call(legalSetterInterceptors[i].InterfaceSetter.GetMethod_OnExit());
            }

            return(x);
        })
        .EndTry()
        .Return()
        .Replace();
    }
 public EqualityCheckWeaver(PropertyData propertyData, TypeDefinition typeDefinition, ModuleWeaver typeEqualityFinder)
 {
     this.propertyData       = propertyData;
     this.typeDefinition     = typeDefinition;
     this.typeEqualityFinder = typeEqualityFinder;
 }
    public void Run()
    {
        var memberMappings = ModuleWeaver.GetMappings(DefinitionFinder.FindType <Model>()).ToList();

        Assert.IsNull(memberMappings.Single().FieldDefinition);
    }
    public void CanDetectStackOverflow()
    {
        var weavingTask = new ModuleWeaver();

        Assert.Throws <WeavingException>(() => { weavingTask.ExecuteTestRun("AssemblyWithStackOverflow.dll"); });
    }