示例#1
0
        public static TypeDefinition CreateStructTypeDefinition(
            [NotNull] this ModuleDefinition moduleDefinition
            , [NotNull] string @namespace
            , [NotNull] string name
            , TypeAttributes additionalAttributes = TypeAttributes.Public
            )
        {
            //.class public sealed sequential ansi beforefieldinit
            //  StructName
            //    extends [netstandard]System.ValueType
            //{
            //} // end of class StructName
            var typeAttributes = TypeAttributes.Class
                                 | TypeAttributes.Sealed
                                 | TypeAttributes.AnsiClass
                                 | TypeAttributes.BeforeFieldInit
                                 | additionalAttributes
            ;
            var isExplicitLayout = (typeAttributes & TypeAttributes.ExplicitLayout) == TypeAttributes.ExplicitLayout;

            if (!isExplicitLayout)
            {
                typeAttributes |= TypeAttributes.SequentialLayout;
            }
            return(new TypeDefinition(@namespace, name, typeAttributes)
            {
                BaseType = moduleDefinition.ImportReference(typeof(ValueType))
            });
        }
示例#2
0
    void AddWeavingInfo()
    {
        if (cancelRequested)
        {
            return;
        }

        Logger.LogDebug("  Adding weaving info");
        var startNew = Stopwatch.StartNew();

        const TypeAttributes typeAttributes = TypeAttributes.NotPublic | TypeAttributes.Class;
        var typeDefinition = new TypeDefinition(null, "ProcessedByFody", typeAttributes, TypeSystem.ObjectReference);

        ModuleDefinition.Types.Add(typeDefinition);

        AddVersionField(typeof(IInnerWeaver).Assembly, "FodyVersion", typeDefinition);

        foreach (var weaver in weaverInstances)
        {
            var configAssembly = weaver.Instance.GetType().Assembly;
            var name           = weaver.Config.ElementName.Replace(".", string.Empty);
            AddVersionField(configAssembly, name, typeDefinition);
        }

        var finishedMessage = $"  Finished in {startNew.ElapsedMilliseconds}ms {Environment.NewLine}";

        Logger.LogDebug(finishedMessage);
    }
 public TypeDefinition addType(String sTypeNameSpace, String sTypeName, TypeAttributes taTypeAttributes,
                               TypeReference trTypeReference)
 {
     var tdNewType = new TypeDefinition(sTypeName, sTypeNameSpace, taTypeAttributes, trTypeReference);
     mainModule.Types.Add(tdNewType);
     return tdNewType;
 }
        MethodDefinition InjectRetriever(TypeReference importType,
                                         IReadOnlyCollection <string> searchPatterns)
        {
            const TypeAttributes typeAttributes = TypeAttributes.AnsiClass |
                                                  TypeAttributes.Sealed | TypeAttributes.AutoClass;

            // internal sealed class ImportTypeRetriever
            var targetType = new TypeDefinition("Vandelay",
                                                TargetName($"{importType.Name}Retriever", -1), typeAttributes,
                                                TypeSystem.ObjectReference);

            ModuleDefinition.Types.Add(targetType);

            var importFields = InjectImportsField(importType);

            targetType.Fields.Add(importFields.Definition);

            var constructor = InjectConstructor(searchPatterns);

            targetType.Methods.Add(constructor);

            var retrieverProperty = InjectRetrieverProperty(importType,
                                                            importFields.CollectionType, constructor, importFields.Definition);

            targetType.Methods.Add(retrieverProperty);

            return(retrieverProperty);
        }
        public TypeDefinition addType(String sTypeNameSpace, String sTypeName, TypeAttributes taTypeAttributes,
                                      TypeReference trTypeReference)
        {
            var tdNewType = new TypeDefinition(sTypeName, sTypeNameSpace, taTypeAttributes, trTypeReference);

            mainModule.Types.Add(tdNewType);
            return(tdNewType);
        }
        private static void CreatePropertyInterface(this ModuleDefinition module, Type type, string namespaceName)
        {
// public interface Int32Property
// {
//     void Allocate(ref BlobBuilder builder, ref BlobVariable<Int32> blobVariable);
// }
// .class interface public abstract auto ansi
//   EntitiesBT.Editor.Int32Property
// {
//
//   .method public hidebysig virtual newslot abstract instance void
//     Allocate(
//       valuetype [Unity.Entities]Unity.Entities.BlobBuilder& builder,
//       valuetype [EntitiesBT.Runtime]EntitiesBT.Variable.BlobVariable`1<int32>& blobVariable
//     ) cil managed
//   {
//     // Can't find a body
//   } // end of method Int32Property::Allocate
// } // end of class EntitiesBT.Editor.Int32Property

            const TypeAttributes interfaceAttributes = TypeAttributes.Class
                                                       | TypeAttributes.Interface
                                                       | TypeAttributes.Public
                                                       | TypeAttributes.Abstract
                                                       | TypeAttributes.AutoClass
                                                       | TypeAttributes.AnsiClass;
            var interfaceType = new TypeDefinition(namespaceName, $"{type.Name}Property", interfaceAttributes, module.TypeSystem.Object);

            const MethodAttributes methodAttributes = MethodAttributes.Public
                                                      | MethodAttributes.HideBySig
                                                      | MethodAttributes.Virtual
                                                      | MethodAttributes.NewSlot
                                                      | MethodAttributes.Abstract;
            var allocateMethod   = new MethodDefinition("Allocate", methodAttributes, module.TypeSystem.Void);
            var builderParameter = new ParameterDefinition(
                "builder"
                , ParameterAttributes.None
                , module.ImportReference(typeof(BlobBuilder)).MakeByReferenceType()
                );
            var blobVariableParameter = new ParameterDefinition(
                "blobVariable"
                , ParameterAttributes.None
                , module.ImportReference(typeof(BlobVariable <>).MakeGenericType(type)).MakeByReferenceType()
                );

            allocateMethod.Parameters.Add(builderParameter);
            allocateMethod.Parameters.Add(blobVariableParameter);
            interfaceType.Methods.Add(allocateMethod);
            module.Types.Add(interfaceType);

            foreach (var propertyType in _PROPERTY_TYPES.Value)
            {
                module.CreatePropertyClass(namespaceName, type, propertyType, new InterfaceImplementation(interfaceType));
            }
        }
示例#7
0
        internal void AddOrReplaceIoc(ILProcessor il)
        {
            var mod         = il.Body.Method.DeclaringType.Module;
            var myNamespace = mod.Types.Select(t => t.Namespace)
                              .Where(n => !string.IsNullOrWhiteSpace(n)).OrderBy(n => n.Length).First();
            const TAttr attr = TAttr.Class | TAttr.Public | TAttr.Sealed
                               | TAttr.Abstract | TAttr.BeforeFieldInit;
            var objBase = mod.ImportReference(typeof(object));
            var type    = new TypeDefinition(myNamespace, IocName, attr, objBase);
            var oldType = mod.Types.FirstOrDefault(t => t.FullName == type.FullName);

            if (oldType != null)
            {
                mod.Types.Remove(oldType);
            }
            mod.Types.Add(type);
            var         vesselRef = mod.ImportReference(typeof(IVessel));
            const FAttr fieldAttr = FAttr.Static | FAttr.Private;
            var         contField = new FieldDefinition(IocField, fieldAttr, vesselRef);

            type.Fields.Add(contField);
            const MAttr getAttrs = MAttr.Static | MAttr.Public
                                   | MAttr.SpecialName | MAttr.HideBySig;
            var getMethod = new MethodDefinition(IocMethod, getAttrs, vesselRef);

            type.Methods.Add(getMethod);
            ScopeMethod = getMethod;
            IocType     = type;
            var gmil = getMethod.Body.GetILProcessor();

            gmil.Append(gmil.Create(OpCodes.Ldsfld, contField));
            gmil.Append(gmil.Create(OpCodes.Ret));
            var         voidRef     = mod.ImportReference(typeof(void));
            const MAttr constrAttrs = MAttr.Static | MAttr.SpecialName | MAttr.Private
                                      | MAttr.RTSpecialName | MAttr.HideBySig;
            var constr = new MethodDefinition(Defaults.StaticConstrName, constrAttrs, voidRef);

            type.Methods.Add(constr);
            var cil       = constr.Body.GetILProcessor();
            var multiMeth = typeof(DefaultVessel).GetConstructors().First();
            var multiRef  = mod.ImportReference(multiMeth);

            cil.Append(cil.Create(OpCodes.Newobj, multiRef));
            cil.Append(cil.Create(OpCodes.Stsfld, contField));
            cil.Append(cil.Create(OpCodes.Ret));
            il.Append(il.Create(OpCodes.Call, getMethod));
            il.Append(il.Create(OpCodes.Pop));
            il.Append(il.Create(OpCodes.Ret));
        }
示例#8
0
        /// <summary>
        /// Determines whether or not a given method is nested.
        /// </summary>
        /// <param name="attributes">The type attributes for the given type.</param>
        /// <returns>Returns <c>true</c> if the type is nested; otherwise, it will return <c>false</c>.</returns>
        private static bool IsNested(Mono.Cecil.TypeAttributes attributes)
        {
            switch (attributes & Mono.Cecil.TypeAttributes.VisibilityMask)
            {
            case Mono.Cecil.TypeAttributes.NestedPublic:
            case Mono.Cecil.TypeAttributes.NestedPrivate:
            case Mono.Cecil.TypeAttributes.NestedFamORAssem:
            case Mono.Cecil.TypeAttributes.NestedFamily:
            case Mono.Cecil.TypeAttributes.NestedFamANDAssem:
            case Mono.Cecil.TypeAttributes.NestedAssembly:
                return(true);

            default:
                return(false);
            }
        }
示例#9
0
        public static MonoDevelop.Projects.Dom.Modifiers GetModifiers(Mono.Cecil.TypeAttributes attr)
        {
            MonoDevelop.Projects.Dom.Modifiers result = MonoDevelop.Projects.Dom.Modifiers.None;
            if ((attr & TypeAttributes.Abstract) == TypeAttributes.Abstract)
            {
                result |= Modifiers.Abstract;
            }
            if ((attr & TypeAttributes.Sealed) == TypeAttributes.Sealed)
            {
                result |= Modifiers.Sealed;
            }
            if ((attr & TypeAttributes.SpecialName) == TypeAttributes.SpecialName)
            {
                result |= Modifiers.SpecialName;
            }

            if ((attr & TypeAttributes.NestedPrivate) == TypeAttributes.NestedPrivate)
            {
                result |= Modifiers.Private;
            }
            else if ((attr & TypeAttributes.Public) == TypeAttributes.Public || (attr & TypeAttributes.NestedPublic) == TypeAttributes.NestedPublic)
            {
                result |= Modifiers.Public;
            }
            else if ((attr & TypeAttributes.NestedFamANDAssem) == TypeAttributes.NestedFamANDAssem)
            {
                result |= Modifiers.ProtectedAndInternal;
            }
            else if ((attr & TypeAttributes.NestedFamORAssem) == TypeAttributes.NestedFamORAssem)
            {
                result |= Modifiers.ProtectedOrInternal;
            }
            else if ((attr & TypeAttributes.NestedFamily) == TypeAttributes.NestedFamily)
            {
                result |= Modifiers.Protected;
            }
            else
            {
                result |= Modifiers.Private;
            }

            if ((attr & TypeAttributes.NestedAssembly) == TypeAttributes.NestedAssembly)
            {
                result |= Modifiers.Internal;
            }
            return(result);
        }
        private static void CreatePropertyClass(this ModuleDefinition module, string namespaceName, Type valueType, Type propertyType, InterfaceImplementation @interface)
        {
// .class public auto ansi beforefieldinit
//   EntitiesBT.Editor.Int32CustomViariableProperty
//     extends class [EntitiesBT.Runtime]EntitiesBT.Variable.CustomVariableProperty`1<int32>
//     implements EntitiesBT.Editor.Int32Property
// {
//
//   .method public hidebysig specialname rtspecialname instance void
//     .ctor() cil managed
//   {
//     .maxstack 8
//
//     IL_0000: ldarg.0      // this
//     IL_0001: call         instance void class [EntitiesBT.Runtime]EntitiesBT.Variable.CustomVariableProperty`1<int32>::.ctor()
//     IL_0006: nop
//     IL_0007: ret
//
//   } // end of method Int32CustomViariableProperty::.ctor
// } // end of class EntitiesBT.Editor.Int32CustomViariableProperty

            const TypeAttributes classAttributes = TypeAttributes.Class | TypeAttributes.Public | TypeAttributes.AutoClass | TypeAttributes.AnsiClass | TypeAttributes.BeforeFieldInit;
            var baseType  = propertyType.MakeGenericType(valueType);
            var classType = new TypeDefinition(namespaceName, $"{valueType.Name}{propertyType.Name}", classAttributes, module.ImportReference(baseType));

            classType.Interfaces.Add(@interface);

            const MethodAttributes methodAttributes = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName;
            var ctor = new MethodDefinition(".ctor", methodAttributes, module.TypeSystem.Void);
            var il   = ctor.Body.GetILProcessor();

            il.Append(il.Create(OpCodes.Ldarg_0));
            // call the base constructor
            il.Append(il.Create(OpCodes.Call, module.ImportReference(baseType.GetConstructor(Array.Empty <Type>()))));
            il.Append(il.Create(OpCodes.Nop));
            il.Append(il.Create(OpCodes.Ret));

            var serializableAttribute = new CustomAttribute(module.ImportReference(
                                                                typeof(SerializableAttribute).GetConstructor(Array.Empty <Type>())
                                                                ));

            classType.CustomAttributes.Add(serializableAttribute);
            classType.Methods.Add(ctor);
            module.Types.Add(classType);
        }
示例#11
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);
        }
示例#12
0
        /// <summary>
        /// Defines a new class and adds it to the <paramref name="mainModule"/> module.
        /// </summary>
        /// <param name="mainModule">The module which will hold the new created type.</param>
        /// <param name="typeName">The name of the class to create.</param>
        /// <param name="namespaceName">The namespace that will contain the new class.</param>
        /// <param name="attributes">The <see cref="Mono.Cecil.TypeAttributes"/> for the given type.</param>
        /// <param name="baseType">The base class of the new type.</param>
        /// <returns>A <see cref="TypeDefinition"/> representing the new class being created.</returns>
        public static TypeDefinition DefineClass(this ModuleDefinition mainModule,
                                                 string typeName, string namespaceName, TypeAttributes attributes,
                                                 TypeReference baseType)
        {
            var resultType = new TypeDefinition(typeName, namespaceName,
                                                attributes, baseType);

            mainModule.Types.Add(resultType);
            return(resultType);
        }
示例#13
0
        private TypeDefinition CreateRepositoryType(TypeDefinition repoTypeDef,
            TypeCodeGenInfo rti,
            MethodAttributes methodAttributes,
            string repoTypeNameFormat,
            TypeAttributes typeAttributes,
            bool isImplementation,
            IEnumerable<TypeReference> interfacesToImplement = null)
        {
            var tt = (ResourceType)rti.TransformedType;

            repoTypeDef.Namespace = this.assemblyName;
            repoTypeDef.Name = string.Format(repoTypeNameFormat, rti.TransformedType.Name);
            repoTypeDef.Attributes = typeAttributes;

            if (isImplementation)
                repoTypeDef.BaseType = rti.CustomRepositoryBaseTypeReference;

            repoTypeDef.Interfaces.AddRange(interfacesToImplement ?? Enumerable.Empty<TypeReference>());
            var baseTypeGenericDef = rti.CustomRepositoryBaseTypeDefinition;
            var baseTypeGenericArgs = rti.CustomRepositoryBaseTypeReference.GenericArguments.ToArray();

            foreach (var subType in tt.MergedTypes.Concat(tt))
            {
                if (subType.PostAllowed)
                {
                    AddRepositoryFormPostMethod(methodAttributes,
                        isImplementation,
                        subType,
                        repoTypeDef,
                        baseTypeGenericDef,
                        baseTypeGenericArgs);
                }
            }
            if (tt.PrimaryId != null)
            {
                AddRepositoryGetByIdMethod(rti,
                    methodAttributes,
                    isImplementation,
                    tt,
                    repoTypeDef,
                    baseTypeGenericDef,
                    baseTypeGenericArgs,
                    "Get");
                AddRepositoryGetByIdMethod(rti,
                    methodAttributes,
                    isImplementation,
                    tt,
                    repoTypeDef,
                    baseTypeGenericDef,
                    baseTypeGenericArgs,
                    "GetLazy");
            }

            // Constructor
            if (isImplementation)
            {
                var baseCtor = baseTypeGenericDef.GetConstructors().First();
                var baseCtorRef =
                    Import(baseCtor).MakeHostInstanceGeneric(baseTypeGenericArgs);

                var ctor = new MethodDefinition(
                    ".ctor",
                    MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName
                    | MethodAttributes.Public,
                    VoidTypeRef);

                baseCtor.Parameters.Select(x => new ParameterDefinition(x.Name, x.Attributes, Import(x.ParameterType)))
                    .AddTo(ctor.Parameters);

                ctor.Body.MaxStackSize = 8;
                var ctorIlProcessor = ctor.Body.GetILProcessor();
                ctorIlProcessor.Append(Instruction.Create(OpCodes.Ldarg_0));
                foreach (var ctorParam in ctor.Parameters)
                    ctorIlProcessor.Append(Instruction.Create(OpCodes.Ldarg, ctorParam));
                ctorIlProcessor.Append(Instruction.Create(OpCodes.Call, baseCtorRef));
                ctorIlProcessor.Append(Instruction.Create(OpCodes.Ret));
                repoTypeDef.Methods.Add(ctor);
            }

            if (!this.module.Types.Contains(repoTypeDef))
                this.module.Types.Add(repoTypeDef);
            return repoTypeDef;
        }
示例#14
0
        /// <summary>
        /// Defines a new class and adds it to the <paramref name="mainModule"/> module.
        /// </summary>
        /// <param name="mainModule">The module which will hold the new created type.</param>
        /// <param name="typeName">The name of the class to create.</param>
        /// <param name="namespaceName">The namespace that will contain the new class.</param>
        /// <param name="attributes">The <see cref="Mono.Cecil.TypeAttributes"/> for the given type.</param>
        /// <param name="baseType">The base class of the new type.</param>
        /// <returns>A <see cref="TypeDefinition"/> representing the new class being created.</returns>
        public static TypeDefinition DefineClass(this ModuleDefinition mainModule,
                                                 string typeName, string namespaceName, Mono.Cecil.TypeAttributes attributes,
                                                 TypeReference baseType)
        {
            var resultType = new TypeDefinition(namespaceName, typeName,
                                                attributes, baseType);

            if (!IsNested(attributes))
            {
                mainModule.Types.Add(resultType);
            }

            return(resultType);
        }
示例#15
0
 public FluentTypeBuilder(ModuleDefinition module, string name)
 {
     _module     = module;
     _name       = name;
     _visibility = TypeAttributes.Public;
 }
示例#16
0
 public static GenericFuncContainer <TypeDefinition, bool> TypeNegAttributeComparer(Mono.Cecil.TypeAttributes negAttrs)
 {
     return(new GenericFuncContainer <TypeDefinition, bool>(type => {
         return (type.Attributes & negAttrs) == 0;
     }));
 }
        public static TypeDefinition AddNestedType(this TypeDefinition type, string name, TypeAttributes attributes, TypeReference baseType)
        {
            TypeDefinition newType = new TypeDefinition(type.Namespace, name, attributes, baseType);

            type.NestedTypes.Add(newType);

            return(newType);
        }