Esempio n. 1
0
            protected override void ImplementAttribute(ModuleDefinition module, TypeDefinition attribute, WellKnownTypes wellKnownTypes, CustomAttributeFactory attributeFactory)
            {
                var constructor = attribute.AddDefaultConstructor(wellKnownTypes.TypeSystem);

                attribute.CustomAttributes.Add(attributeFactory.CompilerGenerated());
                attribute.CustomAttributes.Add(new CustomAttribute(constructor));
            }
        public void AddConstructor(TypeDefinition adapterType,
                                   FieldReference targetField)
        {
            var adapterCtor      = adapterType.AddDefaultConstructor();
            var adapterParameter = new ParameterDefinition(_targetDependency);

            adapterCtor.Parameters.Add(adapterParameter);

            // HACK: Remove the ret instruction from the default constructor and replace it with
            // the field setter
            var adapterBody         = adapterCtor.Body;
            var adapterInstructions = adapterBody.Instructions.Cast <Instruction>().Where(i => i.OpCode != OpCodes.Ret).ToArray();

            adapterBody.Instructions.Clear();

            // Copy the old instructions
            var IL = adapterBody.CilWorker;

            foreach (var instruction in adapterInstructions)
            {
                IL.Append(instruction);
            }

            IL.Emit(OpCodes.Ldarg_0);
            IL.Emit(OpCodes.Ldarg, adapterParameter);
            IL.Emit(OpCodes.Stfld, targetField);
            IL.Emit(OpCodes.Ret);
        }
Esempio n. 3
0
        public void AddEmptyConstructor(TypeDefinition type)
        {
            type.AddDefaultConstructor();


            //var method = new MethodDefinition(".ctor", MethodAttributes.Public | MethodAttributes.HideBySig |
            //                                           MethodAttributes.SpecialName | MethodAttributes.RTSpecialName,
            //    mainModule.TypeSystem.Void);

            ////TODO: might need to fix this later so that PEVERIFY can verify the outputted library properly.
            //// var baseEmptyConstructor = new MethodReference(".ctor", MainModule.TypeSystem.Void, MainModule.TypeSystem.Object);// MainModule.TypeSystem.Object
            //method.Body.Instructions.Add(Instruction.Create(OpCodes.Ldarg_0));

            //if (objectTypeDef != null && objectCtor == null)
            //{
            //    var ctor = objectTypeDef.GetConstructors().FirstOrDefault();
            //    if (ctor != null)
            //        objectCtor = mainModule.Import(ctor);
            //}

            //if (objectCtor != null)
            //    method.Body.Instructions.Add(Instruction.Create(OpCodes.Call, objectCtor));

            //method.Body.Instructions.Add(Instruction.Create(OpCodes.Ret));
            //type.Methods.Add(method);
        }
Esempio n. 4
0
        /// <summary>
        /// Defines the nested constructors for the singleton type.
        /// </summary>
        /// <param name="module">The target module.</param>
        /// <param name="nestedType">The nested type.</param>
        /// <returns>The static singleton constructor.</returns>
        private static MethodDefinition DefineNestedConstructors(ModuleDefinition module, TypeDefinition nestedType)
        {
            // Define the constructor for the nested t ype
            nestedType.AddDefaultConstructor();
            var defaultConstructor = nestedType.GetDefaultConstructor();

            defaultConstructor.IsPublic = true;

            var cctor = DefineStaticConstructor(module, nestedType);

            cctor.IsPublic = true;

            return(cctor);
        }
Esempio n. 5
0
        private static TypeDefinition DefineNotNullAttribute(AssemblyDefinition assemblyDefinition, WellKnownTypes wellKnownTypes, CustomAttributeFactory attributeFactory)
        {
            var attribute = new TypeDefinition(
                @namespace: "System.Diagnostics.CodeAnalysis",
                name: "NotNullAttribute",
                TypeAttributes.NotPublic | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit,
                wellKnownTypes.Module.ImportReference(wellKnownTypes.SystemAttribute));

            attribute.AddDefaultConstructor(wellKnownTypes);
            attribute.CustomAttributes.Add(attributeFactory.AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, inherited: false));

            assemblyDefinition.MainModule.Types.Add(attribute);

            return(attribute);
        }
        private static void DefineSerializationConstructor(ModuleDefinition module, TypeDefinition targetType)
        {
            var getTypeFromHandle = module.ImportMethod <Type>("GetTypeFromHandle",
                                                               BindingFlags.Public | BindingFlags.Static);

            var parameterTypes = new[] { typeof(SerializationInfo), typeof(StreamingContext) };

            // Define the constructor signature
            var serializationCtor = targetType.AddDefaultConstructor();

            serializationCtor.AddParameters(parameterTypes);

            serializationCtor.Attributes = MethodAttributes.HideBySig | MethodAttributes.SpecialName |
                                           MethodAttributes.RTSpecialName | MethodAttributes.Public;
            var interceptorInterfaceType = module.ImportType <IInterceptor>();
            var interceptorTypeVariable  = serializationCtor.AddLocal <Type>();

            var body = serializationCtor.Body;

            body.InitLocals = true;

            var IL = serializationCtor.GetILGenerator();

            IL.Emit(OpCodes.Ldtoken, interceptorInterfaceType);
            IL.Emit(OpCodes.Call, getTypeFromHandle);
            IL.Emit(OpCodes.Stloc, interceptorTypeVariable);

            var defaultConstructor = module.ImportConstructor <object>();

            IL.Emit(OpCodes.Ldarg_0);
            IL.Emit(OpCodes.Call, defaultConstructor);

            // __interceptor = (IInterceptor)info.GetValue("__interceptor", typeof(IInterceptor));
            var getValue = module.ImportMethod <SerializationInfo>("GetValue");

            IL.Emit(OpCodes.Ldarg_0);
            IL.Emit(OpCodes.Ldarg_1);
            IL.Emit(OpCodes.Ldstr, "__interceptor");
            IL.Emit(OpCodes.Ldloc, interceptorTypeVariable);
            IL.Emit(OpCodes.Callvirt, getValue);
            IL.Emit(OpCodes.Castclass, interceptorInterfaceType);

            var setInterceptor = module.ImportMethod <IProxy>("set_Interceptor");

            IL.Emit(OpCodes.Callvirt, setInterceptor);
            ;
            IL.Emit(OpCodes.Ret);
        }
Esempio n. 7
0
        private static TypeDefinition DefineEmbeddedAttribute(AssemblyDefinition assemblyDefinition, WellKnownTypes wellKnownTypes)
        {
            var attribute = new TypeDefinition(
                @namespace: "Microsoft.CodeAnalysis",
                name: "EmbeddedAttribute",
                TypeAttributes.NotPublic | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit,
                wellKnownTypes.Module.ImportReference(wellKnownTypes.SystemAttribute));

            var constructor = attribute.AddDefaultConstructor(wellKnownTypes);

            MethodDefinition compilerGeneratedConstructor = wellKnownTypes.SystemRuntimeCompilerServicesCompilerGeneratedAttribute.Resolve().Methods.Single(method => method.IsConstructor && !method.IsStatic && method.Parameters.Count == 0);
            var customAttribute = new CustomAttribute(wellKnownTypes.Module.ImportReference(compilerGeneratedConstructor));

            attribute.CustomAttributes.Add(customAttribute);
            attribute.CustomAttributes.Add(new CustomAttribute(constructor));

            assemblyDefinition.MainModule.Types.Add(attribute);

            return(attribute);
        }
Esempio n. 8
0
        TypeDefinition CreateTypeForRemoveEvents(TypeDefinition typeDef, out MethodDefinition constructor)
        {
            var module = typeDef.Module;

            var name     = "___Type___For___RemoveEvent___";
            var nestType = typeDef.NestedTypes.FirstOrDefault(a => a.Name == name);

            if (null == nestType)
            {
                nestType          = new TypeDefinition(typeDef.Namespace, name, TypeAttributes.NestedPrivate | TypeAttributes.BeforeFieldInit | TypeAttributes.Sealed | TypeAttributes.AnsiClass);
                nestType.BaseType = module.ImportReference(typeof(object));
                typeDef.NestedTypes.Add(nestType);

                constructor = nestType.AddDefaultConstructor();
            }
            else
            {
                constructor = nestType.Methods.FirstOrDefault(a => a.IsConstructor);
            }

            return(nestType);
        }
Esempio n. 9
0
        /// <summary>
        /// Creates a proxy type using the given
        /// <paramref name="baseType"/> as the base class
        /// and ensures that the proxy type implements the given
        /// interface types.
        /// </summary>
        /// <param name="baseType">The base class from which the proxy type will be derived.</param>
        /// <param name="baseInterfaces">The list of interfaces that the proxy will implement.</param>
        /// <returns>A forwarding proxy.</returns>
        public Type CreateProxyType(Type baseType, IEnumerable <Type> baseInterfaces)
        {
            // Reuse the cached results, if possible
            Type[] originalInterfaces = baseInterfaces.ToArray();
            if (Cache != null && Cache.Contains(baseType, originalInterfaces))
            {
                return(Cache.Get(baseType, originalInterfaces));
            }

            if (!baseType.IsPublic)
            {
                throw new ArgumentException("The proxy factory can only generate proxies from public base classes.",
                                            "baseType");
            }

            bool hasNonPublicInterfaces = (from t in baseInterfaces
                                           where t.IsNotPublic
                                           select t).Count() > 0;

            if (hasNonPublicInterfaces)
            {
                throw new ArgumentException("The proxy factory cannot generate proxies from non-public interfaces.",
                                            "baseInterfaces");
            }

            #region Determine which interfaces need to be implemented

            Type actualBaseType = baseType.IsInterface ? typeof(object) : baseType;
            var  interfaces     = new HashSet <Type>(baseInterfaces);
            // Move the base type into the list of interfaces
            // if the user mistakenly entered
            // an interface type as the base type
            if (baseType.IsInterface)
            {
                interfaces.Add(baseType);
            }

            if (InterfaceExtractor != null)
            {
                // Get the interfaces for the base type
                InterfaceExtractor.GetInterfaces(actualBaseType, interfaces);

                Type[] targetList = interfaces.ToArray();
                // Extract the inherited interfaces
                foreach (Type type in targetList)
                {
                    InterfaceExtractor.GetInterfaces(type, interfaces);
                }
            }

            #endregion

            #region Generate the assembly

            string             assemblyName     = "LinFu.Proxy";
            AssemblyDefinition assembly         = AssemblyFactory.DefineAssembly(assemblyName, AssemblyKind.Dll);
            ModuleDefinition   mainModule       = assembly.MainModule;
            TypeReference      importedBaseType = mainModule.Import(actualBaseType);
            TypeAttributes     attributes       = TypeAttributes.AutoClass | TypeAttributes.Class |
                                                  TypeAttributes.Public | TypeAttributes.BeforeFieldInit;

            #endregion

            #region Initialize the proxy type

            string         guid          = Guid.NewGuid().ToString().Replace("-", "");
            string         typeName      = string.Format("{0}Proxy-{1}", baseType.Name, guid);
            string         namespaceName = "LinFu.Proxy";
            TypeDefinition proxyType     = mainModule.DefineClass(typeName, namespaceName,
                                                                  attributes, importedBaseType);

            proxyType.AddDefaultConstructor();

            #endregion

            if (ProxyBuilder == null)
            {
                throw new NullReferenceException("The 'ProxyBuilder' property cannot be null");
            }

            // Add the list of interfaces to the target type
            foreach (Type interfaceType in interfaces)
            {
                if (!interfaceType.IsInterface)
                {
                    continue;
                }

                TypeReference currentType = mainModule.Import(interfaceType);
                proxyType.Interfaces.Add(currentType);
            }

            // Hand it off to the builder for construction
            ProxyBuilder.Construct(actualBaseType, interfaces, mainModule, proxyType);

            // Verify the assembly, if possible
            if (Verifier != null)
            {
                Verifier.Verify(assembly);
            }

            #region Compile the results

            Assembly compiledAssembly = assembly.ToAssembly();

            IEnumerable <Type> types = null;

            try
            {
                types = compiledAssembly.GetTypes();
            }
            catch (ReflectionTypeLoadException ex)
            {
                types = ex.Types;
            }

            Type result = (from t in types
                           where t != null && t.IsClass
                           select t).FirstOrDefault();

            #endregion

            // Cache the result
            if (Cache != null)
            {
                Cache.Store(result, baseType, originalInterfaces);
            }

            return(result);
        }
Esempio n. 10
0
 protected override void ImplementAttribute(ModuleDefinition module, TypeDefinition attribute, WellKnownTypes wellKnownTypes, CustomAttributeFactory attributeFactory)
 {
     attribute.AddDefaultConstructor(wellKnownTypes.TypeSystem);
     attribute.CustomAttributes.Add(attributeFactory.AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, inherited: false));
 }
Esempio n. 11
0
        static void SetDataTemplate(IElementNode parentNode, ElementNode node, ILContext parentContext,
                                    IXmlLineInfo xmlLineInfo)
        {
            var parentVar = parentContext.Variables[parentNode];

            //Push the DataTemplate to the stack, for setting the template
            parentContext.IL.Emit(OpCodes.Ldloc, parentVar);

            //Create nested class
            //			.class nested private auto ansi sealed beforefieldinit '<Main>c__AnonStorey0'
            //			extends [mscorlib]System.Object

            var module   = parentContext.Body.Method.Module;
            var anonType = new TypeDefinition(
                null,
                "<" + parentContext.Body.Method.Name + ">_anonXamlCDataTemplate_" + dtcount++,
                TypeAttributes.BeforeFieldInit |
                TypeAttributes.Sealed |
                TypeAttributes.NestedPrivate)
            {
                BaseType = module.TypeSystem.Object
            };

            parentContext.Body.Method.DeclaringType.NestedTypes.Add(anonType);
            var ctor = anonType.AddDefaultConstructor();

            var loadTemplate = new MethodDefinition("LoadDataTemplate",
                                                    MethodAttributes.Assembly | MethodAttributes.HideBySig,
                                                    module.TypeSystem.Object);

            anonType.Methods.Add(loadTemplate);

            var parentValues = new FieldDefinition("parentValues", FieldAttributes.Assembly, module.Import(typeof(object[])));

            anonType.Fields.Add(parentValues);

            TypeReference rootType = null;
            var           vdefRoot = parentContext.Root as VariableDefinition;

            if (vdefRoot != null)
            {
                rootType = vdefRoot.VariableType;
            }
            var fdefRoot = parentContext.Root as FieldDefinition;

            if (fdefRoot != null)
            {
                rootType = fdefRoot.FieldType;
            }

            var root = new FieldDefinition("root", FieldAttributes.Assembly, rootType);

            anonType.Fields.Add(root);

            //Fill the loadTemplate Body
            var templateIl = loadTemplate.Body.GetILProcessor();

            templateIl.Emit(OpCodes.Nop);
            var templateContext = new ILContext(templateIl, loadTemplate.Body, parentValues)
            {
                Root = root
            };

            node.Accept(new CreateObjectVisitor(templateContext), null);
            node.Accept(new SetNamescopesAndRegisterNamesVisitor(templateContext), null);
            node.Accept(new SetFieldVisitor(templateContext), null);
            node.Accept(new SetResourcesVisitor(templateContext), null);
            node.Accept(new SetPropertiesVisitor(templateContext), null);
            templateIl.Emit(OpCodes.Ldloc, templateContext.Variables[node]);
            templateIl.Emit(OpCodes.Ret);

            //Instanciate nested class
            var parentIl = parentContext.IL;

            parentIl.Emit(OpCodes.Newobj, ctor);

            //Copy required local vars
            parentIl.Emit(OpCodes.Dup);             //Duplicate the nestedclass instance
            parentIl.Append(node.PushParentObjectsArray(parentContext));
            parentIl.Emit(OpCodes.Stfld, parentValues);
            parentIl.Emit(OpCodes.Dup);             //Duplicate the nestedclass instance
            if (parentContext.Root is VariableDefinition)
            {
                parentIl.Emit(OpCodes.Ldloc, parentContext.Root as VariableDefinition);
            }
            else if (parentContext.Root is FieldDefinition)
            {
                parentIl.Emit(OpCodes.Ldarg_0);
                parentIl.Emit(OpCodes.Ldfld, parentContext.Root as FieldDefinition);
            }
            else
            {
                throw new InvalidProgramException();
            }
            parentIl.Emit(OpCodes.Stfld, root);

            //SetDataTemplate
            parentIl.Emit(OpCodes.Ldftn, loadTemplate);
            var funcObjRef = module.Import(typeof(Func <object>));
            var funcCtor   =
                funcObjRef
                .Resolve()
                .Methods.First(md => md.IsConstructor && md.Parameters.Count == 2)
                .ResolveGenericParameters(funcObjRef, module);

            parentIl.Emit(OpCodes.Newobj, module.Import(funcCtor));

#pragma warning disable 0612
            var propertySetter =
                module.Import(typeof(IDataTemplate)).Resolve().Properties.First(p => p.Name == "LoadTemplate").SetMethod;
#pragma warning restore 0612
            parentContext.IL.Emit(OpCodes.Callvirt, module.Import(propertySetter));
        }
Esempio n. 12
0
        public IEnumerable <Instruction> ConvertFromString(string value, ILContext context, BaseNode node)
        {
            var module = context.Module;

            EmbeddedResource matchedResource = null;

            foreach (var resource in module.Resources.OfType <EmbeddedResource>())
            {
                if (resource.Name.StartsWith(context.EmbeddedResourceNameSpace) && resource.Name.EndsWith(value))
                {
                    matchedResource = resource;
                    break;
                }
            }

            if (null == matchedResource)
            {
                foreach (var resource in module.Resources.OfType <EmbeddedResource>())
                {
                    if (resource.Name.EndsWith(value))
                    {
                        matchedResource = resource;
                        break;
                    }
                }
            }

            if (null != matchedResource)
            {
                string classname;
                if (matchedResource.IsResourceDictionaryXaml(module, out classname))
                {
                    int lastIndex     = classname.LastIndexOf('.');
                    var realClassName = classname.Substring(lastIndex + 1);
                    var typeref       = XmlTypeExtensions.GetTypeReference(realClassName, module, node, XmlTypeExtensions.ModeOfGetType.Both);

                    var typeName             = matchedResource.Name.Replace('.', '_');
                    var typeDefOfGetResource = module.Types.FirstOrDefault(type => type.FullName == "GetResource." + typeName);
                    if (null != typeDefOfGetResource)
                    {
                        module.Types.Remove(typeDefOfGetResource);
                        typeDefOfGetResource = null;
                    }

                    if (null == typeDefOfGetResource)
                    {
                        typeDefOfGetResource          = new TypeDefinition("GetResource", typeName, TypeAttributes.NotPublic);
                        typeDefOfGetResource.BaseType = typeref;
                        module.Types.Add(typeDefOfGetResource);

                        typeDefOfGetResource.AddDefaultConstructor(typeref);
                    }

                    var methodName          = "GetResource";
                    var methodOfGetResource = typeDefOfGetResource.Methods.FirstOrDefault(m => m.Name == methodName);

                    if (null == methodOfGetResource)
                    {
                        methodOfGetResource = new MethodDefinition(methodName, MethodAttributes.Public, typeref);
                        typeDefOfGetResource.Methods.Add(methodOfGetResource);
                    }

                    var constructor = typeDefOfGetResource.Methods.FirstOrDefault(m => m.IsConstructor);

                    if (null != constructor)
                    {
                        constructor.Body.Instructions.Insert(constructor.Body.Instructions.Count - 1, Instruction.Create(OpCodes.Ldarg_0));
                        constructor.Body.Instructions.Insert(constructor.Body.Instructions.Count - 1, Instruction.Create(OpCodes.Call, methodOfGetResource));
                        constructor.Body.Instructions.Insert(constructor.Body.Instructions.Count - 1, Instruction.Create(OpCodes.Pop));
                    }

                    var rootnode = XamlTask.ParseXaml(matchedResource.GetResourceStream(), typeref);

                    Exception exception;
                    TryCoreCompile(methodOfGetResource, rootnode, context.EmbeddedResourceNameSpace, out exception);

                    yield return(Create(Newobj, constructor));
                }
            }
        }
 protected override void ImplementAttribute(ModuleDefinition module, TypeDefinition attribute, WellKnownTypes wellKnownTypes, CustomAttributeFactory attributeFactory)
 {
     attribute.AddDefaultConstructor(wellKnownTypes.TypeSystem);
     attribute.CustomAttributes.Add(attributeFactory.AttributeUsage(AttributeTargets.Method, inherited: false));
 }