Exemple #1
1
 internal static void Initialize(ModuleDefinition moduleDefinition)
 {
     ModuleDefinition = moduleDefinition;
     typeType = ModuleDefinition.Import(typeof(Type));
     taskType = ModuleDefinition.Import(typeof(Task));
     getTypeFromRuntimeHandleMethod = ModuleDefinition.Import(typeType.Resolve().Methods.Single(x => x.Name == "GetTypeFromHandle"));
     typeGetMethod = ModuleDefinition.Import(typeType.Resolve().Methods.Single(x => x.Name == "GetMethod" && x.Parameters.Count == 5));
     taskTType = ModuleDefinition.Import(typeof(Task<>));
     taskFromResult = ModuleDefinition.Import(taskType.Resolve().Methods.Single(x => x.Name == "FromResult"));
 }
Exemple #2
0
 /// <summary>
 /// Adds the specified attribute to the specified method.
 /// </summary>
 /// <param name="field">The method to add the attribute to.</param>
 /// <param name="attribute">The attribute to add.</param>
 /// <param name="module">The module the field is defined in.</param>
 public static void AddAttribute(MethodDefinition method, Type attribute, ModuleDefinition module)
 {
     TypeDefinition tr = module.Import(attribute).Resolve();
     MethodDefinition mr = tr.Methods.First(value => value.IsConstructor);
     MethodReference rf = module.Import(mr);
     method.CustomAttributes.Add(new CustomAttribute(rf));
 }
Exemple #3
0
        public void AddMixing(ModuleDefinition targetModule)
        {
            var objectType = targetModule.Import(typeof(object)).Resolve();
            var mixesAttributeBaseType = targetModule.Import(typeof(MixesAttributeBase)).Resolve();

            var originalTypes = new List<TypeDefinition>(targetModule.Types);
            foreach (var type in originalTypes)
            {
                if(type.CustomAttributes.Any(
                    customAttribute =>
                    {
                        var attributeType = customAttribute.AttributeType.Resolve();
                        while (attributeType != objectType &&
                            attributeType != mixesAttributeBaseType &&
                            attributeType.BaseType != null)
                        {
                            attributeType = attributeType.BaseType.Resolve();
                        }
                        return attributeType == mixesAttributeBaseType;
                    }))
                {
                    this.AddIMixes(type);
                    this.AddISerializable(type);
                }
            }
        }
        protected override TypeDefinition CreateCustomAttributeType(ModuleDefinition targetModule)
        {
            ArgumentUtility.CheckNotNull ("targetModule", targetModule);

              var customType = new TypeDefinition (_attributeNamespace,
                                           _attributeName,
                                           TypeAttributes.Public | TypeAttributes.Class,
                                           targetModule.Import (typeof (Attribute)));

              var ctor = new MethodDefinition (
              ".ctor",
              MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName,
              targetModule.Import (typeof (void)));
              ctor.HasThis = true;

              var il = ctor.Body.GetILProcessor ();
              il.Emit (OpCodes.Ldarg_0);
              il.Emit (
              OpCodes.Call,
              targetModule.Import (typeof (Attribute).GetConstructor (BindingFlags.NonPublic | BindingFlags.Instance, null, Type.EmptyTypes, null)));
              il.Emit (OpCodes.Ret);

              customType.Methods.Add (ctor);
              return customType;
        }
Exemple #5
0
        public Either<MemberReference, PropertyReferenceContainer> Convert(IAstReference astReference, ModuleDefinition module)
        {
            var reflectedType = astReference as AstReflectedType;
            if (reflectedType != null)
                return module.Import(reflectedType.ActualType);

            var reflectedMethod = astReference as AstReflectedMethod;
            if (reflectedMethod != null)
                return module.Import(reflectedMethod.Method);

            var reflectedConstructor = astReference as AstReflectedConstructor;
            if (reflectedConstructor != null)
                return module.Import(reflectedConstructor.Constructor);

            var reflectedProperty = astReference as AstReflectedProperty;
            if (reflectedProperty != null) {
                var getMethod = reflectedProperty.Property.GetGetMethod();
                var setMethod = reflectedProperty.Property.GetSetMethod();
                return new PropertyReferenceContainer(
                    getMethod != null ? module.Import(getMethod) : null,
                    setMethod != null ? module.Import(setMethod) : null
                );
            }

            return null;
        }
Exemple #6
0
 /// <summary>
 /// Adds the specified attribute to the specified field.
 /// </summary>
 /// <param name="field">The field to add the attribute to.</param>
 /// <param name="attribute">The attribute to add.</param>
 /// <param name="module">The module the field is defined in.</param>
 public static CustomAttribute AddAttribute(FieldDefinition field, Type attribute, ModuleDefinition module)
 {
     TypeDefinition tr = module.Import(attribute).Resolve();
     MethodDefinition mr = tr.Methods.First(value => value.IsConstructor);
     MethodReference rf = module.Import(mr);
     var customAttribute = new CustomAttribute(rf);
     field.CustomAttributes.Add(customAttribute);
     return customAttribute;
 }
        void CopyTo(CustomAttribute target, ModuleDefinition context)
        {
            foreach (var arg in ConstructorArguments)
                target.ConstructorArguments.Add(new CustomAttributeArgument(context.Import(arg.Type), arg.Value));

            foreach (var field in Fields)
                target.Fields.Add(new CustomAttributeNamedArgument(field.Name, new CustomAttributeArgument(context.Import(field.Argument.Type), field.Argument.Value)));

            foreach (var prop in Properties)
                target.Properties.Add(new CustomAttributeNamedArgument(prop.Name, new CustomAttributeArgument(context.Import(prop.Argument.Type), prop.Argument.Value)));
        }
 public TypeReferenceProvider(TraceLoggingConfiguration configuration, ILoggerAdapterMetadataScopeProvider loggerAdapterMetadataScopeProvider, ModuleDefinition moduleDefinition)
 {
     _configuration = configuration;
     _moduleDefinition = moduleDefinition;
     _loggerAdapterMetadataScopeProvider = loggerAdapterMetadataScopeProvider;
     _stringArray = new Lazy<TypeReference>(() => moduleDefinition.Import((typeof(string[]))));
     _objectArray = new Lazy<TypeReference>(() => moduleDefinition.Import(typeof(object[])));
     _type = new Lazy<TypeReference>(() => moduleDefinition.Import(typeof(Type)));
     _stopwatch = new Lazy<TypeReference>(() => moduleDefinition.Import(typeof(Stopwatch)));
     _exception = new Lazy<TypeReference>(() => moduleDefinition.Import(typeof(Exception)));
 }
Exemple #9
0
        public Hooker(ModuleDefinition module)
        {
            Module = module;

            hookRegistryType = Module.Import(typeof(Hooks.HookRegistry));
            rmhType = Module.Import(typeof(System.RuntimeMethodHandle));
            onCallMethod = Module.Import(
                typeof(Hooks.HookRegistry).GetMethods()
                .First(mi => mi.Name.Contains("OnCall")));
            Module.AssemblyReferences.Add(new AssemblyNameReference("HookRegistry", new Version(1, 0, 0, 0)));
        }
        /// <summary>
        /// Constructs a type that implements the
        /// <see cref="IProxy"/> interface.
        /// </summary>
        /// <param name="module">The module that will hold the target type.</param>
        /// <param name="targetType">The type that will implement the <see cref="IProxy"/> interface.</param>
        public void Construct(ModuleDefinition module, TypeDefinition targetType)
        {
            TypeReference proxyInterfaceType = module.Import(typeof (IProxy));
            TypeReference interceptorType = module.Import(typeof (IInterceptor));

            // Implement the IProxy interface only once
            if (targetType.Interfaces.Contains(proxyInterfaceType))
                return;

            targetType.Interfaces.Add(proxyInterfaceType);
            targetType.AddProperty("Interceptor", interceptorType);
        }
    static void ProcessType(ModuleDefinition moduleDefinition, TypeDefinition type)
    {
        foreach (var toRemove in type.Properties.Where(x => x.IsCompilerGenerated()).ToList())
        {
            type.Properties.Remove(toRemove);
        }
        foreach (var toRemove in type.Methods.Where(x => x.IsCompilerGenerated() && !x.Name.StartsWith("get_") && !x.Name.StartsWith("set_")).ToList())
        {
            type.Methods.Remove(toRemove);
        }
        foreach (var toRemove in type.Fields.Where(x => x.IsCompilerGenerated()).ToList())
        {
            type.Fields.Remove(toRemove);
        }

        foreach (var property in type.Properties)
        {
            property.RemoveUnwantedAttributes();
        }

        foreach (var field in type.Fields)
        {
            field.RemoveUnwantedAttributes();
        }

        var exceptionReference = new TypeReference("System", "Exception", moduleDefinition.TypeSystem.String.Module, moduleDefinition.TypeSystem.String.Scope);
        exceptionReference = moduleDefinition.Import(exceptionReference);
        var ctor = moduleDefinition.Import(exceptionReference.Resolve().GetConstructors().First(c => !c.HasParameters));

        foreach (var method in type.Methods)
        {
            method.RemoveUnwantedAttributes();
            if (method.HasBody)
            {
                //todo: preserve a single pdb line
                var body = method.Body;
                var validSequencePoint = method.GetValidSequencePoint();
                body.Variables.Clear();
                body.ExceptionHandlers.Clear();
                body.Instructions.Clear();

                body.Instructions.Add(Instruction.Create(OpCodes.Newobj, ctor));

                var instruction = Instruction.Create(OpCodes.Throw);
                if (validSequencePoint != null)
                {
                    instruction.SequencePoint = validSequencePoint;
                }
                body.Instructions.Add(instruction);
            }
        }
    }
Exemple #12
0
        public ReferenceContainer(ModuleDefinition moduleDefinition, IAssemblyResolver assemblyResolver)
        {
            var systemDefinition = assemblyResolver.Resolve("mscorlib");
            var yalfDefinition = assemblyResolver.Resolve("Yalf");
            var yalfTypes = yalfDefinition.MainModule.Types;

            var logType = yalfTypes.Single(x => x.Name == "Log");
            var iContextType = yalfTypes.Single(x => x.Name == "IContext");

            var iDisposableType = systemDefinition.MainModule.Types.Single(x => x.Name == "IDisposable");
            var exceptionType = systemDefinition.MainModule.Types.Single(x => x.Name == "Exception");

            MethodContextMethod = moduleDefinition.Import(logType.Methods.Single(m => m.Name == "MethodContext"));
            TraceExceptionMethod = moduleDefinition.Import(logType.Methods.Single(m => m.Name == "TraceException"));
            CreateRecordReturnMethod = retType => {

                var recordReturn = moduleDefinition.Import(iContextType.Methods.Single(m => m.Name == "RecordReturn"));
                if (retType.IsGenericInstance)
                {
                    return recordReturn.MakeGeneric(retType);
                }
                else
                {
                    return recordReturn.MakeGeneric(retType);
                }
            };
            DisposeMethod = moduleDefinition.Import(iDisposableType.Methods.Single(m => m.Name == "Dispose"));
            LogType = moduleDefinition.Import(logType);
            IContextType = moduleDefinition.Import(iContextType);
            ExceptionType = moduleDefinition.Import(exceptionType);
            PreserveStackTraceMethod = moduleDefinition.Import(iContextType.Methods.Single(m => m.Name == "PreserveStackTrace"));
        }
Exemple #13
0
        public CecilVisitor(AssemblyDefinition assembly, ModuleDefinition module)
        {
            _assembly = assembly;
            _module = module;

            var program = _module.Types.First(t => t.Name == "Program");
            _main = program.Methods.First(m => m.Name == "Main");

            _body = _main.Body;
            _instructions = _body.Instructions;
            _instructions.Clear();

            _objCtor = _module.Import(typeof(object).GetConstructor(new System.Type[0]));

            var systemFunctions = _module.Types.First(t => t.Name == "SystemFunctions");
            // Math methods
            _fact = systemFunctions.Methods.First(m => m.Name == "Fact");
            _max = systemFunctions.Methods.First(m => m.Name == "Max");
            _min = systemFunctions.Methods.First(m => m.Name == "Min");
            _pow = systemFunctions.Methods.First(m => m.Name == "Pow");
            // Console methods
            _printBool = systemFunctions.Methods.First(m => m.Name == "PrintBool");
            _printInt = systemFunctions.Methods.First(m => m.Name == "PrintInt");

            _userFunctions = _module.Types.First(t => t.Name == "UserFunctions");
        }
		public static MethodReference ResolveGenericParameters(this MethodReference self, TypeReference declaringTypeRef,
			ModuleDefinition module)
		{
			if (self == null)
				throw new ArgumentNullException(nameof(self));
			if (declaringTypeRef == null)
				throw new ArgumentNullException(nameof(declaringTypeRef));

			var reference = new MethodReference(self.Name, self.ReturnType)
			{
				DeclaringType = declaringTypeRef,
				HasThis = self.HasThis,
				ExplicitThis = self.ExplicitThis,
				CallingConvention = self.CallingConvention
			};

			foreach (var parameter in self.Parameters) {
				var p = parameter.ParameterType.IsGenericParameter ? parameter.ParameterType : module.Import(parameter.ParameterType);
				reference.Parameters.Add(new ParameterDefinition(p));
			}

			foreach (var generic_parameter in self.GenericParameters)
				reference.GenericParameters.Add(new GenericParameter(generic_parameter.Name, reference));

			return reference;
		}
 public static CustomAttribute Clone(CustomAttribute custattr, ModuleDefinition context,
     IImportMapper mapper)
 {
     var ca = new CustomAttribute(context.Import(custattr.Constructor, mapper));
     custattr.CopyTo(ca, context, mapper);
     return ca;
 }
Exemple #16
0
        public Either<MemberReference, PropertyReferenceContainer> Convert(IAstReference astReference, ModuleDefinition module, IReferenceProvider recursive)
        {
            if (astReference != AstVoidType.Instance)
                return null;

            return module.Import(typeof(void));
        }
Exemple #17
0
        private static void GenerateFunctionCall(ModuleDefinition module, MethodDefinition method)
        {
            Console.WriteLine("Modifing {0}", method.Name);

            method.Body.Instructions.Clear();

            var gen = method.Body.GetILProcessor();

            int paramaters = method.Parameters.Count;

            for (int arg = 0; arg < paramaters; ++arg)
            {
                if (arg == 0)
                {
                    gen.Emit(OpCodes.Ldarg_0);
                }
                else if (arg == 1)
                {
                    gen.Emit(OpCodes.Ldarg_1);
                }
                else if (arg == 2)
                {
                    gen.Emit(OpCodes.Ldarg_2);
                }
                else if (arg == 3)
                {
                    gen.Emit(OpCodes.Ldarg_3);
                }
                else if (arg <= byte.MaxValue)
                {
                    gen.Emit(OpCodes.Ldarg_S, (byte)arg);
                }
                else
                {
                    gen.Emit(OpCodes.Ldarg, (ushort)arg);
                }
            }

            var intptr = module.Import(typeof(IntPtr));

            gen.Emit(OpCodes.Ldsfld,
                new FieldReference("context", method.DeclaringType, method.DeclaringType));
            gen.Emit(OpCodes.Ldfld,
                new FieldReference("gl" + method.Name, intptr, method.DeclaringType));

            var topointer = module.Import(typeof(IntPtr).GetMethod("ToPointer"));

            var callsite = new CallSite(method.ReturnType);
            callsite.CallingConvention = MethodCallingConvention.StdCall;
            foreach (var param in method.Parameters)
            {
                var newParam = new ParameterDefinition(param.ParameterType);
                callsite.Parameters.Add(newParam);
            }

            gen.Emit(OpCodes.Calli, callsite);

            gen.Emit(OpCodes.Ret);
        }
		public static void ImportTypes(this MethodReference self, ModuleDefinition module)
		{
			if (self.HasParameters)
			{
				for (var i = 0; i < self.Parameters.Count; i++)
					self.Parameters[i].ParameterType = module.Import(self.Parameters[i].ParameterType);
			}
		}
    public static void FindReferences(IAssemblyResolver assemblyResolver, ModuleDefinition moduleDefinition)
    {
        var baseLib = assemblyResolver.Resolve("mscorlib");
        var baseLibTypes = baseLib.MainModule.Types;

        var winrt = !baseLibTypes.Any(type => type.Name == "Object");
        if (winrt)
        {
            baseLib = assemblyResolver.Resolve("System.Runtime");
            baseLibTypes = baseLib.MainModule.Types;
        }

        var argumentException = baseLibTypes.First(x => x.Name == "ArgumentException");
        ArgumentExceptionConstructor = moduleDefinition.Import(argumentException.Methods.First(x =>
            x.IsConstructor &&
            x.Parameters.Count == 2 &&
            x.Parameters[0].ParameterType.Name == "String" &&
            x.Parameters[1].ParameterType.Name == "String"));

        var argumentNullException = baseLibTypes.First(x => x.Name == "ArgumentNullException");
        ArgumentNullExceptionConstructor = moduleDefinition.Import(argumentNullException.Methods.First(x =>
            x.IsConstructor &&
            x.Parameters.Count == 1 &&
            x.Parameters[0].ParameterType.Name == "String"));
        ArgumentNullExceptionWithMessageConstructor = moduleDefinition.Import(argumentNullException.Methods.First(x =>
            x.IsConstructor &&
            x.Parameters.Count == 2 &&
            x.Parameters[0].ParameterType.Name == "String" &&
            x.Parameters[1].ParameterType.Name == "String"));

        var invalidOperationException = baseLibTypes.First(x => x.Name == "InvalidOperationException");
        InvalidOperationExceptionConstructor = moduleDefinition.Import(invalidOperationException.Methods.First(x =>
            x.IsConstructor &&
            x.Parameters.Count == 1 &&
            x.Parameters[0].ParameterType.Name == "String"));

        var debugLib = !winrt ? assemblyResolver.Resolve("System") : assemblyResolver.Resolve("System.Diagnostics.Debug");
        var debugLibTypes = debugLib.MainModule.Types;

        var debug = debugLibTypes.First(x => x.Name == "Debug");
        DebugAssertMethod = moduleDefinition.Import(debug.Methods.First(x =>
            x.IsStatic &&
            x.Parameters.Count == 2 &&
            x.Parameters[0].ParameterType.Name == "Boolean" &&
            x.Parameters[1].ParameterType.Name == "String"));
    }
        public static MethodReference GetEmptyConstructor(this TypeDefinition type,
            ModuleDefinition moduleDefinition)
        {
            var typeEmptyConstructor = type.GetConstructors()
                .FirstOrDefault(c => (null == c.Parameters) || (0 >= c.Parameters.Count));

            return null != typeEmptyConstructor ? moduleDefinition.Import(typeEmptyConstructor) : null;
        }
Exemple #21
0
 /// <summary>
 /// Adds the necessary local variables to the GetServiceHashCode method.
 /// </summary>
 /// <param name="module">The target module.</param>
 /// <param name="body">The method body of the GetServiceHashCode method.</param>
 /// <returns>The variable that holds the hash code.</returns>
 private static VariableDefinition AddLocals(ModuleDefinition module, Mono.Cecil.Cil.MethodBody body)
 {
     var integerType = module.Import(typeof(int));
     var hashVariable = new VariableDefinition(integerType);
     body.Variables.Add(hashVariable);
     body.InitLocals = true;
     body.MaxStackSize = 3;
     return hashVariable;
 }
 /// <summary>
 /// Inject an enum definition to a module definition
 /// </summary>
 /// <param name="mdef">Module definition</param>
 /// <param name="name">Enum name</param>
 /// <returns>the new enum with related value__ field</returns>
 public static TypeDefinition InjectEnumDefinition(ModuleDefinition mdef, string name)
 {
     var edef = InjectTypeDefinition(mdef, name, mdef.Import(typeof(System.Enum)));
     edef.IsSealed = true;
     var fdef = InjectFieldDefinition(edef, "value__", edef.Module.Import(typeof(int)));
     fdef.IsRuntimeSpecialName = true;
     fdef.IsSpecialName = true;
     return edef;
 }
Exemple #23
0
        private static void GenerateMemoryType(ModuleDefinition module)
        {
            var type = module.Types.First(t => t.Name == "Memory");
            type.BaseType = module.Import(typeof(object));

            GenerateCopy(module, type);
            GenerateFill(module, type);
            GenerateWrite(module, type);
            GenerateRead(module, type);
            GenerateSizeOf(module, type);
        }
Exemple #24
0
        public static void EmitCreateDelegateToLocalMethod(ModuleDefinition module, ILProcessor worker, TypeDefinition declaringType, MethodDefinition source, out VariableDefinition dlg, out MethodDefinition ctor, out MethodDefinition invok)
        {
            // Define some variables
            var body = worker.Body;
            var method = body.Method;
            var newdlg = new VariableDefinition(module.Import(typeof(Delegate)));
            body.Variables.Add(newdlg);

            var multiDelegateType = module.Import(typeof(MulticastDelegate));
            var voidType = module.Import(typeof(void));
            var objectType = module.Import(typeof(object));
            var nativeIntType = module.Import(typeof(IntPtr));
            var asyncCallbackType = module.Import(typeof(AsyncCallback));
            var asyncResultType = module.Import(typeof(IAsyncResult));

            // Create new delegate type
            var dlgtype = new TypeDefinition(declaringType.Namespace, method.Name + "_Delegate" + declaringType.NestedTypes.Count,
                                             TypeAttributes.Sealed | TypeAttributes.NestedAssembly | TypeAttributes.RTSpecialName, multiDelegateType);
            declaringType.NestedTypes.Add(dlgtype);
            dlgtype.IsRuntimeSpecialName = true;

            var constructor = new MethodDefinition(".ctor", MethodAttributes.Public | MethodAttributes.CompilerControlled | MethodAttributes.RTSpecialName | MethodAttributes.SpecialName | MethodAttributes.HideBySig, voidType);
            dlgtype.Methods.Add(constructor);
            constructor.Parameters.Add(new ParameterDefinition("object", ParameterAttributes.None, objectType));
            constructor.Parameters.Add(new ParameterDefinition("method", ParameterAttributes.None, nativeIntType));
            constructor.IsRuntime = true;

            var begininvoke = new MethodDefinition("BeginInvoke", MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Virtual, asyncResultType);
            dlgtype.Methods.Add(begininvoke);
            foreach (var para in source.Parameters)
            {
                begininvoke.Parameters.Add(new ParameterDefinition(para.Name, para.Attributes, para.ParameterType));
            }
            begininvoke.Parameters.Add(new ParameterDefinition("callback", ParameterAttributes.None, asyncCallbackType));
            begininvoke.Parameters.Add(new ParameterDefinition("object", ParameterAttributes.None, objectType));
            begininvoke.IsRuntime = true;

            var endinvoke = new MethodDefinition("EndInvoke", MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Virtual, voidType);
            dlgtype.Methods.Add(endinvoke);
            endinvoke.Parameters.Add(new ParameterDefinition("result", ParameterAttributes.None, asyncResultType));
            endinvoke.IsRuntime = true;
            endinvoke.ReturnType = source.ReturnType;

            var invoke = new MethodDefinition("Invoke", MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Virtual, voidType);
            dlgtype.Methods.Add(invoke);
            foreach (var para in source.Parameters)
            {
                invoke.Parameters.Add(new ParameterDefinition(para.Name, para.Attributes, para.ParameterType));
            }
            invoke.IsRuntime = true;
            invoke.ReturnType = source.ReturnType;

            ctor = constructor;
            dlg = newdlg;
            invok = invoke;
        }
Exemple #25
0
		public void SetUp()
		{
			AssemblyNameDefinition name = new AssemblyNameDefinition($"_{Guid.NewGuid()}", new Version(1, 0));
			AssemblyDefinition assembly = AssemblyDefinition.CreateAssembly(name, name.Name, ModuleKind.Dll);
			TestModule = ModuleDefinition.CreateModule(name.Name, ModuleKind.Dll);
			assembly.Modules.Add(TestModule);
			foreach (var asm in this.GetType().Assembly.GetReferencedAssemblies())
				assembly.MainModule.AssemblyReferences.Add(new AssemblyNameDefinition(asm.FullName, asm.Version));
			TestType = new TypeDefinition("", $"_{Guid.NewGuid()}", TypeAttributes.Class | TypeAttributes.Public, TestModule.Import(typeof(object)));
			TestModule.Types.Add(TestType);
			AddEmptyConstructor();
		}
Exemple #26
0
        public TypeDefinition CreateClass(ModuleDefinition module, string @namespace, string name, TypeReference baseType = null)
        {
            if (baseType == null)
                baseType = module.Import(typeof(object));

            var newType = new TypeDefinition(
                @namespace,
                name,
                TypeAttributes.AutoClass | TypeAttributes.AnsiClass | TypeAttributes.Public,
                baseType);
            module.Types.Add(newType);
            return newType;
        }
        public static TypeReference ParseTypeReference(object o, ModuleDefinition module)
        {
            TypeReference tr = null;

            if (o is TypeReference)
            {
                tr = module.Import((TypeReference)o);
            }
            else if (o is Type)
            {
                tr = module.Import((Type)o);
            }
            else if(o is string)
            {
                string typeName = o as string;
                Type type = Type.GetType(typeName, false, true);
                if (type != null)
                {
                    tr = module.Import(type);
                }
            }            

            return tr;
        }
		public void OnFile(string fileName, ModuleDefinition module)
		{
			replaced = 0;
			skipped = 0;

			TypeReference delegateTypeDef = module.Import(typeof(Delegate));
			
			 combineR = delegateTypeDef.Module.Import(
				typeof(Delegate).GetMethod("Combine", 
			                           new Type[] { typeof(Delegate), typeof(Delegate) })); 
			
			removeR = delegateTypeDef.Module.Import(
				typeof(Delegate).GetMethod("Remove", 
			                           new Type[] { typeof(Delegate), typeof(Delegate) })); 
		}
Exemple #29
0
        public void Mix(ModuleDefinition targetModule)
        {
            Contract.Requires(targetModule != null);

            var originalTypes = new List<TypeDefinition>(targetModule.Types);
            var encapsulatesAttributeType = targetModule.Import(typeof(EncapsulatesAttribute)).Resolve();
            foreach (var type in originalTypes)
            {
                var encapsulatesAttribute = type.CustomAttributes.SingleOrDefault(
                    customAttribute => customAttribute.AttributeType.Resolve() == encapsulatesAttributeType);

                if (encapsulatesAttribute != null)
                {
                    type.CustomAttributes.Remove(encapsulatesAttribute);
                    AddEncapsulation(type);
                }
            }
        }
		protected CustomAttributeArgument FixCustomAttributeArgument(ModuleDefinition module, CustomAttributeArgument argument)
		{
			var value = argument.Value;

			if (value is TypeReference)
				value = module.Import(value as TypeReference);

			if (value is CustomAttributeArgument[])
			{
				var arguments = value as CustomAttributeArgument[];
				for (var i = 0; i < arguments.Length; i++)
					arguments[i] = FixCustomAttributeArgument(module, arguments[i]);
			}

			// Used for wrapped CustomAttributeArgument[]
			if (argument.Type.Module == null)
				argument.Type = module.TypeSystem.LookupType(argument.Type.Namespace, argument.Type.Name);

			return new CustomAttributeArgument(module.Import(argument.Type), value);
		}
Exemple #31
0
 public static MethodReference ImportEx(this ModuleDefinition module, MethodReference method, IGenericParameterProvider context)
 {
     return(module.Import(method, context));
 }
Exemple #32
0
 public static TypeReference ImportEx(this ModuleDefinition module, TypeReference type, IGenericParameterProvider context)
 {
     return(module.Import(type, context));
 }
Exemple #33
0
 public static FieldReference ImportEx(this ModuleDefinition module, FieldReference field, IGenericParameterProvider context)
 {
     return(module.Import(field, context));
 }
Exemple #34
0
 public static FieldReference ImportEx(this ModuleDefinition module, FieldReference field)
 {
     return(module.Import(field));
 }
Exemple #35
0
 public static MethodReference ImportEx(this ModuleDefinition module, MethodReference method)
 {
     return(module.Import(method));
 }
Exemple #36
0
 public static TypeReference ImportEx(this ModuleDefinition module, TypeReference type)
 {
     return(module.Import(type));
 }