Exemple #1
0
 static InitializeCallTests()
 {
     testResult = WeavingHelper.CreateIsolatedAssemblyCopy("AssemblyToProcess.dll",
                                                           "<Costura />",
                                                           new[] { "AssemblyToReference.dll", "AssemblyToReferencePreEmbedded.dll", "ExeToReference.exe" },
                                                           "InitializeCall");
 }
 static ReferenceCasingTests()
 {
     testResult = WeavingHelper.CreateIsolatedAssemblyCopy("AssemblyToProcess.dll",
                                                           "<Costura IncludeAssemblies='assemblytoreference|exetoreference' />",
                                                           new[] { "AssemblyToReference.dll", "AssemblyToReferencePreEmbedded.dll", "ExeToReference.exe" },
                                                           "InitializeCall");
 }
Exemple #3
0
 static InitializeCallWithoutModuleInitTest()
 {
     testResult = WeavingHelper.CreateIsolatedAssemblyCopy("AssemblyToProcess.dll",
                                                           "<Costura LoadAtModuleInit='false' />",
                                                           new[] { "AssemblyToReference.dll", "AssemblyToReferencePreEmbedded.dll", "ExeToReference.exe" },
                                                           "InitializeCallWithoutModuleInit");
 }
Exemple #4
0
 public void FailsToWeave()
 {
     Assert.Throws <WeavingException>(() =>
                                      WeavingHelper.CreateIsolatedAssemblyCopy("AssemblyWithoutInitialize.dll",
                                                                               "<Costura LoadAtModuleInit='false' />",
                                                                               new[] { "AssemblyToReference.dll", "AssemblyToReferencePreEmbedded.dll", "ExeToReference.exe" },
                                                                               "NoInitialize"));
 }
        private Instruction EmitInitializeCall(ProcessorContext context, ILProcessor il)
        {
            var initializedType = type.HasGenericParameters ? WeavingHelper.CreateGenericInstance(type) : type;
            var start           = il.Create(OpCodes.Ldarg_0);

            il.Append(start);
            il.Emit(OpCodes.Ldtoken, initializedType);
            il.Emit(OpCodes.Call, context.References.TypeGetTypeFromHandle);
            il.Emit(OpCodes.Call, context.References.PersistentInitialize);
            return(start);
        }
 public void ThrowsForMissingReference()
 {
     // Note: this will throw WeavingException because References is null, but should actually
     // log an error about the missing assembly
     Assert.Throws <WeavingException>(() =>
     {
         WeavingHelper.CreateIsolatedAssemblyCopy("AssemblyToProcess.dll",
                                                  "<Costura IncludeAssemblies='AssemblyToReference|AssemblyToReferencePreEmbedded|ExeToReference|MissingAssembly' />",
                                                  new[] { "AssemblyToReference.dll", "AssemblyToReferencePreEmbedded.dll", "ExeToReference.exe" },
                                                  "InitializeCall");
     });
 }
 static CultureResourceTests()
 {
     testResult = WeavingHelper.CreateIsolatedAssemblyCopy("ExeToProcess.exe",
                                                           "<Costura />",
                                                           new[]
     {
         "AssemblyToReference.dll",
         "de\\AssemblyToReference.resources.dll",
         "fr\\AssemblyToReference.resources.dll",
         "AssemblyToReferencePreEmbedded.dll",
         "ExeToReference.exe"
     }, "Culture");
 }
Exemple #8
0
    public void WeavesWildcards()
    {
        var wildcardWeave = WeavingHelper.CreateIsolatedAssemblyCopy("ExeToProcess.exe",
                                                                     "<Costura IncludeAssemblies=\"AssemblyToReference*\"/>",
                                                                     new[] { "AssemblyToReference.dll", "AssemblyToReferenceMixed.dll" }, "WildcardWeave");

        var referencedAssemblies = wildcardWeave.Assembly.GetReferencedAssemblies().Select(x => x.Name).ToList();

        Assert.Contains("AssemblyToReference", referencedAssemblies);
        Assert.Contains("AssemblyToReferencePreEmbedded", referencedAssemblies);

        var instance = wildcardWeave.GetInstance("ClassToTest");

        Assert.AreEqual("Hello", instance.Simple());
        Assert.AreEqual("Hello", instance.SimplePreEmbed());
    }
Exemple #9
0
        private MethodDefinition DefineConstructor(ProcessorContext context)
        {
            var baseConstructor = GetBaseConstructor(context);
            var method          = new MethodDefinition(WellKnown.Constructor, ConstructorAttributes, voidType)
            {
                HasThis = true
            };

            DefineParameters(method);
            WeavingHelper.MarkAsCompilerGenerated(context, method);
            var il = method.Body.GetILProcessor();

            WeavingHelper.EmitLoadArguments(il, signature.Length + 1);
            il.Emit(OpCodes.Call, baseConstructor);
            il.Emit(OpCodes.Ret);
            targetType.Methods.Add(method);
            return(method);
        }
        public LoggingImplementationTypeBuilder( ModuleDeclaration module )
        {
            this.module = module;
            this.categoryFields = new Dictionary<string, FieldDefDeclaration>();
            this.wrapperMethods = new Dictionary<IMethod, MethodDefDeclaration>();

            this.stringFormatArrayMethod = module.FindMethod( module.Cache.GetIntrinsic( IntrinsicType.String ), "Format",
                                                              method => method.Parameters.Count == 2 &&
                                                                        IntrinsicTypeSignature.Is( method.Parameters[0].ParameterType, IntrinsicType.String ) &&
                                                                        method.Parameters[1].ParameterType.BelongsToClassification( TypeClassifications.Array ) );

            this.traceWriteLineMethod = module.FindMethod( module.Cache.GetType( typeof(System.Diagnostics.Trace) ), "WriteLine",
                                                           method => method.Parameters.Count == 1 &&
                                                                     IntrinsicTypeSignature.Is( method.Parameters[0].ParameterType, IntrinsicType.String ) );

            this.weavingHelper = new WeavingHelper( module );
            this.implementationType = this.CreateContainingType();
            this.isLoggingField = this.CreateIsLoggingField();
        }
        public LoggingImplementationTypeBuilder(ModuleDeclaration module)
        {
            this.module         = module;
            this.categoryFields = new Dictionary <string, FieldDefDeclaration>();
            this.wrapperMethods = new Dictionary <IMethod, MethodDefDeclaration>();

            this.stringFormatArrayMethod = module.FindMethod(module.Cache.GetIntrinsic(IntrinsicType.String), "Format",
                                                             method => method.Parameters.Count == 2 &&
                                                             IntrinsicTypeSignature.Is(method.Parameters[0].ParameterType, IntrinsicType.String) &&
                                                             method.Parameters[1].ParameterType.BelongsToClassification(TypeClassifications.Array));

            this.traceWriteLineMethod = module.FindMethod(module.Cache.GetType(typeof(System.Diagnostics.Trace)), "WriteLine",
                                                          method => method.Parameters.Count == 1 &&
                                                          IntrinsicTypeSignature.Is(method.Parameters[0].ParameterType, IntrinsicType.String));

            this.weavingHelper      = new WeavingHelper(module);
            this.implementationType = this.CreateContainingType();
            this.isLoggingField     = this.CreateIsLoggingField();
        }
        private Tuple <Instruction, Instruction> EmitExceptionHandler(ProcessorContext context, ILProcessor il, TypeReference exceptionType)
        {
            var initializedType = type.HasGenericParameters ? WeavingHelper.CreateGenericInstance(type) : type;
            var variables       = constructor.Body.Variables;
            var instructions    = constructor.Body.Instructions;
            var variableIndex   = variables.Count;

            variables.Add(new VariableDefinition(exceptionType));
            il.Emit(OpCodes.Stloc, variableIndex);
            var start = instructions[instructions.Count - 1];

            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ldtoken, initializedType);
            il.Emit(OpCodes.Call, context.References.TypeGetTypeFromHandle);
            il.Emit(OpCodes.Ldloc, variableIndex);
            il.Emit(OpCodes.Call, context.References.PersistentInitializationError);
            il.Emit(OpCodes.Rethrow);
            il.Emit(OpCodes.Nop);
            var end = instructions[instructions.Count - 1];

            return(Tuple.Create(start, end));
        }
Exemple #13
0
        private void DefineFactoryMethod(ProcessorContext context, MethodReference constructor)
        {
            var returnType = (TypeReference)targetType;

            if (targetType.HasGenericParameters)
            {
                returnType  = WeavingHelper.CreateGenericInstance(targetType);
                constructor = new MethodReference(WellKnown.Constructor, voidType, returnType)
                {
                    HasThis = true
                };
                DefineParameters(constructor);
            }
            var method = new MethodDefinition(WellKnown.FactoryMethod, FactoryMethodAttributes, returnType);

            DefineParameters(method);
            WeavingHelper.MarkAsCompilerGenerated(context, method);
            var il = method.Body.GetILProcessor();

            WeavingHelper.EmitLoadArguments(il, signature.Length);
            il.Emit(OpCodes.Newobj, constructor);
            il.Emit(OpCodes.Ret);
            targetType.Methods.Add(method);
        }
 public static void Get_MethodInfo(this InstructionWriter writer, IMethod method, WeavingHelper weavingHelper)
 {
     writer.Get_RuntimeMethod(method, weavingHelper);
     writer.Cast_ToType(method.Module.FindType(typeof(MethodInfo)));
 }
 static TempFileTests()
 {
     testResult = WeavingHelper.CreateIsolatedAssemblyCopy("ExeToProcess.exe",
                                                           "<Costura CreateTemporaryAssemblies='true' />",
                                                           new[] { "AssemblyToReference.dll", "AssemblyToReferencePreEmbedded.dll", "ExeToReference.exe" }, "TempFile");
 }
        public static void ImplementRemoveOn(
            this EventDeclaration theEvent,
            TypeDefDeclaration type,
            IField field,
            WeavingHelper weavingHelper = null,
            MethodAttributes methodAttributes =
                MethodAttributes.Public | MethodAttributes.HideBySig
                | MethodAttributes.Virtual | MethodAttributes.Final 
                | MethodAttributes.NewSlot | MethodAttributes.SpecialName)
        {
            var module = type.Module;
            weavingHelper = weavingHelper ?? new WeavingHelper(module);
            var pEWeavingHelper = module.Cache.GetItem(() => new PostEdgeWeaverAssets(module));

            var method = new MethodDefDeclaration {
                Attributes = methodAttributes,
                Name = "remove_" + theEvent.Name,
                CallingConvention = CallingConvention.HasThis
            };
            type.Methods.Add(method);
            weavingHelper.AddCompilerGeneratedAttribute(method.CustomAttributes);
            var parameter = new ParameterDeclaration {
                Name = "value",
                ParameterType = theEvent.EventType,
            };
            method.Parameters.Add(parameter);

            var methodBody = new MethodBodyDeclaration();
            methodBody.EnsureWritableLocalVariables();
            var instructionBlock = methodBody.CreateInstructionBlock();
            var initSequence = methodBody.CreateInstructionSequence();
            var loopSequence = methodBody.CreateInstructionSequence();
            var endSequence = methodBody.CreateInstructionSequence();
            instructionBlock.AddInstructionSequence(initSequence, NodePosition.After, null);
            instructionBlock.AddInstructionSequence(loopSequence, NodePosition.After, initSequence);
            instructionBlock.AddInstructionSequence(endSequence, NodePosition.After, loopSequence);
            methodBody.RootInstructionBlock = instructionBlock;
            method.MethodBody = methodBody;
            methodBody.CreateLocalVariable(theEvent.EventType);
            methodBody.CreateLocalVariable(theEvent.EventType);
            methodBody.CreateLocalVariable(theEvent.EventType);
            methodBody.CreateLocalVariable(module.Cache.GetIntrinsic(typeof(bool)));

            var writer = new InstructionWriter();
            //Initialize
            writer.AttachInstructionSequence(initSequence);

            //PropertyChangedHandler handler = this.PropertyChanged
            writer.EmitInstruction(OpCodeNumber.Ldarg_0);           //Get the this pointer
            writer.EmitInstructionField(OpCodeNumber.Ldfld, field); //Get the event's field
            writer.EmitInstruction(OpCodeNumber.Stloc_0);           //store into the first local variable
            writer.DetachInstructionSequence();

            //Loop
            //do {
            writer.AttachInstructionSequence(loopSequence);

            //PropertyChangedHandler handler2 = handler;
            writer.EmitInstruction(OpCodeNumber.Ldloc_0);
            writer.EmitInstruction(OpCodeNumber.Stloc_1);

            //PropertyChangedHandler handler3 = System.Delegate.Remove(handler2, value)
            writer.EmitInstruction(OpCodeNumber.Ldloc_1);
            writer.EmitInstruction(OpCodeNumber.Ldarg_1);
            writer.EmitInstructionMethod(OpCodeNumber.Call, pEWeavingHelper.DelegateRemoveMethod);
            writer.EmitInstructionType(OpCodeNumber.Castclass, theEvent.EventType);
            writer.EmitInstruction(OpCodeNumber.Stloc_2);

            //handler = System.Threading.Interlocked.CompareExchnage<PropertyChangedEventHandler>(ref this.PropertyChtyChanged, handler3, handler2);
            var compareExchangeMethodT = pEWeavingHelper.CompareExchangeMethod;
            var compareExchangeMethod = compareExchangeMethodT.GetGenericInstance(module, theEvent.EventType);
            writer.EmitInstruction(OpCodeNumber.Ldarg_0);           //Load this
            writer.EmitInstructionField(OpCodeNumber.Ldflda, field);
            writer.EmitInstruction(OpCodeNumber.Ldloc_2);
            writer.EmitInstruction(OpCodeNumber.Ldloc_1);
            writer.EmitInstructionMethod(OpCodeNumber.Call, compareExchangeMethod);
            writer.EmitInstruction(OpCodeNumber.Stloc_0);

            //flag = handler != handler2;
            writer.EmitInstruction(OpCodeNumber.Ldloc_0);
            writer.EmitInstruction(OpCodeNumber.Ldloc_1);
            writer.EmitInstruction(OpCodeNumber.Ceq);
            writer.EmitInstruction(OpCodeNumber.Ldc_I4_0);
            writer.EmitInstruction(OpCodeNumber.Ceq);
            writer.EmitInstruction(OpCodeNumber.Stloc_3);

            //} while (flag);
            writer.EmitInstruction(OpCodeNumber.Ldloc_3);
            writer.EmitBranchingInstruction(OpCodeNumber.Brtrue_S, loopSequence);

            writer.DetachInstructionSequence();

            //End
            writer.AttachInstructionSequence(endSequence);
            writer.EmitInstruction(OpCodeNumber.Ret);               //Exit the method
            writer.DetachInstructionSequence();

            theEvent.Members.Add(new MethodSemanticDeclaration(MethodSemantics.RemoveOn, method));
        }
Exemple #17
0
 static MixedAndNativeTests()
 {
     testResult = WeavingHelper.CreateIsolatedAssemblyCopy("ExeToProcessWithNative.exe",
                                                           "<Costura Unmanaged32Assemblies='AssemblyToReferenceMixed' />",
                                                           new[] { "AssemblyToReferenceMixed.dll" }, "MixedAndNative");
 }
 public static void Get_RuntimeType(this InstructionWriter instructionWriter, ITypeSignature type, WeavingHelper weavingHelper)
 {
     weavingHelper.GetRuntimeType(type, instructionWriter);
 }
 public LoggingImplementationTypeBuilder(ModuleDeclaration module)
 {
     this.module         = module;
     this.weavingHelper  = new WeavingHelper(module);
     this.containingType = this.CreateContainingType();
 }
 public LoggingImplementationTypeBuilder(ModuleDeclaration module)
 {
     this.module = module;
     this.weavingHelper = new WeavingHelper(module);
     this.containingType = this.CreateContainingType();
 }
 public static void Get_RuntimeMethod(this InstructionWriter instructionWriter, IMethod method, WeavingHelper weavingHelper)
 {
     var module = method.Module;
     if (!method.IsGenericDefinition && !method.DeclaringType.IsGenericDefinition)
     {
         instructionWriter.EmitInstructionMethod(OpCodeNumber.Ldtoken, method);
         instructionWriter.EmitInstructionMethod(OpCodeNumber.Call, module.Cache.GetItem(module.Cache.MethodBaseGetMethodFromHandle));
     }
     else
     {
         instructionWriter.EmitInstructionMethod(OpCodeNumber.Ldtoken, method.EnsureTypeQualifiedMethod(module));
         instructionWriter.EmitInstructionType(OpCodeNumber.Ldtoken, method.DeclaringType.GetTypeDefinition().GetCanonicalGenericInstance());
         instructionWriter.EmitInstructionMethod(OpCodeNumber.Call, module.Cache.GetItem(module.Cache.MethodBaseGetMethodFromHandle2));
     }
 }
        private void InspectProperties(ProcessorContext context, TypeInfo type)
        {
            foreach (var property in type.Definition.Properties)
            {
                var propertyInfo = new PropertyInfo(type, property);
                // only indexers has parameters and we skip them
                if (propertyInfo.AnyAccessor == null || property.HasParameters)
                {
                    continue;
                }
                propertyInfo.IsAutomatic  = autoPropertyChecker.Invoke(type.Definition, property);
                propertyInfo.IsPersistent = propertyInfo.IsInstance && property.HasAttribute(WellKnown.FieldAttribute);
                propertyInfo.IsKey        = propertyInfo.IsPersistent && property.HasAttribute(WellKnown.KeyAttribute);
                type.Properties.Add(propertyInfo.Name, propertyInfo);
            }

            var baseType = type.BaseType;

            if (baseType != null)
            {
                foreach (var property in type.Properties.Values)
                {
                    var baseProperty = baseType.FindProperty(property.Name);
                    if (baseProperty == null)
                    {
                        continue;
                    }
                    property.BaseProperty = baseProperty;
                    var thisAccessor = property.AnyAccessor;
                    var baseAccessor = baseProperty.AnyAccessor;
                    if (baseAccessor.IsVirtual && thisAccessor.IsVirtual && !thisAccessor.IsNewSlot)
                    {
                        property.IsOverride = true;
                        InheritPersistence(property, baseProperty);
                    }
                    else
                    {
                        property.IsNew = true;
                        var persistentBase = property.FindBase(p => p.IsPersistent);
                        if (persistentBase != null)
                        {
                            property.PersistentName = WeavingHelper.BuildComplexPersistentName(type, property);
                        }
                    }
                }
            }

            var propertiesToImplement = new HashSet <PropertyInfo>(type.Interfaces.SelectMany(i => i.Properties.Values));

            // Exclude explicit implementations
            foreach (var property in type.Properties.Values)
            {
                var implementedAccessor = property.AnyAccessor.Overrides.FirstOrDefault();
                if (implementedAccessor == null)
                {
                    continue;
                }
                var interfaceType           = GetType(new TypeIdentity(implementedAccessor.DeclaringType.StripGenericParameters()));
                var implementedPropertyName = WeavingHelper.GetPropertyName(implementedAccessor.Name);
                var implementedProperty     = interfaceType.FindProperty(implementedPropertyName);
                if (implementedProperty == null)
                {
                    continue;
                }
                property.ImplementedProperties.Add(implementedProperty);
                property.IsExplicitInterfaceImplementation = true;
                if (context.Language != SourceLanguage.VbNet)
                {
                    property.PersistentName = WeavingHelper.BuildComplexPersistentName(interfaceType, implementedProperty);
                }
                propertiesToImplement.Remove(implementedProperty);
                InheritPersistence(property, implementedProperty);
            }

            // Try associate remaining properties
            foreach (var property in propertiesToImplement)
            {
                PropertyInfo implementor;
                if (type.Properties.TryGetValue(property.Name, out implementor))
                {
                    implementor.ImplementedProperties.Add(property);
                    InheritPersistence(implementor, property);
                }
            }
        }