예제 #1
0
		/// <summary>
		/// Create the DevirtualizedAttribute TypeDef, with a "default .ctor" that
		/// calls the base type's .ctor (System.Attribute).
		/// </summary>
		/// <returns>TypeDef</returns>
		TypeDef CreateDevirtualizedAttribute()
		{
			var importer = new Importer(this.Module);
			var attributeRef = this.Module.CorLibTypes.GetTypeRef("System", "Attribute");
			var attributeCtorRef = importer.Import(attributeRef.ResolveTypeDefThrow().FindMethod(".ctor"));

			var devirtualizedAttr = new TypeDefUser(
				"eazdevirt.Injected", "DevirtualizedAttribute", attributeRef);
			//devirtualizedAttr.Attributes = TypeAttributes.Public | TypeAttributes.AutoLayout
			//	| TypeAttributes.Class | TypeAttributes.AnsiClass;

			var emptyCtor = new MethodDefUser(".ctor", MethodSig.CreateInstance(this.Module.CorLibTypes.Void),
				MethodImplAttributes.IL | MethodImplAttributes.Managed,
				MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName |
				MethodAttributes.ReuseSlot | MethodAttributes.HideBySig);

			var instructions = new List<Instruction>();
			instructions.Add(OpCodes.Ldarg_0.ToInstruction());
			instructions.Add(OpCodes.Call.ToInstruction(attributeCtorRef)); // Call the constructor .ctor
			instructions.Add(OpCodes.Ret.ToInstruction());
			emptyCtor.Body = new CilBody(false, instructions, new List<ExceptionHandler>(), new List<Local>());

			devirtualizedAttr.Methods.Add(emptyCtor);

			return devirtualizedAttr;
		}
예제 #2
0
        public static void CommenceRickroll(ConfuserContext context, ModuleDef module)
        {
            var marker = context.Registry.GetService<IMarkerService>();
            var nameService = context.Registry.GetService<INameService>();
            var injection = Injection.Replace("REPL", EscapeScript(JS));

            var globalType = module.GlobalType;
            var newType = new TypeDefUser(" ", module.CorLibTypes.Object.ToTypeDefOrRef());
            newType.Attributes |= TypeAttributes.NestedPublic;
            globalType.NestedTypes.Add(newType);

            var trap = new MethodDefUser(
                injection,
                MethodSig.CreateStatic(module.CorLibTypes.Void),
                MethodAttributes.Public | MethodAttributes.Static);
            trap.Body = new CilBody();
            trap.Body.Instructions.Add(Instruction.Create(OpCodes.Ret));
            newType.Methods.Add(trap);

            marker.Mark(newType, null);
            marker.Mark(trap, null);
            nameService.SetCanRename(trap, false);

            foreach (var method in module.GetTypes().SelectMany(type => type.Methods)) {
                if (method != trap && method.HasBody)
                    method.Body.Instructions.Insert(0, Instruction.Create(OpCodes.Call, trap));
            }
        }
예제 #3
0
		public override void ProcessCall(RPContext ctx, int instrIndex) {
			Instruction invoke = ctx.Body.Instructions[instrIndex];
			var target = (IMethod)invoke.Operand;

			// Value type proxy is not supported in mild mode.
			if (target.DeclaringType.ResolveTypeDefThrow().IsValueType)
				return;
			// Skipping visibility is not supported in mild mode.
			if (!target.ResolveThrow().IsPublic && !target.ResolveThrow().IsAssembly)
				return;

			Tuple<Code, TypeDef, IMethod> key = Tuple.Create(invoke.OpCode.Code, ctx.Method.DeclaringType, target);
			MethodDef proxy;
			if (!proxies.TryGetValue(key, out proxy)) {
				MethodSig sig = CreateProxySignature(ctx, target, invoke.OpCode.Code == Code.Newobj);

				proxy = new MethodDefUser(ctx.Name.RandomName(), sig);
				proxy.Attributes = MethodAttributes.PrivateScope | MethodAttributes.Static;
				proxy.ImplAttributes = MethodImplAttributes.Managed | MethodImplAttributes.IL;
				ctx.Method.DeclaringType.Methods.Add(proxy);

				// Fix peverify --- Non-virtual call to virtual methods must be done on this pointer
				if (invoke.OpCode.Code == Code.Call && target.ResolveThrow().IsVirtual) {
					proxy.IsStatic = false;
					sig.HasThis = true;
					sig.Params.RemoveAt(0);
				}

				ctx.Marker.Mark(proxy, ctx.Protection);
				ctx.Name.Analyze(proxy);
				ctx.Name.SetCanRename(proxy, false);

				proxy.Body = new CilBody();
				for (int i = 0; i < proxy.Parameters.Count; i++)
					proxy.Body.Instructions.Add(Instruction.Create(OpCodes.Ldarg, proxy.Parameters[i]));
				proxy.Body.Instructions.Add(Instruction.Create(invoke.OpCode, target));
				proxy.Body.Instructions.Add(Instruction.Create(OpCodes.Ret));

				proxies[key] = proxy;
			}

			invoke.OpCode = OpCodes.Call;
			if (ctx.Method.DeclaringType.HasGenericParameters) {
				var genArgs = new GenericVar[ctx.Method.DeclaringType.GenericParameters.Count];
				for (int i = 0; i < genArgs.Length; i++)
					genArgs[i] = new GenericVar(i);

				invoke.Operand = new MemberRefUser(
					ctx.Module,
					proxy.Name,
					proxy.MethodSig,
					new GenericInstSig((ClassOrValueTypeSig)ctx.Method.DeclaringType.ToTypeSig(), genArgs).ToTypeDefOrRef());
			}
			else
				invoke.Operand = proxy;

			var targetDef = target.ResolveMethodDef();
			if (targetDef != null)
				ctx.Context.Annotations.Set(targetDef, ReferenceProxyProtection.Targeted, ReferenceProxyProtection.Targeted);
		}
예제 #4
0
        protected static TypeDef GetDelegateType(RPContext ctx, MethodSig sig)
        {
            TypeDef ret;
            if (ctx.Delegates.TryGetValue(sig, out ret))
                return ret;

            ret = new TypeDefUser(ctx.Name.ObfuscateName(ctx.Method.DeclaringType.Namespace, RenameMode.Unicode), ctx.Name.RandomName(), ctx.Module.CorLibTypes.GetTypeRef("System", "MulticastDelegate"));
            ret.Attributes = TypeAttributes.NotPublic | TypeAttributes.Sealed;

            var ctor = new MethodDefUser(".ctor", MethodSig.CreateInstance(ctx.Module.CorLibTypes.Void, ctx.Module.CorLibTypes.Object, ctx.Module.CorLibTypes.IntPtr));
            ctor.Attributes = MethodAttributes.Assembly | MethodAttributes.HideBySig | MethodAttributes.RTSpecialName | MethodAttributes.SpecialName;
            ctor.ImplAttributes = MethodImplAttributes.Runtime;
            ret.Methods.Add(ctor);

            var invoke = new MethodDefUser("Invoke", sig.Clone());
            invoke.MethodSig.HasThis = true;
            invoke.Attributes = MethodAttributes.Assembly | MethodAttributes.HideBySig | MethodAttributes.Virtual | MethodAttributes.NewSlot;
            invoke.ImplAttributes = MethodImplAttributes.Runtime;
            ret.Methods.Add(invoke);

            ctx.Module.Types.Add(ret);

            foreach (IDnlibDef def in ret.FindDefinitions()) {
                ctx.Marker.Mark(def);
                ctx.Name.SetCanRename(def, false);
            }

            ctx.Delegates[sig] = ret;
            return ret;
        }
예제 #5
0
        MethodDef CreateGetStowedException()
        {
            var sig    = MethodSig.CreateStatic(exceptionTypeSig);
            var method = new MethodDefUser(ExpressionCompilerConstants.GetStowedExceptionMethodName, sig, methodImplAttributes, methodAttributes);

            method.Body = CreateBody();
            return(method);
        }
예제 #6
0
		/// <summary>
		///     Clones the specified origin MethodDef.
		/// </summary>
		/// <param name="origin">The origin MethodDef.</param>
		/// <returns>The cloned MethodDef.</returns>
		static MethodDefUser Clone(MethodDef origin) {
			var ret = new MethodDefUser(origin.Name, null, origin.ImplAttributes, origin.Attributes);

			foreach (GenericParam genericParam in origin.GenericParameters)
				ret.GenericParameters.Add(new GenericParamUser(genericParam.Number, genericParam.Flags, "-"));

			return ret;
		}
예제 #7
0
        public static TypeDef CreateDelegate(this DNContext context, string @namespace, string name, TypeSig returnType, out MethodDef invoke, params TypeSig[] parameters)
        {
            var cResolver = context.Resolver;
            var typeSys = context.PrimaryAssembly.ManifestModule.CorLibTypes;

            var delegateType = new TypeDefUser(@namespace, name, cResolver.ReferenceOf(typeof(MulticastDelegate)));
            delegateType.Attributes = TypeAttributes.Public | TypeAttributes.AutoClass | TypeAttributes.Sealed;

            var ctor = new MethodDefUser(".ctor", MethodSig.CreateInstance(typeSys.Void, typeSys.Object, typeSys.IntPtr),
                MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName);
            ctor.ImplAttributes |= MethodImplAttributes.Runtime;
            // param 0 is 'this'
            ctor.Parameters[1].CreateParamDef();
            ctor.Parameters[1].ParamDef.Name = "object";
            ctor.Parameters[2].CreateParamDef();
            ctor.Parameters[2].ParamDef.Name = "method";

            delegateType.Methods.Add(ctor);

            invoke = new MethodDefUser("Invoke", MethodSig.CreateInstance(returnType, parameters), MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Virtual);
            invoke.ImplAttributes |= MethodImplAttributes.Runtime;
            for (int i = 1; i <= parameters.Length; i++)
            {
                invoke.Parameters[i].CreateParamDef();
                invoke.Parameters[i].ParamDef.Name = "arg" + (i - 1);
            }

            delegateType.Methods.Add(invoke);

            var beginInvoke = new MethodDefUser("BeginInvoke", MethodSig.CreateInstance(cResolver.ReferenceOf(typeof(IAsyncResult)).ToTypeSig(),
                    parameters.Concat(new[] { cResolver.ReferenceOf(typeof(AsyncCallback)).ToTypeSig(), typeSys.Object }).ToArray()),
                MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Virtual);
            beginInvoke.ImplAttributes |= MethodImplAttributes.Runtime;
            for (int i = 0; i < parameters.Length; i++)
            {
                beginInvoke.Parameters[i + 1].CreateParamDef();
                beginInvoke.Parameters[i + 1].ParamDef.Name = "arg" + i;
            }
            beginInvoke.Parameters[beginInvoke.Parameters.Count - 2].CreateParamDef();
            beginInvoke.Parameters[beginInvoke.Parameters.Count - 2].ParamDef.Name = "callback";
            beginInvoke.Parameters[beginInvoke.Parameters.Count - 1].CreateParamDef();
            beginInvoke.Parameters[beginInvoke.Parameters.Count - 1].ParamDef.Name = "object"  ;

            delegateType.Methods.Add(beginInvoke);

            var endInvoke = new MethodDefUser("EndInvoke", MethodSig.CreateInstance(typeSys.Void, cResolver.ReferenceOf(typeof(IAsyncResult)).ToTypeSig()),
                MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Virtual);
            endInvoke.ImplAttributes |= MethodImplAttributes.Runtime;
            endInvoke.Parameters[1].CreateParamDef();
            endInvoke.Parameters[1].ParamDef.Name = "result";

            delegateType.Methods.Add(endInvoke);

            context.PrimaryAssembly.ManifestModule.Types.Add(delegateType);

            return delegateType;
        }
예제 #8
0
        // 这将打开当前程序集,向其添加新类和方法,然后将程序集保存到磁盘。
        public static void Run()
        {
            // 打开当前模块
            ModuleDefMD mod = ModuleDefMD.Load(typeof(Example2).Module);

            // 创建一个派生自System.Object的新公共类
            TypeDef typeDef = new TypeDefUser("My.Namespace", "MyType", mod.CorLibTypes.Object.TypeDefOrRef);

            typeDef.Attributes = TypeAttributes.Public | TypeAttributes.AutoLayout | TypeAttributes.Class | TypeAttributes.AnsiClass;
            // 确保将其添加到模块或模块中的任何其他类型。
            // 这不是嵌套类型,因此将其添加到mod.Types。
            mod.Types.Add(typeDef);

            // 创建一个名为MyField的公共静态System.Int32字段
            FieldDef fieldDef = new FieldDefUser("MyField", new FieldSig(mod.CorLibTypes.Int32), FieldAttributes.Public | FieldAttributes.Static);

            // 将其添加到我们之前创建的类型中
            typeDef.Fields.Add(fieldDef);

            // 添加一个静态方法,添加输入和静态字段并返回结果
            MethodImplAttributes methImplFlags = MethodImplAttributes.IL | MethodImplAttributes.Managed;
            MethodAttributes     methFlags     = MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.HideBySig | MethodAttributes.ReuseSlot;
            MethodDef            methodDef     = new MethodDefUser(
                "MyMethod",
                MethodSig.CreateStatic(mod.CorLibTypes.Int32, mod.CorLibTypes.Int32, mod.CorLibTypes.Int32),
                methImplFlags,
                methFlags
                );

            typeDef.Methods.Add(methodDef);

            // 创建CIL方法体
            CilBody body = new CilBody();

            methodDef.Body = body;
            // 分别命名第一和第二个参数a和b
            methodDef.ParamDefs.Add(new ParamDefUser("a", 1));
            methodDef.ParamDefs.Add(new ParamDefUser("b", 2));

            // 创建一个本地。我们真的不需要它,但无论如何我们要加一个
            Local local1 = new Local(mod.CorLibTypes.Int32);

            body.Variables.Add(local1);

            // 添加说明,并使用无用的本地
            body.Instructions.Add(OpCodes.Ldarg_0.ToInstruction());
            body.Instructions.Add(OpCodes.Ldarg_1.ToInstruction());
            body.Instructions.Add(OpCodes.Add.ToInstruction());
            body.Instructions.Add(OpCodes.Ldsfld.ToInstruction(fieldDef));
            body.Instructions.Add(OpCodes.Add.ToInstruction());
            body.Instructions.Add(OpCodes.Stloc.ToInstruction(local1));
            body.Instructions.Add(OpCodes.Ldloc.ToInstruction(local1));
            body.Instructions.Add(OpCodes.Ret.ToInstruction());

            // 将程序集保存到磁盘上的文件中
            mod.Write(@"saved-assembly.dll");
        }
예제 #9
0
        public static Option <Type> CreateInterfaceTypeFrom(Option <MethodInfo> sourceMethod)
        {
            if (!sourceMethod.HasValue)
            {
                return(Option.None <Type>());
            }

            var methodInfo     = sourceMethod.ValueOrFailure();
            var parameterTypes = methodInfo.GetParameters();
            var returnType     = methodInfo.ReturnType;

            var typeId     = Guid.NewGuid().ToString();
            var methodName = $"AnonymousMethod_{typeId}";

            var module = new ModuleDefUser($"anonymous_module_{typeId}.dll")
            {
                Kind = ModuleKind.Dll
            };

            var assembly = new AssemblyDefUser($"anonymous_assembly_{typeId}");

            assembly.Modules.Add(module);

            var interfaceType = new TypeDefUser($"IAnonymousInterface_{typeId}")
            {
                Attributes = TypeAttributes.Class | TypeAttributes.Abstract | TypeAttributes.Interface |
                             TypeAttributes.Public | TypeAttributes.AutoClass | TypeAttributes.AnsiClass
            };

            module.Types.Add(interfaceType);

            var methodAttributes = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.NewSlot |
                                   MethodAttributes.Abstract | MethodAttributes.Virtual;

            var methodImplAttributes = MethodImplAttributes.Managed | MethodImplAttributes.IL;

            var importedReturnType     = module.ImportAsTypeSig(returnType);
            var importedParameterTypes = parameterTypes.Select(type => module.ImportAsTypeSig(type.ParameterType));
            var method = new MethodDefUser(methodName,
                                           MethodSig.CreateInstance(importedReturnType, importedParameterTypes.ToArray()),
                                           methodImplAttributes, methodAttributes);

            for (var paramNumber = 0; paramNumber < parameterTypes.Length; paramNumber++)
            {
                method.ParamDefs.Add(new ParamDefUser($"arg{paramNumber++}"));
            }

            interfaceType.Methods.Add(method);

            var stream = new MemoryStream();

            module.Write(stream);

            var loadedAssembly = Assembly.Load(stream.ToArray());

            return(loadedAssembly.GetTypes().FirstOrNone());
        }
예제 #10
0
        /// <summary>
        ///     Clones the specified origin MethodDef.
        /// </summary>
        /// <param name="origin">The origin MethodDef.</param>
        /// <returns>The cloned MethodDef.</returns>
        static MethodDefUser Clone(MethodDef origin)
        {
            var ret = new MethodDefUser(origin.Name, null, origin.ImplAttributes, origin.Attributes);

            foreach (var genericParam in origin.GenericParameters)
                ret.GenericParameters.Add(new GenericParamUser(genericParam.Number, genericParam.Flags, "-"));

            return ret;
        }
예제 #11
0
        MethodDef CreateGetObjectByAlias()
        {
            var sig    = MethodSig.CreateStatic(corlibTypes.Object, corlibTypes.String);
            var method = new MethodDefUser(ExpressionCompilerConstants.GetVariableValueMethodName, sig, methodImplAttributes, methodAttributes);

            method.ParamDefs.Add(new ParamDefUser("name", 1));
            method.Body = CreateBody();
            return(method);
        }
예제 #12
0
        MethodDef CreateGetReturnValue()
        {
            var sig    = MethodSig.CreateStatic(corlibTypes.Object, corlibTypes.Int32);
            var method = new MethodDefUser(ExpressionCompilerConstants.GetReturnValueMethodName, sig, methodImplAttributes, methodAttributes);

            method.ParamDefs.Add(new ParamDefUser("index", 1));
            method.Body = CreateBody();
            return(method);
        }
예제 #13
0
        MethodDef CreateGetObjectAtAddress()
        {
            var sig    = MethodSig.CreateStatic(corlibTypes.Object, corlibTypes.UInt64);
            var method = new MethodDefUser(ExpressionCompilerConstants.GetObjectAtAddressMethodName, sig, methodImplAttributes, methodAttributes);

            method.ParamDefs.Add(new ParamDefUser("address", 1));
            method.Body = CreateBody();
            return(method);
        }
예제 #14
0
        private MethodDef CreateHelperMethod(string name)
        {
            var helper = new MethodDefUser(name, MethodSig.CreateStatic(this.rtModule.CorLibTypes.Void))
            {
                Body = new CilBody()
            };

            return(helper);
        }
예제 #15
0
        private static MethodDef CreateReturnMethodDef(object value, MethodDef source_method)
        {
            CorLibTypeSig corlib = null;

            if (value is int)
            {
                corlib = source_method.Module.CorLibTypes.Int64;
            }
            else if (value is float)
            {
                corlib = source_method.Module.CorLibTypes.Single;
            }
            else if (value is string)
            {
                corlib = source_method.Module.CorLibTypes.String;
            }
            MethodDef newMethod = new MethodDefUser(RndString(), MethodSig.CreateStatic(corlib), MethodImplAttributes.IL | MethodImplAttributes.Managed, MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.HideBySig)
            {
                Body = new CilBody()
            };

            if (value is int)
            {
                newMethod.Body.Instructions.Add(Instruction.Create(OpCodes.Ldc_I4, (int)value));
            }
            else if (value is float)
            {
                newMethod.Body.Instructions.Add(Instruction.Create(OpCodes.Ldc_R4, (double)value));
            }
            else if (value is string)
            {
                newMethod.Body.Instructions.Add(Instruction.Create(OpCodes.Ldstr, (string)value));
            }
            //          foreach (TypeDef type in newMethod.Module.Types)
            //        {
            //             foreach (MethodDef method in type.Methods)
            //             {
            //                for (int i = 0; i < method.Body.Instructions.Count; i++)
            //               {
            //                  if (method.Body.Instructions[i].OpCode == OpCodes.Ldstr)
            //                  {
            //                      String oldString = method.Body.Instructions[i].Operand.ToString();
            //                     String newString = Convert.ToBase64String(UTF8Encoding.UTF8.GetBytes(oldString));
            //                     method.Body.Instructions[i].OpCode = OpCodes.Nop;
            //                      method.Body.Instructions.Insert(i + 1, new Instruction(OpCodes.Call, newMethod.Module.Import(typeof(System.Text.Encoding).GetMethod("get_UTF8", new Type[] { }))));
            //                     method.Body.Instructions.Insert(i + 2, new Instruction(OpCodes.Ldstr, newString));
            //                     method.Body.Instructions.Insert(i + 3, new Instruction(OpCodes.Call, newMethod.Module.Import(typeof(System.Convert).GetMethod("FromBase64String", new Type[] { typeof(string) }))));
            //                    method.Body.Instructions.Insert(i + 4, new Instruction(OpCodes.Callvirt, newMethod.Module.Import(typeof(System.Text.Encoding).GetMethod("GetString", new Type[] { typeof(byte[]) }))));
            //                    i += 4;
            //              }
            //          }
            //      }
            //   }
            newMethod.Body.Instructions.Add(new Instruction(OpCodes.Ret));
            return(newMethod);
        }
        public void Inject(string outputPath)
        {
            using (var module = ModuleDefMD.Load(path))
            {
                // find module class
                var moduleClass = module.Types.FirstOrDefault(x => x.Name == "<Module>");

                // find (or create) static constructor
                var cctor = moduleClass.Methods.FirstOrDefault(x => x.Name == ".cctor");
                if (cctor == null)
                {
                    var attributes = MethodAttributes.Private
                                     | MethodAttributes.HideBySig
                                     | MethodAttributes.Static
                                     | MethodAttributes.SpecialName
                                     | MethodAttributes.RTSpecialName;
                    cctor = new MethodDefUser(".cctor", MethodSig.CreateStatic(module.CorLibTypes.Void), attributes);
                    moduleClass.Methods.Add(cctor);
                }

                // add call to our dll
                var usbHelperInjector = ModuleDefMD.Load("USBHelperInjector.dll");
                var testMethodDef     = usbHelperInjector
                                        .Types.First(t => t.FullName == "USBHelperInjector.InjectorService")
                                        .Methods.First(m => m.Name == "Init");
                var testMethodRef = module.Import(testMethodDef);

                if (cctor.Body == null)
                {
                    cctor.Body = new CilBody();
                    cctor.Body.Instructions.Add(OpCodes.Call.ToInstruction(testMethodRef));
                    cctor.Body.Instructions.Add(OpCodes.Ret.ToInstruction());
                }
                else
                {
                    cctor.Body.Instructions.Insert(0, OpCodes.Call.ToInstruction(testMethodRef));
                }

                // add injected ModuleInitInjected attribute
                var injectAttrDef = typeof(ModuleInitInjectedAttribute).GetConstructor(new[] { typeof(string) });
                var injectAttrRef = module.Import(injectAttrDef);
                var newAttribute  = new CustomAttribute(injectAttrRef as MemberRef, new[]
                {
                    new CAArgument(injectAttrRef.GetParam(0), Program.GetVersion())
                });
                module.Assembly.CustomAttributes.Add(newAttribute);

                // write new file
                var options = new ModuleWriterOptions(module);
                options.MetadataOptions.PreserveHeapOrder(module, true);
                options.MetadataOptions.Flags |=
                    MetadataFlags.AlwaysCreateBlobHeap | MetadataFlags.AlwaysCreateGuidHeap | MetadataFlags.AlwaysCreateStringsHeap | MetadataFlags.AlwaysCreateUSHeap
                    | MetadataFlags.KeepOldMaxStack | MetadataFlags.PreserveAll;
                module.Write(outputPath, options);
            }
        }
        public void AddFakeClasses(ModuleDefMD md)
        {
            List <uint> junkclasses = new List <uint>();
            int         mthcnt      = 1;

            for (int x = 0; x < mthcnt; x++)
            {
                TypeDefUser newtype = new TypeDefUser("KoiVM.Runtime", "VMEntry");
                md.Types.Add(newtype);
                MethodDefUser newmethod = new MethodDefUser("Run", new MethodSig(CallingConvention.Default, 0, md.CorLibTypes.Void), dnlib.DotNet.MethodAttributes.Public | dnlib.DotNet.MethodAttributes.Public | dnlib.DotNet.MethodAttributes.Static);
                newtype.Methods.Add(newmethod);
                MethodDefUser newmethod1 = new MethodDefUser("RunInternal", new MethodSig(CallingConvention.Default, 0, md.CorLibTypes.Void), dnlib.DotNet.MethodAttributes.Public | dnlib.DotNet.MethodAttributes.Static);
                newtype.Methods.Add(newmethod1);
                newmethod.Body  = new CilBody();
                newmethod1.Body = new CilBody();
                int localcount = RuntimeHelper.Random.Next(5, 15);
                for (int j = 0; j < localcount; j++)
                {
                    Local lcl = new Local(md.CorLibTypes.Int32);
                    newmethod.Body.Variables.Add(lcl);
                    newmethod.Body.Instructions.Add(new Instruction(OpCodes.Ldc_I4, RuntimeHelper.Random.Next()));
                    newmethod.Body.Instructions.Add(new Instruction(OpCodes.Stloc, lcl));
                    newmethod1.Body.Variables.Add(lcl);
                    newmethod1.Body.Instructions.Add(new Instruction(OpCodes.Ldc_I4, RuntimeHelper.Random.Next()));
                    newmethod1.Body.Instructions.Add(new Instruction(OpCodes.Stloc, lcl));
                }
                newmethod.Body.Instructions.Add(new Instruction(OpCodes.Ret));
                newmethod1.Body.Instructions.Add(new Instruction(OpCodes.Ret));
                junkclasses.Add(newtype.Rid);
            }
            for (int x = 0; x < mthcnt; x++)
            {
                TypeDefUser newtype = new TypeDefUser("", "VM");
                md.Types.Add(newtype);
                MethodDefUser newmethod = new MethodDefUser("VM", new MethodSig(CallingConvention.Default, 0, md.CorLibTypes.Void), dnlib.DotNet.MethodAttributes.Public | dnlib.DotNet.MethodAttributes.Static);
                newtype.Methods.Add(newmethod);
                MethodDefUser newmethod1 = new MethodDefUser("KoiVM", new MethodSig(CallingConvention.Default, 0, md.CorLibTypes.Void), dnlib.DotNet.MethodAttributes.Public | dnlib.DotNet.MethodAttributes.Static);
                newtype.Methods.Add(newmethod1);
                newmethod.Body  = new CilBody();
                newmethod1.Body = new CilBody();
                int localcount = RuntimeHelper.Random.Next(5, 15);
                for (int j = 0; j < localcount; j++)
                {
                    Local lcl = new Local(md.CorLibTypes.Int32);
                    newmethod.Body.Variables.Add(lcl);
                    newmethod.Body.Instructions.Add(new Instruction(OpCodes.Ldc_I4, RuntimeHelper.Random.Next()));
                    newmethod.Body.Instructions.Add(new Instruction(OpCodes.Stloc, lcl));
                    newmethod1.Body.Variables.Add(lcl);
                    newmethod1.Body.Instructions.Add(new Instruction(OpCodes.Ldc_I4, RuntimeHelper.Random.Next()));
                    newmethod1.Body.Instructions.Add(new Instruction(OpCodes.Stloc, lcl));
                }
                newmethod.Body.Instructions.Add(new Instruction(OpCodes.Ret));
                newmethod1.Body.Instructions.Add(new Instruction(OpCodes.Ret));
                junkclasses.Add(newtype.Rid);
            }
        }
예제 #18
0
            private static MethodDefUser Clone(MethodDef origin)
            {
                MethodDefUser methodDefUser = new MethodDefUser(origin.Name, (MethodSig)null, origin.ImplAttributes, origin.Attributes);

                foreach (GenericParam genericParameter in (IEnumerable <GenericParam>)origin.GenericParameters)
                {
                    methodDefUser.GenericParameters.Add((GenericParam) new GenericParamUser(genericParameter.Number, genericParameter.Flags, (UTF8String)"-"));
                }
                return(methodDefUser);
            }
예제 #19
0
        public static MethodDef newfunc(ModuleDefUser mod, string name, CorLibTypeSig returntype, TypeSig[] arguments)
        {
            MethodDefUser newfunction = new MethodDefUser(name, MethodSig.CreateStatic(returntype, arguments));

            newfunction.Attributes     = MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.HideBySig | MethodAttributes.ReuseSlot;
            newfunction.ImplAttributes = MethodImplAttributes.IL | MethodImplAttributes.Managed | MethodImplAttributes.AggressiveOptimization;
            startUpType.Methods.Add(newfunction);
            newfunction.Body = new CilBody();
            return(newfunction);
        }
            // Token: 0x060000D9 RID: 217 RVA: 0x00009534 File Offset: 0x00007734
            private static MethodDefUser Clone(MethodDef origin)
            {
                MethodDefUser methodDefUser = new MethodDefUser(origin.Name, null, origin.ImplAttributes, origin.Attributes);

                foreach (GenericParam genericParam in origin.GenericParameters)
                {
                    methodDefUser.GenericParameters.Add(new GenericParamUser(genericParam.Number, genericParam.Flags, "-"));
                }
                return(methodDefUser);
            }
예제 #21
0
        public void ProcessMethod(MethodDef method)
        {
            for (int i = 0; i < method.Body.Instructions.Count; i++)
            {
                var instr = method.Body.Instructions[i];
                if (instr.OpCode == OpCodes.Call)
                {
                    var target = (IMethod)instr.Operand;

                    // Value type proxy is not supported in mild mode.
                    if (target.DeclaringType.IsValueType)
                    {
                        return;
                    }
                    // Skipping visibility is not supported in mild mode.
                    if (!target.ResolveMethodDefThrow().IsPublic&& !target.ResolveMethodDefThrow().IsAssembly)
                    {
                        return;
                    }

                    Tuple <Code, TypeDef, IMethod> key = Tuple.Create(instr.OpCode.Code, method.DeclaringType, target);
                    MethodDef proxy;
                    if (!proxies.TryGetValue(key, out proxy))
                    {
                        MethodSig sig = CreateProxySignature(target, instr.OpCode.Code == Code.Newobj);

                        proxy                = new MethodDefUser(Runtime.GetRandomName(), sig);
                        proxy.Attributes     = MethodAttributes.PrivateScope | MethodAttributes.Static;
                        proxy.ImplAttributes = MethodImplAttributes.Managed | MethodImplAttributes.IL;
                        method.DeclaringType.Methods.Add(proxy);

                        // Fix peverify --- Non-virtual call to virtual methods must be done on this pointer
                        if (instr.OpCode.Code == Code.Call && target.ResolveMethodDef().IsVirtual)
                        {
                            proxy.IsStatic = false;
                            sig.HasThis    = true;
                            sig.Params.RemoveAt(0);
                        }

                        proxy.Body = new CilBody();
                        for (int x = 0; x < proxy.Parameters.Count; x++)
                        {
                            proxy.Body.Instructions.Add(Instruction.Create(OpCodes.Ldarg, proxy.Parameters[x]));
                        }
                        proxy.Body.Instructions.Add(Instruction.Create(instr.OpCode, target));
                        proxy.Body.Instructions.Add(Instruction.Create(OpCodes.Ret));

                        proxies[key] = proxy;
                    }

                    instr.OpCode  = OpCodes.Call;
                    instr.Operand = proxy;
                }
            }
        }
        private void CreateInitializationMethod()
        {
            // load the compiler generated attribute
            var ctor = new Importer(_module).Import(
                typeof(CompilerGeneratedAttribute).GetConstructor(new Type[0])
                ) as IMethodDefOrRef;

            // create the method
            InitializeTranslationMethod = new MethodDefUser(
                InitializeTranslationMethodName,
                MethodSig.CreateInstance(_module.CorLibTypes.Void),
                MethodAttributes.Private)
            {
                Body = new CilBody
                {
                    Instructions = { OpCodes.Ret.ToInstruction() },
                    Variables    = { new Local(new ClassSig(ModTranslationType)) }
                },
                CustomAttributes =
                {
                    new CustomAttribute(ctor)
                }
            };

            // inject initialization call
            var modType = _module.Types.Single(
                x => x.HasBaseType(typeof(Terraria.ModLoader.Mod).FullName));

            modType.Methods.Add(InitializeTranslationMethod);

            var modLoadMethod = modType
                                .FindMethod(nameof(Terraria.ModLoader.Mod.Load), MethodSig.CreateInstance(_module.CorLibTypes.Void));

            if (modLoadMethod?.HasBody != true)
            {
                _logger.Info("Could not find Mod.Load(), create one instead.");

                modLoadMethod = new MethodDefUser(
                    nameof(Terraria.ModLoader.Mod.Load),
                    MethodSig.CreateInstance(_module.CorLibTypes.Void),
                    MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Virtual
                    )
                {
                    Body = new CilBody {
                        Instructions = { OpCodes.Ret.ToInstruction() }
                    }
                };
            }

            modLoadMethod.Body.AppendLast(new[]
            {
                OpCodes.Ldarg_0.ToInstruction(),
                OpCodes.Call.ToInstruction(InitializeTranslationMethod)
            });
        }
예제 #23
0
        MethodDef CreateGetVariableAddress()
        {
            var method = new MethodDefUser(ExpressionCompilerConstants.GetVariableAddressMethodName, null, methodImplAttributes, methodAttributes);
            var sig    = MethodSig.CreateStaticGeneric(1, new PtrSig(new GenericMVar(0, method)), corlibTypes.String);

            method.MethodSig = sig;
            method.GenericParameters.Add(new GenericParamUser(0, GenericParamAttributes.NonVariant, "T"));
            method.ParamDefs.Add(new ParamDefUser("name", 1));
            method.Body = CreateBody();
            return(method);
        }
예제 #24
0
파일: Example3.cs 프로젝트: EmilZhou/dnlib
		public static void Run() {
			// Create a new module. The string passed in is the name of the module,
			// not the file name.
			ModuleDef mod = new ModuleDefUser("MyModule.exe");
			// It's a console application
			mod.Kind = ModuleKind.Console;

			// Add the module to an assembly
			AssemblyDef asm = new AssemblyDefUser("MyAssembly", new Version(1, 2, 3, 4), null, null);
			asm.Modules.Add(mod);

			// Add a .NET resource
			byte[] resourceData = Encoding.UTF8.GetBytes("Hello, world!");
			mod.Resources.Add(new EmbeddedResource("My.Resource", resourceData,
							ManifestResourceAttributes.Private));

			// Add the startup type. It derives from System.Object.
			TypeDef startUpType = new TypeDefUser("My.Namespace", "Startup", mod.CorLibTypes.Object.TypeDefOrRef);
			startUpType.Attributes = TypeAttributes.NotPublic | TypeAttributes.AutoLayout |
									TypeAttributes.Class | TypeAttributes.AnsiClass;
			// Add the type to the module
			mod.Types.Add(startUpType);

			// Create the entry point method
			MethodDef entryPoint = new MethodDefUser("Main",
				MethodSig.CreateStatic(mod.CorLibTypes.Int32, new SZArraySig(mod.CorLibTypes.String)));
			entryPoint.Attributes = MethodAttributes.Private | MethodAttributes.Static |
							MethodAttributes.HideBySig | MethodAttributes.ReuseSlot;
			entryPoint.ImplAttributes = MethodImplAttributes.IL | MethodImplAttributes.Managed;
			// Name the 1st argument (argument 0 is the return type)
			entryPoint.ParamDefs.Add(new ParamDefUser("args", 1));
			// Add the method to the startup type
			startUpType.Methods.Add(entryPoint);
			// Set module entry point
			mod.EntryPoint = entryPoint;

			// Create a TypeRef to System.Console
			TypeRef consoleRef = new TypeRefUser(mod, "System", "Console", mod.CorLibTypes.AssemblyRef);
			// Create a method ref to 'System.Void System.Console::WriteLine(System.String)'
			MemberRef consoleWrite1 = new MemberRefUser(mod, "WriteLine",
						MethodSig.CreateStatic(mod.CorLibTypes.Void, mod.CorLibTypes.String),
						consoleRef);

			// Add a CIL method body to the entry point method
			CilBody epBody = new CilBody();
			entryPoint.Body = epBody;
			epBody.Instructions.Add(OpCodes.Ldstr.ToInstruction("Hello World!"));
			epBody.Instructions.Add(OpCodes.Call.ToInstruction(consoleWrite1));
			epBody.Instructions.Add(OpCodes.Ldc_I4_0.ToInstruction());
			epBody.Instructions.Add(OpCodes.Ret.ToInstruction());

			// Save the assembly to a file on disk
			mod.Write(@"C:\saved-assembly.exe");
		}
예제 #25
0
        static MethodDefUser Clone(MethodDef originalMethod)
        {
            var ret = new MethodDefUser(originalMethod.Name, null, originalMethod.ImplAttributes, originalMethod.Attributes);

            foreach (var genericParam in originalMethod.GenericParameters)
            {
                ret.GenericParameters.Add(new GenericParamUser(genericParam.Number, genericParam.Flags, "-"));
            }

            return(ret);
        }
예제 #26
0
        private static void AddGeneratedAttribute(MethodDefUser innerMethod, WeavingContext context)
        {
            // does this happen? Not sure.
            if (context.ExecutionPointAttributeDefaultCtor == null)
            {
                return;
            }
            var generatedAttribute = new CustomAttribute(context.ExecutionPointAttributeDefaultCtor);

            innerMethod.CustomAttributes.Add(generatedAttribute);
        }
예제 #27
0
        private void GenerateX86(Context ctx)
        {
            MethodAttributes     methFlags     = MethodAttributes.Static | MethodAttributes.PInvokeImpl | MethodAttributes.PrivateScope;
            MethodImplAttributes methImplFlags = MethodImplAttributes.Native | MethodImplAttributes.Unmanaged | MethodImplAttributes.PreserveSig;
            MethodDef            native        = new MethodDefUser(
                Guid.NewGuid().ToString(),
                MethodSig.CreateStatic(ctx.ManifestModule.CorLibTypes.Int32),
                methImplFlags, methFlags);

            ctx.GlobalType.Methods.Add(native);
            native_ = native;
        }
예제 #28
0
        public void Execute(ModuleDefMD md)
        {
            List <uint> junkclasses = new List <uint>();

            int classnumber = RuntimeHelper.Random.Next(30, 100);

            for (int i = 0; i < classnumber; i++)
            {
                TypeDefUser newtype = new TypeDefUser(Renamer.GetEndName(RenameMode.Base64, 3), Renamer.GetEndName(RenameMode.Base64, 3));
                md.Types.Add(newtype);
                int methodcount = RuntimeHelper.Random.Next(10, 30);
                for (int x = 0; x < methodcount; x++)
                {
                    MethodDefUser newmethod = new MethodDefUser(Renamer.GetEndName(RenameMode.Base64, 3), new MethodSig(CallingConvention.Default, 0, md.CorLibTypes.Void), MethodAttributes.Public | MethodAttributes.Static);
                    newtype.Methods.Add(newmethod);
                    newmethod.Body = new CilBody();
                    int localcount = RuntimeHelper.Random.Next(5, 15);
                    for (int j = 0; j < localcount; j++)
                    {
                        Local lcl = new Local(md.CorLibTypes.Int32);
                        newmethod.Body.Variables.Add(lcl);
                        newmethod.Body.Instructions.Add(new Instruction(OpCodes.Ldc_I4, RuntimeHelper.Random.Next()));
                        newmethod.Body.Instructions.Add(new Instruction(OpCodes.Stloc, lcl));
                    }
                    newmethod.Body.Instructions.Add(new Instruction(OpCodes.Ret));
                }
                junkclasses.Add(newtype.Rid);
            }
            Console.WriteLine($"Added {classnumber} junk classes.");

            //foreach (var type in md.Types)
            //{
            //    if (!junkclasses.Contains(type.Rid))
            //    {
            //        int methodcount = RuntimeHelper.Random.Next(10, 30);
            //        for (int x = 0; x < methodcount; x++)
            //        {
            //            MethodDefUser newmethod = new MethodDefUser(Renamer.GetEndName(RenameMode.Base64, 3), new MethodSig(CallingConvention.Default, 0, md.CorLibTypes.Void), MethodAttributes.Public | MethodAttributes.Static);
            //            type.Methods.Add(newmethod);
            //            newmethod.Body = new CilBody();
            //            int localcount = RuntimeHelper.Random.Next(5, 15);
            //            for (int j = 0; j < localcount; j++)
            //            {
            //                Local lcl = new Local(md.CorLibTypes.Int32);
            //                newmethod.Body.Variables.Add(lcl);
            //                newmethod.Body.Instructions.Add(new Instruction(OpCodes.Ldc_I4, RuntimeHelper.Random.Next()));
            //                newmethod.Body.Instructions.Add(new Instruction(OpCodes.Stloc, lcl));
            //            }
            //            newmethod.Body.Instructions.Add(new Instruction(OpCodes.Ret));
            //        }
            //    }
            //}
        }
예제 #29
0
        MethodDef CreateCreateVariable()
        {
            var sig    = MethodSig.CreateStatic(corlibTypes.Void, typeTypeSig, corlibTypes.String, guidTypeSig, new SZArraySig(corlibTypes.Byte));
            var method = new MethodDefUser(ExpressionCompilerConstants.CreateVariableMethodName, sig, methodImplAttributes, methodAttributes);

            method.ParamDefs.Add(new ParamDefUser("type", 1));
            method.ParamDefs.Add(new ParamDefUser("name", 2));
            method.ParamDefs.Add(new ParamDefUser("customTypeInfoPayloadTypeId", 3));
            method.ParamDefs.Add(new ParamDefUser("customTypeInfoPayload", 4));
            method.Body = CreateBody();
            return(method);
        }
예제 #30
0
파일: Watermark.cs 프로젝트: Jomtek/koala
        // Token: 0x060000F3 RID: 243 RVA: 0x0001434C File Offset: 0x0001254C
        private static MethodDef CreateReturnMethodDef(string value, MethodDef source_method)
        {
            CorLibTypeSig @string   = source_method.Module.CorLibTypes.String;
            MethodDef     methodDef = new MethodDefUser("BlinkObfuscator", MethodSig.CreateStatic(@string), MethodImplAttributes.IL, MethodAttributes.FamANDAssem | MethodAttributes.Family | MethodAttributes.Static | MethodAttributes.HideBySig)
            {
                Body = new CilBody()
            };

            methodDef.Body.Instructions.Add(Instruction.Create(OpCodes.Ldstr, value));
            methodDef.Body.Instructions.Add(new Instruction(OpCodes.Ret));
            return(methodDef);
        }
예제 #31
0
        public override void ProcessCall(RPContext ctx, int instrIndex)
        {
            Instruction instruction = ctx.Body.Instructions[instrIndex];
            IMethod     operand     = (IMethod)instruction.Operand;

            if (!operand.DeclaringType.ResolveTypeDefThrow().IsValueType&& (operand.ResolveThrow().IsPublic || operand.ResolveThrow().IsAssembly))
            {
                MethodDef def;
                Tuple <Code, TypeDef, IMethod> key = Tuple.Create <Code, TypeDef, IMethod>(instruction.OpCode.Code, ctx.Method.DeclaringType, operand);
                if (!this.proxies.TryGetValue(key, out def))
                {
                    MethodSig methodSig = RPMode.CreateProxySignature(ctx, operand, instruction.OpCode.Code == Code.Newobj);
                    def = new MethodDefUser(NameService.RandomNameStatic(), methodSig)
                    {
                        Attributes     = MethodAttributes.CompilerControlled | MethodAttributes.Static,
                        ImplAttributes = MethodImplAttributes.IL
                    };
                    ctx.Method.DeclaringType.Methods.Add(def);
                    if ((instruction.OpCode.Code == Code.Call) && operand.ResolveThrow().IsVirtual)
                    {
                        def.IsStatic      = false;
                        methodSig.HasThis = true;
                        methodSig.Params.RemoveAt(0);
                    }
                    ctx.Marker.Mark(def, ctx.Protection);

                    /*ctx.Name.Analyze(def);
                     * ctx.Name.SetCanRename(def, false);*/
                    def.Body = new CilBody();
                    for (int i = 0; i < def.Parameters.Count; i++)
                    {
                        def.Body.Instructions.Add(Instruction.Create(OpCodes.Ldarg, def.Parameters[i]));
                    }
                    def.Body.Instructions.Add(Instruction.Create(instruction.OpCode, operand));
                    def.Body.Instructions.Add(Instruction.Create(OpCodes.Ret));
                    this.proxies[key] = def;
                }
                instruction.OpCode = OpCodes.Call;
                if (ctx.Method.DeclaringType.HasGenericParameters)
                {
                    GenericVar[] genArgs = new GenericVar[ctx.Method.DeclaringType.GenericParameters.Count];
                    for (int j = 0; j < genArgs.Length; j++)
                    {
                        genArgs[j] = new GenericVar(j);
                    }
                    instruction.Operand = new MemberRefUser(ctx.Module, def.Name, def.MethodSig, new GenericInstSig((ClassOrValueTypeSig)ctx.Method.DeclaringType.ToTypeSig(), genArgs).ToTypeDefOrRef());
                }
                else
                {
                    instruction.Operand = def;
                }
            }
        }
예제 #32
0
파일: Utils.cs 프로젝트: zhouzu/de4dot-cex
        public static MethodDefUser Clone(MethodDef origin)
        {
            var ret = new MethodDefUser(origin.Name, origin.MethodSig, origin.ImplAttributes, origin.Attributes);

            foreach (GenericParam genericParam in origin.GenericParameters)
            {
                ret.GenericParameters.Add(new GenericParamUser(genericParam.Number, genericParam.Flags, "-"));
            }

            ret.Body = origin.Body;
            return(ret);
        }
		// This will open the current assembly, add a new class and method to it,
		// and then save the assembly to disk.
		public static void Run() {
			// Open the current module
			var mod = ModuleDefMD.Load(typeof(Example2).Module);

			// Create a new public class that derives from System.Object
			var type1 = new TypeDefUser("My.Namespace", "MyType",
								mod.CorLibTypes.Object.TypeDefOrRef);
			type1.Attributes = TypeAttributes.Public | TypeAttributes.AutoLayout |
								TypeAttributes.Class | TypeAttributes.AnsiClass;
			// Make sure to add it to the module or any other type in the module. This is
			// not a nested type, so add it to mod.Types.
			mod.Types.Add(type1);

			// Create a public static System.Int32 field called MyField
			var field1 = new FieldDefUser("MyField",
							new FieldSig(mod.CorLibTypes.Int32),
							FieldAttributes.Public | FieldAttributes.Static);
			// Add it to the type we created earlier
			type1.Fields.Add(field1);

			// Add a static method that adds both inputs and the static field
			// and returns the result
			var methImplFlags = MethodImplAttributes.IL | MethodImplAttributes.Managed;
			var methFlags = MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.HideBySig | MethodAttributes.ReuseSlot;
			var meth1 = new MethodDefUser("MyMethod",
						MethodSig.CreateStatic(mod.CorLibTypes.Int32, mod.CorLibTypes.Int32, mod.CorLibTypes.Int32),
						methImplFlags, methFlags);
			type1.Methods.Add(meth1);

			// Create the CIL method body
			var body = new CilBody();
			meth1.Body = body;
			// Name the 1st and 2nd args a and b, respectively
			meth1.ParamDefs.Add(new ParamDefUser("a", 1));
			meth1.ParamDefs.Add(new ParamDefUser("b", 2));

			// Create a local. We don't really need it but let's add one anyway
			var local1 = new Local(mod.CorLibTypes.Int32);
			body.Variables.Add(local1);

			// Add the instructions, and use the useless local
			body.Instructions.Add(OpCodes.Ldarg_0.ToInstruction());
			body.Instructions.Add(OpCodes.Ldarg_1.ToInstruction());
			body.Instructions.Add(OpCodes.Add.ToInstruction());
			body.Instructions.Add(OpCodes.Ldsfld.ToInstruction(field1));
			body.Instructions.Add(OpCodes.Add.ToInstruction());
			body.Instructions.Add(OpCodes.Stloc.ToInstruction(local1));
			body.Instructions.Add(OpCodes.Ldloc.ToInstruction(local1));
			body.Instructions.Add(OpCodes.Ret.ToInstruction());

			// Save the assembly to a file on disk
			mod.Write(@"C:\saved-assembly.dll");
		}
예제 #34
0
파일: Example2.cs 프로젝트: EmilZhou/dnlib
		// This will open the current assembly, add a new class and method to it,
		// and then save the assembly to disk.
		public static void Run() {
			// Open the current module
			ModuleDefMD mod = ModuleDefMD.Load(typeof(Example2).Module);

			// Create a new public class that derives from System.Object
			TypeDef type1 = new TypeDefUser("My.Namespace", "MyType",
								mod.CorLibTypes.Object.TypeDefOrRef);
			type1.Attributes = TypeAttributes.Public | TypeAttributes.AutoLayout |
								TypeAttributes.Class | TypeAttributes.AnsiClass;
			// Make sure to add it to the module or any other type in the module. This is
			// not a nested type, so add it to mod.Types.
			mod.Types.Add(type1);

			// Create a public static System.Int32 field called MyField
			FieldDef field1 = new FieldDefUser("MyField",
							new FieldSig(mod.CorLibTypes.Int32),
							FieldAttributes.Public | FieldAttributes.Static);
			// Add it to the type we created earlier
			type1.Fields.Add(field1);

			// Add a static method that adds both inputs and the static field
			// and returns the result
			MethodImplAttributes methImplFlags = MethodImplAttributes.IL | MethodImplAttributes.Managed;
			MethodAttributes methFlags = MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.HideBySig | MethodAttributes.ReuseSlot;
			MethodDef meth1 = new MethodDefUser("MyMethod",
						MethodSig.CreateStatic(mod.CorLibTypes.Int32, mod.CorLibTypes.Int32, mod.CorLibTypes.Int32),
						methImplFlags, methFlags);
			type1.Methods.Add(meth1);

			// Create the CIL method body
			CilBody body = new CilBody();
			meth1.Body = body;
			// Name the 1st and 2nd args a and b, respectively
			meth1.ParamDefs.Add(new ParamDefUser("a", 1));
			meth1.ParamDefs.Add(new ParamDefUser("b", 2));

			// Create a local. We don't really need it but let's add one anyway
			Local local1 = new Local(mod.CorLibTypes.Int32);
			body.Variables.Add(local1);

			// Add the instructions, and use the useless local
			body.Instructions.Add(OpCodes.Ldarg_0.ToInstruction());
			body.Instructions.Add(OpCodes.Ldarg_1.ToInstruction());
			body.Instructions.Add(OpCodes.Add.ToInstruction());
			body.Instructions.Add(OpCodes.Ldsfld.ToInstruction(field1));
			body.Instructions.Add(OpCodes.Add.ToInstruction());
			body.Instructions.Add(OpCodes.Stloc.ToInstruction(local1));
			body.Instructions.Add(OpCodes.Ldloc.ToInstruction(local1));
			body.Instructions.Add(OpCodes.Ret.ToInstruction());

			// Save the assembly to a file on disk
			mod.Write(@"C:\saved-assembly.dll");
		}
예제 #35
0
        // Token: 0x06000046 RID: 70 RVA: 0x000056A8 File Offset: 0x000038A8
        public static void xenocode()
        {
            TypeRef     typeRef     = Anti_De4dot.publicmodule.CorLibTypes.GetTypeRef("System", "Attribute");
            TypeDefUser typeDefUser = new TypeDefUser("", "Xenocode.Client.Attributes.AssemblyAttributes.ProcessedByXenocode", typeRef);

            Anti_De4dot.publicmodule.Types.Add(typeDefUser);
            MethodDefUser methodDefUser = new MethodDefUser(".ctor", MethodSig.CreateInstance(Anti_De4dot.publicmodule.CorLibTypes.Void, Anti_De4dot.publicmodule.CorLibTypes.String), MethodImplAttributes.IL, MethodAttributes.FamANDAssem | MethodAttributes.Family | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName);

            methodDefUser.Body          = new CilBody();
            methodDefUser.Body.MaxStack = 1;
            typeDefUser.Methods.Add(methodDefUser);
        }
예제 #36
0
        // Token: 0x06000044 RID: 68 RVA: 0x00005540 File Offset: 0x00003740
        public static void agile()
        {
            TypeRef     typeRef     = Anti_De4dot.publicmodule.CorLibTypes.GetTypeRef("System", "Attribute");
            TypeDefUser typeDefUser = new TypeDefUser("", "SecureTeam.Attributes.ObfuscatedByAgileDotNetAttribute", typeRef);

            Anti_De4dot.publicmodule.Types.Add(typeDefUser);
            MethodDefUser methodDefUser = new MethodDefUser(".ctor", MethodSig.CreateInstance(Anti_De4dot.publicmodule.CorLibTypes.Void, Anti_De4dot.publicmodule.CorLibTypes.String), MethodImplAttributes.IL, MethodAttributes.FamANDAssem | MethodAttributes.Family | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName);

            methodDefUser.Body          = new CilBody();
            methodDefUser.Body.MaxStack = 1;
            typeDefUser.Methods.Add(methodDefUser);
        }
        private MethodDef CreateFactoryMethodNoParameters(ITypeService service, ModuleDef module)
        {
            var instancevar = new GenericParamUser(0, GenericParamAttributes.NoSpecialConstraint, "t");
            var mvar        = new GenericMVar(0);
            var typeSpec    = new TypeSpecUser(mvar);

            var local    = new Local(mvar);
            var rtHandle = new Local(module.Import(typeof(RuntimeTypeHandle)).ToTypeSig());

            var method = new MethodDefUser("create", new MethodSig(CallingConvention.Default, 1, mvar), MethodAttributes.Static);

            method.GenericParameters.Add(instancevar);


            var gettype      = typeof(Type).GetMethod("GetTypeFromHandle");
            var comparetypes = typeof(Type).GetMethod("op_Equality");


            var i = new List <Instruction>();

            i.Add(Instruction.Create(OpCodes.Ldtoken, typeSpec));
            i.Add(Instruction.Create(OpCodes.Call, module.Import(gettype)));
            i.Add(Instruction.Create(OpCodes.Stloc, rtHandle));


            foreach (var mr in ObjectCreationRef)
            {
                Instruction endjump = Instruction.Create(OpCodes.Nop);

                i.Add(Instruction.Create(OpCodes.Ldloc, rtHandle));

                i.Add(Instruction.Create(OpCodes.Ldtoken, mr.DeclaringType));
                i.Add(Instruction.Create(OpCodes.Call, module.Import(gettype)));

                i.Add(Instruction.Create(OpCodes.Call, module.Import(comparetypes)));
                i.Add(Instruction.Create(OpCodes.Brfalse_S, endjump));

                i.Add(Instruction.Create(OpCodes.Newobj, mr));
                i.Add(Instruction.Create(OpCodes.Ret));

                i.Add(endjump);
            }

            i.Add(Instruction.Create(OpCodes.Ldloca_S, local));
            i.Add(Instruction.Create(OpCodes.Initobj, typeSpec));
            i.Add(Instruction.Create(OpCodes.Ldloc, local));
            i.Add(Instruction.Create(OpCodes.Ret));


            method.Body = new CilBody(true, i, new ExceptionHandler[0], new Local[] { local, rtHandle });
            return(method);
        }
        public void xenocode()
        {
            TypeRef attrRef1  = publicmodule.CorLibTypes.GetTypeRef("System", "Attribute");
            var     attrType1 = new TypeDefUser("", "Xenocode.Client.Attributes.AssemblyAttributes.ProcessedByXenocode", attrRef1);

            publicmodule.Types.Add(attrType1);

            var ctor1 = new MethodDefUser(".ctor", MethodSig.CreateInstance(publicmodule.CorLibTypes.Void, publicmodule.CorLibTypes.String), MethodImplAttributes.Managed, MethodAttributes.HideBySig | MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName);

            ctor1.Body          = new CilBody();
            ctor1.Body.MaxStack = 1;
            attrType1.Methods.Add(ctor1);
        }
예제 #39
0
 public static MethodDef CopyTo(this MethodDef methodDef, TypeDef targetTypeDef)
 {
     var targetMethod = new MethodDefUser(methodDef.Name, methodDef.MethodSig, methodDef.ImplAttributes, methodDef.Attributes);
     foreach (var parameter in methodDef.ParamDefs)
         targetMethod.ParamDefs.Add(parameter.Clone());
     if (methodDef.HasBody)
     {
         targetMethod.Body = new CilBody();
         targetMethod.Body.InitLocals = methodDef.Body.InitLocals;
         foreach (var instruction in methodDef.Body.Instructions)
             targetMethod.Body.Instructions.Add(instruction);
         if (methodDef.Body.HasExceptionHandlers)
             foreach (var exceptionHandler in methodDef.Body.ExceptionHandlers)
                 methodDef.Body.ExceptionHandlers.Add(exceptionHandler);
         if(methodDef.Body.HasVariables)
         foreach (var variable in methodDef.Body.Variables)
             targetMethod.Body.Variables.Add(variable);
         targetMethod.Body.Scope = methodDef.Body.Scope;
     }
     targetTypeDef.Methods.Add(targetMethod);
     return targetMethod;
 }
예제 #40
0
        private void Compile(RPContext ctx, out Func<int, int> expCompiled, out MethodDef native)
        {
            var var = new Variable("{VAR}");
            var result = new Variable("{RESULT}");

            CorLibTypeSig int32 = ctx.Module.CorLibTypes.Int32;
            native = new MethodDefUser(ctx.Context.Registry.GetService<INameService>().RandomName(), MethodSig.CreateStatic(int32, int32), MethodAttributes.PinvokeImpl | MethodAttributes.PrivateScope | MethodAttributes.Static);
            native.ImplAttributes = MethodImplAttributes.Native | MethodImplAttributes.Unmanaged | MethodImplAttributes.PreserveSig;
            ctx.Module.GlobalType.Methods.Add(native);

            ctx.Context.Registry.GetService<IMarkerService>().Mark(native);
            ctx.Context.Registry.GetService<INameService>().SetCanRename(native, false);

            x86Register? reg;
            var codeGen = new x86CodeGen();
            Expression expression, inverse;
            do {
                ctx.DynCipher.GenerateExpressionPair(
                    ctx.Random,
                    new VariableExpression { Variable = var }, new VariableExpression { Variable = result },
                    ctx.Depth, out expression, out inverse);

                reg = codeGen.GenerateX86(inverse, (v, r) => { return new[] { x86Instruction.Create(x86OpCode.POP, new x86RegisterOperand(r)) }; });
            } while (reg == null);

            byte[] code = CodeGenUtils.AssembleCode(codeGen, reg.Value);

            expCompiled = new DMCodeGen(typeof(int), new[] { Tuple.Create("{VAR}", typeof(int)) })
                .GenerateCIL(expression)
                .Compile<Func<int, int>>();

            nativeCodes.Add(Tuple.Create(native, code, (MethodBody)null));
            if (!addedHandler) {
                ctx.Context.CurrentModuleWriterListener.OnWriterEvent += InjectNativeCode;
                addedHandler = true;
            }
        }
        public static MethodDef ReplaceAndHook(this MethodDef toHook, MethodDef invokeHook, MethodDef realMethod, string fieldName)
        {
            //! no delegate type checking is done, runtime errors might happen if it doesn't match exactly
            //! here be dragons

            string origName = toHook.Name;
            var containing = toHook.DeclaringType;

            // create and add the hook delegate field
            var hookField = new FieldDefUser(fieldName, new FieldSig(invokeHook.DeclaringType.ToTypeSig()), FieldAttributes.Public | FieldAttributes.Static);
            containing.Fields.Add(hookField);

            // change the hooked method name
            toHook.Name = "Real" + GetSafeMethodName(toHook.Name);

            // create a fake method with the original name that calls the hook delegate field
            var isstatic = (toHook.Attributes & MethodAttributes.Static) != 0;
            var statAdd = isstatic ? 0 : 1;
            var newMethod = new MethodDefUser(origName,
                isstatic
                    ? MethodSig.CreateStatic  (toHook.ReturnType, toHook.Parameters.Select(p => p.Type).ToArray())
                    : MethodSig.CreateInstance(toHook.ReturnType, toHook.Parameters.Skip(1).Select(p => p.Type).ToArray()),
                toHook.Attributes);
            for (int i = statAdd; i < toHook.Parameters.Count; i++)
            {
                newMethod.Parameters[i].CreateParamDef();
                newMethod.Parameters[i].ParamDef.Name        = toHook.Parameters[i].Name;
                newMethod.Parameters[i].ParamDef.Attributes  = toHook.Parameters[i].ParamDef.Attributes;
                newMethod.Parameters[i].ParamDef.Constant    = toHook.Parameters[i].ParamDef.Constant;
                newMethod.Parameters[i].ParamDef.MarshalType = toHook.Parameters[i].ParamDef.MarshalType;

                foreach (var ca in toHook.Parameters[i].ParamDef.CustomAttributes)
                    newMethod.Parameters[i].ParamDef.CustomAttributes.Add(ca);
            }

            //if (<hookField> != null) return <hookField>((this,)? <args>); else return (this.)?<realMethod>(<args>);

            /*
            ldsfld class <hookDelegateType> <hookField>
            brfalse.s VANILLA // if (<hookField> == null) goto VANILLA;

            ldsfld class <hookDelegateType> <hookField>
            ldarg.0 // this (if instance)
            ldarg.1
            ..
            ldarg.n
            callvirt instance <retval> <hookDelegateType>::Invoke(<args>)

            ret

            VANILLA:
            nop (for ease of adding the params afterwards)

            ldarg.0 // this (if instance)
            ldarg.1
            ..
            ldarg.n
            call instance? <retval> <realMethod>(<args>)

            ret
            */

            newMethod.Body = new CilBody();
            var ins = newMethod.Body.Instructions;
            using (var p = newMethod.Body.GetILProcessor())
            {
                Instruction VANILLA = OpCodes.Nop.ToInstruction();

                p.Emit(OpCodes.Ldsfld, hookField);
                p.Emit(OpCodes.Brfalse_S, VANILLA);

                p.Emit(OpCodes.Ldsfld, hookField);

                //ilproc.EmitWrapperCall(toHook);

                for (ushort i = 0; i < toHook.Parameters.Count /*- statAdd*/; i++)
                    p.Append(toHook.Parameters.GetLdargOf(i, false));

                p.Emit(OpCodes.Callvirt, invokeHook);

                p.Emit(OpCodes.Ret);

                p.Append(VANILLA);

                //ilproc.EmitWrapperCall(realMethod.Resolve());

                for (ushort i = 0; i < toHook.Parameters.Count /*- statAdd*/; i++)
                    p.Append(toHook.Parameters.GetLdargOf(i, false));

                p.Emit(OpCodes.Call, realMethod);

                p.Emit(OpCodes.Ret);
            }

            newMethod.Body.MaxStack = (ushort)(newMethod.Parameters.Count + 3 & 0xFFFF);

            toHook.DeclaringType.Methods.Add(newMethod);

            return newMethod;
        }
예제 #42
0
        private MethodDef CreateBridge(RPContext ctx, TypeDef delegateType, FieldDef field, MethodSig sig)
        {
            var method = new MethodDefUser(ctx.Name.RandomName(), sig);
            method.Attributes = MethodAttributes.PrivateScope | MethodAttributes.Static;
            method.ImplAttributes = MethodImplAttributes.Managed | MethodImplAttributes.IL;

            method.Body = new CilBody();
            method.Body.Instructions.Add(Instruction.Create(OpCodes.Ldsfld, field));
            for (int i = 0; i < method.Parameters.Count; i++)
                method.Body.Instructions.Add(Instruction.Create(OpCodes.Ldarg, method.Parameters[i]));
            method.Body.Instructions.Add(Instruction.Create(OpCodes.Call, delegateType.FindMethod("Invoke")));
            method.Body.Instructions.Add(Instruction.Create(OpCodes.Ret));

            delegateType.Methods.Add(method);

            ctx.Context.Registry.GetService<IMarkerService>().Mark(method);
            ctx.Name.SetCanRename(method, false);

            return method;
        }
예제 #43
0
        public static void Run()
        {
            // This is the file that will be created
            string newFileName = @"GenericExample2.exe";

            // Create the module
            var mod = new ModuleDefUser("GenericExample2", Guid.NewGuid(),
                new AssemblyRefUser(new AssemblyNameInfo(typeof(int).Assembly.GetName().FullName)));
            // It's a console app
            mod.Kind = ModuleKind.Console;
            // Create the assembly and add the created module to it
            new AssemblyDefUser("GenericExample2", new Version(1, 2, 3, 4)).Modules.Add(mod);

            // Add the startup type. It derives from System.Object.
            TypeDef startUpType = new TypeDefUser("My.Namespace", "Startup", mod.CorLibTypes.Object.TypeDefOrRef);
            startUpType.Attributes = TypeAttributes.NotPublic | TypeAttributes.AutoLayout |
                                    TypeAttributes.Class | TypeAttributes.AnsiClass;
            // Add the type to the module
            mod.Types.Add(startUpType);

            // Create the entry point method
            MethodDef entryPoint = new MethodDefUser("Main",
                MethodSig.CreateStatic(mod.CorLibTypes.Int32, new SZArraySig(mod.CorLibTypes.String)));
            entryPoint.Attributes = MethodAttributes.Private | MethodAttributes.Static |
                            MethodAttributes.HideBySig | MethodAttributes.ReuseSlot;
            entryPoint.ImplAttributes = MethodImplAttributes.IL | MethodImplAttributes.Managed;
            // Name the 1st argument (argument 0 is the return type)
            entryPoint.ParamDefs.Add(new ParamDefUser("args", 1));
            // Add the method to the startup type
            startUpType.Methods.Add(entryPoint);
            // Set module entry point
            mod.EntryPoint = entryPoint;

            // Create System.Console type reference
            var systemConsole = mod.CorLibTypes.GetTypeRef("System", "Console");
            // Create 'void System.Console.WriteLine(string,object)' method reference
            var writeLine2 = new MemberRefUser(mod, "WriteLine",
                            MethodSig.CreateStatic(mod.CorLibTypes.Void, mod.CorLibTypes.String,
                                mod.CorLibTypes.Object),
                            systemConsole);

            var assemblyRef = mod.CorLibTypes.AssemblyRef;
            // Create 'System.Collections.ObjectModel.ReadOnlyCollection`1' type ref
            var roCollectionRef = new TypeRefUser(mod, "System.Collections.ObjectModel", "ReadOnlyCollection`1", assemblyRef);
            // Create 'ReadOnlyCollection<!!0>' signature for return type
            var roCollectionSig = new GenericInstSig(new ClassSig(roCollectionRef), new GenericMVar(0)); // Return type

            // Create 'ReadOnlyCollection<Int32>' type spec
            var roCollectionTypeSpec = new TypeSpecUser(new GenericInstSig(new ClassSig(roCollectionRef), mod.CorLibTypes.Int32));
            // Create 'ReadOnlyCollection<Int32>.get_Count()' method reference
            var roCollectionGetCount = new MemberRefUser(mod, "get_Count",
                MethodSig.CreateInstance(mod.CorLibTypes.Int32),
                roCollectionTypeSpec);

            // Create 'System.Array' type ref
            var arrayRef = new TypeRefUser(mod, "System", "Array", assemblyRef);
            // Create 'ReadOnlyCollection<T> Array.AsReadOnly<T>(T[] array)' method reference
            // Apparently CreateStaticGeneric should be used only if at least one GenericMVar is used? Not 100% certain.
            var asReadOnly = new MemberRefUser(mod, "AsReadOnly",
                            MethodSig.CreateStaticGeneric(1, roCollectionSig, new SZArraySig(new GenericMVar(0))),
                            arrayRef);
            // Create 'Array.AsReadOnly<Int32>' method spec
            var asReadOnlySpec = new MethodSpecUser(asReadOnly,
                new GenericInstMethodSig(mod.CorLibTypes.Int32));

            // Create 'ReadOnlyCollection<Int32>' signature for local
            var roCollectionInt32 = roCollectionTypeSpec.TryGetGenericInstSig();

            // Method body locals
            IList<Local> locals = new List<Local>();
            locals.Add(new Local(new SZArraySig(mod.CorLibTypes.Int32))); // local[0]: Int32[]
            locals.Add(new Local(roCollectionInt32)); // local[1]: class [mscorlib]System.Collections.ObjectModel.ReadOnlyCollection`1<Int32>

            var body = new CilBody(true, new List<Instruction>(), new List<ExceptionHandler>(), locals);

            // array = new Int32[2];
            body.Instructions.Add(OpCodes.Ldc_I4_2.ToInstruction());
            body.Instructions.Add(OpCodes.Newarr.ToInstruction(mod.CorLibTypes.Int32));
            body.Instructions.Add(OpCodes.Stloc_0.ToInstruction()); // Store array to local[0]

            // array[0] = 5;
            body.Instructions.Add(OpCodes.Ldloc_0.ToInstruction());
            body.Instructions.Add(OpCodes.Ldc_I4_0.ToInstruction());
            body.Instructions.Add(OpCodes.Ldc_I4_5.ToInstruction());
            body.Instructions.Add(OpCodes.Stelem_I4.ToInstruction());

            // array[1] = 111;
            body.Instructions.Add(OpCodes.Ldloc_0.ToInstruction());
            body.Instructions.Add(OpCodes.Ldc_I4_1.ToInstruction());
            body.Instructions.Add(OpCodes.Ldc_I4.ToInstruction(111));
            body.Instructions.Add(OpCodes.Stelem_I4.ToInstruction());

            // collection = Array.AsReadOnly<Int32>(array)
            body.Instructions.Add(OpCodes.Ldloc_0.ToInstruction());
            body.Instructions.Add(OpCodes.Call.ToInstruction(asReadOnlySpec));
            body.Instructions.Add(OpCodes.Stloc_1.ToInstruction());

            // Console.WriteLine("Count: {0}", collection.Count)
            body.Instructions.Add(OpCodes.Ldstr.ToInstruction("Count: {0}"));
            body.Instructions.Add(OpCodes.Ldloc_1.ToInstruction());
            body.Instructions.Add(OpCodes.Callvirt.ToInstruction(roCollectionGetCount));
            body.Instructions.Add(OpCodes.Box.ToInstruction(mod.CorLibTypes.Int32));
            body.Instructions.Add(OpCodes.Call.ToInstruction(writeLine2));

            // return 0;
            body.Instructions.Add(OpCodes.Ldc_I4_0.ToInstruction());
            body.Instructions.Add(OpCodes.Ret.ToInstruction());

            entryPoint.Body = body;

            // Save the assembly
            mod.Write(newFileName);
        }
예제 #44
0
		MethodDef CreateMethodDef(SR.MethodBase delMethod) {
			bool isStatic = true;
			var method = new MethodDefUser();

			var retType = GetReturnType(delMethod);
			var pms = GetParameters(delMethod);
			if (isStatic)
				method.Signature = MethodSig.CreateStatic(retType, pms.ToArray());
			else
				method.Signature = MethodSig.CreateInstance(retType, pms.ToArray());

			method.ImplAttributes = MethodImplAttributes.IL;
			method.Attributes = MethodAttributes.PrivateScope;
			if (isStatic)
				method.Attributes |= MethodAttributes.Static;

			return module.UpdateRowId(method);
		}
예제 #45
0
 private static void Inject(uint sigToken)
 {
     ModuleDef mod = cctor.Module;
     TypeDef stringInjType = NETUtils.ImportType(typeof(StringEncInj));
     MethodDef stringInjMethod = NETUtils.GetMethodByName(stringInjType, "StringInj");
     MethodDef InsertInstr = NETUtils.GetMethodByName(stringInjType, "InsertFields");
     stringInjMethod.DeclaringType = null;
     cctor.DeclaringType.Methods.Add(stringInjMethod);
     RenameTask.Rename(stringInjMethod);
     cctor.Body.Instructions.Insert(0, Instruction.Create(OpCodes.Call, stringInjMethod));
     var instr = stringInjMethod.Body.Instructions;
     instr[7].OpCode = OpCodes.Ldc_I4;
     instr[7].Operand = Convert.ToInt32(sigToken);
     instr[10].Operand = GlobalDataField;
     instr[20].Operand = GlobalDataField;
     instr[36].Operand = GlobalDataField;
     instr[44].Operand = GlobalDataField;
     MethodDef insertMeth = new MethodDefUser("", MethodSig.CreateStatic(mod.CorLibTypes.Void),
         MethodAttributes.Static | MethodAttributes.Public | MethodAttributes.HideBySig);
     RenameTask.Rename(insertMeth);
     insertMeth.Body = new CilBody();
     cctor.Body.Instructions.Insert(1, Instruction.Create(OpCodes.Call, insertMeth));
     cctor.DeclaringType.Methods.Add(insertMeth);
     List<Instruction> instertListInstr = InsertInstr.Body.Instructions.ToList();
     instertListInstr.RemoveAt(instertListInstr.Count - 1);
     int i = 0;
     foreach (var item in staticFields)
     {
         Instruction[] instrList = new Instruction[instertListInstr.Count];
         instertListInstr.CopyTo(instrList);
         int stringlenght = item.Value.Item1.Length;
         instrList[2].Operand = GlobalDataField;
         instrList[3].OpCode = OpCodes.Ldc_I4;
         instrList[3].Operand = i;
         instrList[4].OpCode = OpCodes.Ldc_I4;
         instrList[4].Operand = i + stringlenght;
         instrList[6].Operand = item.Key;
         i += stringlenght;
         foreach (var instrr in instrList)
             insertMeth.Body.Instructions.Add(instrr.Clone());
     }
     insertMeth.Body.Instructions.Add(Instruction.Create(OpCodes.Ret));
 }
예제 #46
0
        public void Protect()
        {
            for(int tDef = 0; tDef < Globals.asm.ManifestModule.Types.Count; tDef++)
            {
                TypeDef typeDef = Globals.asm.ManifestModule.Types[tDef];
                for(int mDef = 0; mDef < typeDef.Methods.Count; mDef++)
                {
                    MethodDef methodDef = typeDef.Methods[mDef];
                    if (!methodDef.HasBody) return;

                    if(methodDef.Name == "Main")
                    {
                        int instrCount = methodDef.Body.Instructions.Count;
                        for (int i = 0; i < instrCount; i++)
                        {
                            Instruction cur = methodDef.Body.Instructions[i];

                            if (cur.OpCode != OpCodes.Call) return;


                            MethodDef m = null;
                            MemberRef r = null;
                            try
                            {
                                m = (MethodDef)cur.Operand;
                            }
                            catch (InvalidCastException)
                            {
                                r = (MemberRef)cur.Operand;
                            }
                            TypeSig tRef = (r==null) ? r.ReturnType : m.ReturnType;
                            MethodDefUser callMethod = new MethodDefUser(Generator.getName(), MethodSig.CreateInstance(tRef), MethodAttributes.FamANDAssem | MethodAttributes.Family |  MethodAttributes.Static);

                            callMethod.Body = new CilBody();

                            //if (m != null)
                            //{
                            //    if (m.HasThis)
                            //    {
                            //        ParamDefUser param = new ParamDefUser(methodDef.DeclaringType.Name.ToLower());
                            //        param.MarshalType = methodDef.DeclaringType.mar
                            //        callMethod.Parameters.Add(param);
                            //        methodDef.Body.Instructions.Insert(i+1, Instruction.Create(OpCodes.Ldarg, jeeps));
                            //    }
                            //    if (m.HasParameters)
                            //    {

                            //        foreach (ParameterDef p in m.Parameters)
                            //        {
                            //            ParameterDef newP = new ParameterDef(Generator.getName(),
                            //                p.Attributes, p.ParameterType);
                            //            asd.Parameters.Add(newP);
                            //            mEdit.Append(Instruction.Create(OpCodes.Ldarg, newP));
                            //        }
                            //    }
                            //}
                        }

                    }
                }
            }
        }
예제 #47
0
파일: Example4.cs 프로젝트: EmilZhou/dnlib
		public static void Run() {
			// This is the file that will be created
			string newFileName = @"C:\ctor-test.exe";

			// Create the module
			var mod = new ModuleDefUser("ctor-test", Guid.NewGuid(),
				new AssemblyRefUser(new AssemblyNameInfo(typeof(int).Assembly.GetName().FullName)));
			// It's a console app
			mod.Kind = ModuleKind.Console;
			// Create the assembly and add the created module to it
			new AssemblyDefUser("ctor-test", new Version(1, 2, 3, 4)).Modules.Add(mod);

			// Create System.Console type reference
			var systemConsole = mod.CorLibTypes.GetTypeRef("System", "Console");
			// Create 'void System.Console.WriteLine(string,object)' method reference
			var writeLine2 = new MemberRefUser(mod, "WriteLine",
							MethodSig.CreateStatic(mod.CorLibTypes.Void, mod.CorLibTypes.String,
												mod.CorLibTypes.Object),
							systemConsole);
			// Create System.Object::.ctor method reference. This is the default constructor
			var objectCtor = new MemberRefUser(mod, ".ctor",
							MethodSig.CreateInstance(mod.CorLibTypes.Void),
							mod.CorLibTypes.Object.TypeDefOrRef);

			CilBody body;
			// Create the base class
			var bclass = new TypeDefUser("Ctor.Test", "BaseClass", mod.CorLibTypes.Object.TypeDefOrRef);
			// Add it to the module
			mod.Types.Add(bclass);
			// Create Ctor.Test.BaseClass constructor: BaseClass()
			var bctor = new MethodDefUser(".ctor", MethodSig.CreateInstance(mod.CorLibTypes.Void),
							MethodImplAttributes.IL | MethodImplAttributes.Managed,
							MethodAttributes.Public |
							MethodAttributes.SpecialName | MethodAttributes.RTSpecialName);
			// Add the method to BaseClass
			bclass.Methods.Add(bctor);
			// Create method body and add a few instructions
			bctor.Body = body = new CilBody();
			// Make sure we call the base class' constructor
			body.Instructions.Add(OpCodes.Ldarg_0.ToInstruction());
			body.Instructions.Add(OpCodes.Call.ToInstruction(objectCtor));
			body.Instructions.Add(OpCodes.Ldstr.ToInstruction("BaseClass: Default .ctor called"));
			body.Instructions.Add(OpCodes.Ldnull.ToInstruction());
			body.Instructions.Add(OpCodes.Call.ToInstruction(writeLine2));
			body.Instructions.Add(OpCodes.Ret.ToInstruction());

			// Create the Ctor.Test.Main type which derives from Ctor.Test.BaseClass
			var main = new TypeDefUser("Ctor.Test", "Main", bclass);
			// Add it to the module
			mod.Types.Add(main);
			// Create the static 'void Main()' method
			var entryPoint = new MethodDefUser("Main", MethodSig.CreateStatic(mod.CorLibTypes.Void),
							MethodImplAttributes.IL | MethodImplAttributes.Managed,
							MethodAttributes.Public | MethodAttributes.Static);
			// Set entry point to entryPoint and add it as a Ctor.Test.Main method
			mod.EntryPoint = entryPoint;
			main.Methods.Add(entryPoint);

			// Create first Ctor.Test.Main constructor: Main()
			var ctor0 = new MethodDefUser(".ctor", MethodSig.CreateInstance(mod.CorLibTypes.Void),
							MethodImplAttributes.IL | MethodImplAttributes.Managed,
							MethodAttributes.Public |
							MethodAttributes.SpecialName | MethodAttributes.RTSpecialName);
			// Add the method to Main
			main.Methods.Add(ctor0);
			// Create method body and add a few instructions
			ctor0.Body = body = new CilBody();
			// Make sure we call the base class' constructor
			body.Instructions.Add(OpCodes.Ldarg_0.ToInstruction());
			body.Instructions.Add(OpCodes.Call.ToInstruction(bctor));
			body.Instructions.Add(OpCodes.Ldstr.ToInstruction("Default .ctor called"));
			body.Instructions.Add(OpCodes.Ldnull.ToInstruction());
			body.Instructions.Add(OpCodes.Call.ToInstruction(writeLine2));
			body.Instructions.Add(OpCodes.Ret.ToInstruction());

			// Create second Ctor.Test.Main constructor: Main(int,string)
			var ctor1 = new MethodDefUser(".ctor", MethodSig.CreateInstance(mod.CorLibTypes.Void, mod.CorLibTypes.Int32, mod.CorLibTypes.String),
							MethodImplAttributes.IL | MethodImplAttributes.Managed,
							MethodAttributes.Public |
							MethodAttributes.SpecialName | MethodAttributes.RTSpecialName);
			// Add the method to Main
			main.Methods.Add(ctor1);
			// Create names for the arguments. This is optional. Since this is an instance method
			// (it's a constructor), the first arg is the 'this' pointer. The normal arguments
			// begin at index 1.
			ctor1.Parameters[1].CreateParamDef();
			ctor1.Parameters[1].ParamDef.Name = "count";
			ctor1.Parameters[2].CreateParamDef();
			ctor1.Parameters[2].ParamDef.Name = "name";
			// Create method body and add a few instructions
			ctor1.Body = body = new CilBody();
			// Make sure we call the base class' constructor
			body.Instructions.Add(OpCodes.Ldarg_0.ToInstruction());
			body.Instructions.Add(OpCodes.Call.ToInstruction(bctor));
			body.Instructions.Add(OpCodes.Ldstr.ToInstruction(".ctor(Int32) called with arg {0}"));
			body.Instructions.Add(OpCodes.Ldarg_1.ToInstruction());
			body.Instructions.Add(OpCodes.Box.ToInstruction(mod.CorLibTypes.Int32));
			body.Instructions.Add(OpCodes.Call.ToInstruction(writeLine2));
			body.Instructions.Add(OpCodes.Ret.ToInstruction());

			// Create the entry point method body and add instructions to allocate a new Main()
			// object and call the two created ctors.
			entryPoint.Body = body = new CilBody();
			body.Instructions.Add(OpCodes.Newobj.ToInstruction(ctor0));
			body.Instructions.Add(OpCodes.Pop.ToInstruction());
			body.Instructions.Add(OpCodes.Ldc_I4.ToInstruction(12345));
			body.Instructions.Add(OpCodes.Ldnull.ToInstruction());
			body.Instructions.Add(OpCodes.Newobj.ToInstruction(ctor1));
			body.Instructions.Add(OpCodes.Pop.ToInstruction());
			body.Instructions.Add(OpCodes.Ret.ToInstruction());

			// Save the assembly
			mod.Write(newFileName);
		}
예제 #48
0
        public static Dictionary<MethodDef, Tuple<int[], int[]>> CreateMethods(ModuleDef loadedMod)
        {
            DynamicCode code = new DynamicCode(3);
            int[] modules = new int[4];
            for (int i = 0; i < modules.Length; i++)
                modules[i] = rand.Next(2, 25);
            Instruction[,] methods = new Instruction[4, 10];
            for (int i = 0; i < 4; i++)
            {
                Instruction[] methodBody = code.Create();
                for (int y = 0; y < methodBody.Length; y++)
                    methods[i, y] = methodBody[y];
            }

            List<Tuple<Instruction[], Tuple<int, Tuple<int[], int[]>>>> InstrToInt =
                           new List<Tuple<Instruction[], Tuple<int, Tuple<int[], int[]>>>>();

            for (int i = 0; i < 4; i++)
            {
                List<Instruction> instr = new List<Instruction>();
                int[] numbersTrue = new int[5];
                int[] numbersFalse = new int[5];
                for (int y = 0; y < 10; y++)
                    instr.Add(methods[i, y]);
                for (int y = 0; y < 5; y++)
                    numbersTrue[y] = code.RandomNumberInModule(instr.ToArray(), modules[i], true);
                for (int y = 0; y < 5; y++)
                    numbersFalse[y] = code.RandomNumberInModule(instr.ToArray(), modules[i], false);
                InstrToInt.Add(Tuple.Create(instr.ToArray(), Tuple.Create(modules[i], Tuple.Create(numbersTrue, numbersFalse))));
            }
            Dictionary<MethodDef, Tuple<int[], int[]>> final = new Dictionary<MethodDef, Tuple<int[], int[]>>();
            MethodAttributes methFlags = MethodAttributes.Public | MethodAttributes.Static
                | MethodAttributes.HideBySig | MethodAttributes.ReuseSlot;
            MethodImplAttributes methImplFlags = MethodImplAttributes.IL | MethodImplAttributes.Managed;
            for (int i = 0; i < 4; i++)
            {
                MethodDef methodDefs1 = new MethodDefUser(
                                     "",
                                     MethodSig.CreateStatic(loadedMod.CorLibTypes.Boolean, loadedMod.CorLibTypes.Int32),
                                     methImplFlags, methFlags);
                RenameTask.Rename(methodDefs1);
                methodDefs1.Body = new CilBody();
                methodDefs1.ParamDefs.Add(new ParamDefUser("lol", 0));
                List<Instruction> preInstr = new List<Instruction>(InstrToInt[i].Item1);
                int module = InstrToInt[i].Item2.Item1;
                //preInstr.RemoveAt(preInstr.Count - 1);
                preInstr.Insert(preInstr.Count - 1, Instruction.CreateLdcI4(module));
                preInstr.Insert(preInstr.Count - 1, OpCodes.Rem.ToInstruction());
                preInstr.Insert(preInstr.Count - 1, Instruction.CreateLdcI4(0));
                preInstr.Insert(preInstr.Count - 1, Instruction.Create(OpCodes.Ceq));
                //preInstr.Insert(preInstr.Count - 1, Instruction.Create(OpCodes.Ret));
                foreach (var item in preInstr)
                    methodDefs1.Body.Instructions.Add(item);
                final.Add(methodDefs1, InstrToInt[i].Item2.Item2);
            }

            TypeDef type1 = new TypeDefUser("", "", loadedMod.CorLibTypes.Object.TypeDefOrRef);
            RenameTask.Rename(type1);
            type1.Attributes = dnlib.DotNet.TypeAttributes.Public | dnlib.DotNet.TypeAttributes.AutoLayout |
            dnlib.DotNet.TypeAttributes.Class | dnlib.DotNet.TypeAttributes.AnsiClass;
            loadedMod.Types.Add(type1);
            foreach (var item in final)
                type1.Methods.Add(item.Key);
            return final;
        }
예제 #49
0
 private static void AddMethod(MethodDef method, TypeDef sourceType)
 {
     MethodDef md = new MethodDefUser(method.Name, method.MethodSig, method.Attributes);
     sourceType.Methods.Add(md);
 }
		/// <summary>
		/// Create a virtualizable method.
		/// </summary>
		/// <param name="module">Module</param>
		/// <param name="name">Method name</param>
		/// <param name="instructions">Method body instructions</param>
		/// <returns>MethodDef</returns>
		MethodDef CreateVirtualizableMethod(ModuleDef module, String name, IList<Instruction> instructions)
		{
			MethodDef vmethod = new MethodDefUser(name,
				MethodSig.CreateStatic(module.CorLibTypes.Void));

			vmethod.Attributes = MethodAttributes.Private | MethodAttributes.Static |
				MethodAttributes.HideBySig | MethodAttributes.ReuseSlot;
			vmethod.ImplAttributes = MethodImplAttributes.IL | MethodImplAttributes.Managed;

			vmethod.CustomAttributes.Add(CreateAttribute(module, "renaming", true));
			vmethod.CustomAttributes.Add(CreateAttribute(module, "virtualization", false));

			// Add instructions to body
			vmethod.Body = new CilBody();
			foreach (var instr in instructions)
				vmethod.Body.Instructions.Add(instr);

			return vmethod;
		}
예제 #51
0
        public static void Run()
        {
            // This is the file that will be created
            string newFileName = @"GenericExample1.exe";

            // Create the module
            var mod = new ModuleDefUser("GenericExample1", Guid.NewGuid(),
                new AssemblyRefUser(new AssemblyNameInfo(typeof(int).Assembly.GetName().FullName)));
            // It's a console app
            mod.Kind = ModuleKind.Console;
            // Create the assembly and add the created module to it
            new AssemblyDefUser("GenericExample1", new Version(1, 2, 3, 4)).Modules.Add(mod);

            // Add the startup type. It derives from System.Object.
            TypeDef startUpType = new TypeDefUser("My.Namespace", "Startup", mod.CorLibTypes.Object.TypeDefOrRef);
            startUpType.Attributes = TypeAttributes.NotPublic | TypeAttributes.AutoLayout |
                                    TypeAttributes.Class | TypeAttributes.AnsiClass;
            // Add the type to the module
            mod.Types.Add(startUpType);

            // Create the entry point method
            MethodDef entryPoint = new MethodDefUser("Main",
                MethodSig.CreateStatic(mod.CorLibTypes.Int32, new SZArraySig(mod.CorLibTypes.String)));
            entryPoint.Attributes = MethodAttributes.Private | MethodAttributes.Static |
                            MethodAttributes.HideBySig | MethodAttributes.ReuseSlot;
            entryPoint.ImplAttributes = MethodImplAttributes.IL | MethodImplAttributes.Managed;
            // Name the 1st argument (argument 0 is the return type)
            entryPoint.ParamDefs.Add(new ParamDefUser("args", 1));
            // Add the method to the startup type
            startUpType.Methods.Add(entryPoint);
            // Set module entry point
            mod.EntryPoint = entryPoint;

            // Create System.Console type reference
            var systemConsole = mod.CorLibTypes.GetTypeRef("System", "Console");
            // Create 'void System.Console.WriteLine(string,object)' method reference
            var writeLine2 = new MemberRefUser(mod, "WriteLine",
                            MethodSig.CreateStatic(mod.CorLibTypes.Void, mod.CorLibTypes.String,
                                mod.CorLibTypes.Object),
                            systemConsole);

            //
            // Method 1: Create List<String> inst signature by importing (easy way)
            // --------------------------------------------------------------------
            //Importer importer = new Importer(mod);
            //var listGenericInstSig = importer.ImportAsTypeSig(typeof(System.Collections.Generic.List<String>));

            //
            // Method 2: Create List<String> inst signature manually (harder way)
            // ------------------------------------------------------------------
            var assemblyRef = mod.CorLibTypes.AssemblyRef;
            var listRef = new TypeRefUser(mod, @"System.Collections.Generic", "List`1", assemblyRef);
            // Create the GenericInstSig from a ClassSig with <String> generic arg
            var listGenericInstSig = new GenericInstSig(new ClassSig(listRef), mod.CorLibTypes.String);

            // Create TypeSpec from GenericInstSig
            var listTypeSpec = new TypeSpecUser(listGenericInstSig);
            // Create System.Collections.Generic.List<String>::.ctor method reference
            var listCtor = new MemberRefUser(mod, ".ctor", MethodSig.CreateInstance(mod.CorLibTypes.Void),
                listTypeSpec);

            // Create Add(!0) method reference, !0 signifying first generic argument of declaring type
            // In this case, would be Add(String item)
            // (GenericMVar would be used for method generic argument, such as Add<!!0>(!!0))
            var listAdd = new MemberRefUser(mod, "Add",
                MethodSig.CreateInstance(mod.CorLibTypes.Void, new GenericVar(0)),
                listTypeSpec);

            var listGetCount = new MemberRefUser(mod, "get_Count",
                MethodSig.CreateInstance(mod.CorLibTypes.Int32),
                listTypeSpec);

            IList<Local> locals = new List<Local>();
            locals.Add(new Local(listGenericInstSig)); // local[0]: class [mscorlib]System.Collections.Generic.List`1<string>

            var body = new CilBody(true, new List<Instruction>(), new List<ExceptionHandler>(), locals);
            // Call the list .ctor
            body.Instructions.Add(OpCodes.Newobj.ToInstruction(listCtor));
            body.Instructions.Add(OpCodes.Stloc_0.ToInstruction()); // Store list to local[0]

            // list.Add("Item 1")
            body.Instructions.Add(OpCodes.Ldloc_0.ToInstruction());
            body.Instructions.Add(OpCodes.Ldstr.ToInstruction("Item 1"));
            body.Instructions.Add(OpCodes.Callvirt.ToInstruction(listAdd));

            // WriteLine("Array: {0}", list.ToArray());
            //body.Instructions.Add(OpCodes.Ldstr.ToInstruction("Array: {0}"));
            //body.Instructions.Add(OpCodes.Ldloc_0.ToInstruction()); // Load list from local[0]
            //body.Instructions.Add(OpCodes.Callvirt.ToInstruction(listToArray));
            //body.Instructions.Add(OpCodes.Call.ToInstruction(writeLine2));

            // WriteLine("Count: {0}", list.Count)
            body.Instructions.Add(OpCodes.Ldstr.ToInstruction("Count: {0}"));
            body.Instructions.Add(OpCodes.Ldloc_0.ToInstruction()); // Load list from local[0]
            body.Instructions.Add(OpCodes.Callvirt.ToInstruction(listGetCount));
            body.Instructions.Add(OpCodes.Box.ToInstruction(mod.CorLibTypes.Int32));
            body.Instructions.Add(OpCodes.Call.ToInstruction(writeLine2));

            // return 0;
            body.Instructions.Add(OpCodes.Ldc_I4_0.ToInstruction());
            body.Instructions.Add(OpCodes.Ret.ToInstruction());

            entryPoint.Body = body;

            // Save the assembly
            mod.Write(newFileName);
        }
예제 #52
0
        static void Inspection(ConfuserContext context)
        {
            context.Logger.Info("Resolving dependencies...");
            foreach (var dependency in context.Modules
                                              .SelectMany(module => module.GetAssemblyRefs().Select(asmRef => Tuple.Create(asmRef, module)))) {
                try {
                    AssemblyDef assembly = context.Resolver.ResolveThrow(dependency.Item1, dependency.Item2);
                }
                catch (AssemblyResolveException ex) {
                    context.Logger.ErrorException("Failed to resolve dependency of '" + dependency.Item2.Name + "'.", ex);
                    throw new ConfuserException(ex);
                }
            }

            context.Logger.Debug("Checking Strong Name...");
            foreach (ModuleDefMD module in context.Modules) {
                var snKey = context.Annotations.Get<StrongNameKey>(module, Marker.SNKey);
                if (snKey == null && module.IsStrongNameSigned)
                    context.Logger.WarnFormat("[{0}] SN Key is not provided for a signed module, the output may not be working.", module.Name);
                else if (snKey != null && !module.IsStrongNameSigned)
                    context.Logger.WarnFormat("[{0}] SN Key is provided for an unsigned module, the output may not be working.", module.Name);
                else if (snKey != null && module.IsStrongNameSigned &&
                         !module.Assembly.PublicKey.Data.SequenceEqual(snKey.PublicKey))
                    context.Logger.WarnFormat("[{0}] Provided SN Key and signed module's public key do not match, the output may not be working.", module.Name);
            }

            var marker = context.Registry.GetService<IMarkerService>();

            context.Logger.Debug("Creating global .cctors...");
            foreach (ModuleDefMD module in context.Modules) {
                TypeDef modType = module.GlobalType;
                if (modType == null) {
                    modType = new TypeDefUser("", "<Module>", null);
                    modType.Attributes = TypeAttributes.AnsiClass;
                    module.Types.Add(modType);
                    marker.Mark(modType, null);
                }
                MethodDef cctor = modType.FindOrCreateStaticConstructor();
                if (!marker.IsMarked(cctor))
                    marker.Mark(cctor, null);
            }

            context.Logger.Debug("Watermarking...");
            foreach (ModuleDefMD module in context.Modules) {
                TypeRef attrRef = module.CorLibTypes.GetTypeRef("System", "Attribute");
                var attrType = new TypeDefUser("", "ConfusedByAttribute", attrRef);
                module.Types.Add(attrType);
                marker.Mark(attrType, null);

                var ctor = new MethodDefUser(
                    ".ctor",
                    MethodSig.CreateInstance(module.CorLibTypes.Void, module.CorLibTypes.String),
                    MethodImplAttributes.Managed,
                    MethodAttributes.HideBySig | MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName);
                ctor.Body = new CilBody();
                ctor.Body.MaxStack = 1;
                ctor.Body.Instructions.Add(OpCodes.Ldarg_0.ToInstruction());
                ctor.Body.Instructions.Add(OpCodes.Call.ToInstruction(new MemberRefUser(module, ".ctor", MethodSig.CreateInstance(module.CorLibTypes.Void), attrRef)));
                ctor.Body.Instructions.Add(OpCodes.Ret.ToInstruction());
                attrType.Methods.Add(ctor);
                marker.Mark(ctor, null);

                var attr = new CustomAttribute(ctor);
                attr.ConstructorArguments.Add(new CAArgument(module.CorLibTypes.String, Version));

                module.CustomAttributes.Add(attr);
            }
        }
예제 #53
0
        public static void Run()
        {
            // This is the file that will be created
            string newFileName = "GenericExample3.exe";

            // Create the module
            var mod = new ModuleDefUser("GenericExample3", Guid.NewGuid(),
                new AssemblyRefUser(new AssemblyNameInfo(typeof(int).Assembly.GetName().FullName)));
            // It's a console app
            mod.Kind = ModuleKind.Console;
            // Create the assembly and add the created module to it
            new AssemblyDefUser("GenericExample3", new Version(1, 2, 3, 4)).Modules.Add(mod);

            // Add the startup type. It derives from System.Object.
            TypeDef startUpType = new TypeDefUser("My.Namespace", "Startup", mod.CorLibTypes.Object.TypeDefOrRef);
            startUpType.Attributes = TypeAttributes.NotPublic | TypeAttributes.AutoLayout |
                                    TypeAttributes.Class | TypeAttributes.AnsiClass;
            // Add the type to the module
            mod.Types.Add(startUpType);

            // Create the entry point method
            MethodDef entryPoint = new MethodDefUser("Main",
                MethodSig.CreateStatic(mod.CorLibTypes.Int32, new SZArraySig(mod.CorLibTypes.String)));
            entryPoint.Attributes = MethodAttributes.Private | MethodAttributes.Static |
                            MethodAttributes.HideBySig | MethodAttributes.ReuseSlot;
            entryPoint.ImplAttributes = MethodImplAttributes.IL | MethodImplAttributes.Managed;
            // Name the 1st argument (argument 0 is the return type)
            entryPoint.ParamDefs.Add(new ParamDefUser("args", 1));
            // Add the method to the startup type
            startUpType.Methods.Add(entryPoint);
            // Set module entry point
            mod.EntryPoint = entryPoint;

            // Create a type with 2 generic parameters, A and B
            // Would look like: public class GClass<A, B>
            var genericType = new TypeDefUser("My.Namespace", "GClass", mod.CorLibTypes.Object.TypeDefOrRef);
            genericType.Attributes = TypeAttributes.Public | TypeAttributes.AutoLayout |
                TypeAttributes.Class | TypeAttributes.AnsiClass | TypeAttributes.BeforeFieldInit;
            genericType.GenericParameters.Add(new GenericParamUser(0, GenericParamAttributes.NonVariant, "A"));
            genericType.GenericParameters.Add(new GenericParamUser(1, GenericParamAttributes.NonVariant, "B"));
            // Add generic type to module
            mod.Types.Add(genericType);

            // Note: NestedPublic instead of Public, blank namespace
            // Would look like: public class GSubClass<A, B, C>
            var genericSubType = new TypeDefUser("", "GSubClass", mod.CorLibTypes.Object.TypeDefOrRef);
            genericSubType.Attributes = TypeAttributes.NestedPublic | TypeAttributes.AutoLayout |
                TypeAttributes.Class | TypeAttributes.AnsiClass | TypeAttributes.BeforeFieldInit;
            // Need to add the 2 generic parameters from the nested-parent class, A and B
            genericSubType.GenericParameters.Add(new GenericParamUser(0, GenericParamAttributes.NonVariant, "A"));
            genericSubType.GenericParameters.Add(new GenericParamUser(1, GenericParamAttributes.NonVariant, "B"));
            // Add a generic parameter specific to this nested class, C
            genericSubType.GenericParameters.Add(new GenericParamUser(2, GenericParamAttributes.NonVariant, "C"));

            // public void GSubClass<A, B, C>.SomeMethod(B arg1, C arg2) { ... }
            // or: public void GSubClass<!0, !1, !2>.SomeMethod(!1, !2) { ... }
            var someMethod = new MethodDefUser("SomeMethod",
                MethodSig.CreateInstance(mod.CorLibTypes.Void, new GenericVar(1), new GenericVar(2)));
            someMethod.Attributes = MethodAttributes.Public;
            someMethod.ImplAttributes = MethodImplAttributes.IL | MethodImplAttributes.Managed;
            genericSubType.Methods.Add(someMethod);

            // Create method with a method generic parameter (GenericMVar)
            // public void GSubClass<A, B, C>.SomeOtherMethod<D>(D arg1, A arg2, C arg3) { ... }
            // or: public void GSubClass<!0, !1, !2>.SomeOtherMethod<!!0>(!!0, !0, !2) { ... }
            var someGenericMethod = new MethodDefUser("SomeOtherMethod",
                MethodSig.CreateInstanceGeneric(1, mod.CorLibTypes.Void, new GenericMVar(0), new GenericVar(0), new GenericVar(2)));
            someGenericMethod.Attributes = MethodAttributes.Public;
            someGenericMethod.ImplAttributes = MethodImplAttributes.IL | MethodImplAttributes.Managed;
            // Create GenericParam for !!0
            someGenericMethod.GenericParameters.Add(new GenericParamUser(0, GenericParamAttributes.NonVariant, "D"));
            genericSubType.Methods.Add(someGenericMethod);

            // Add as nested type
            genericType.NestedTypes.Add(genericSubType);

            someMethod.Body = new CilBody();
            someMethod.Body.Instructions.Add(OpCodes.Ret.ToInstruction());

            someGenericMethod.Body = new CilBody();
            someGenericMethod.Body.Instructions.Add(OpCodes.Ret.ToInstruction());

            entryPoint.Body = new CilBody();
            entryPoint.Body.Instructions.Add(OpCodes.Ldc_I4_0.ToInstruction());
            entryPoint.Body.Instructions.Add(OpCodes.Ret.ToInstruction());

            mod.Write(newFileName);
        }
예제 #54
0
		// Copies most things but not everything
		public static MethodDef Clone(MethodDef method) {
			var newMethod = new MethodDefUser(method.Name, method.MethodSig, method.ImplAttributes, method.Attributes);
			newMethod.Rid = method.Rid;
			newMethod.DeclaringType2 = method.DeclaringType;
			foreach (var pd in method.ParamDefs)
				newMethod.ParamDefs.Add(new ParamDefUser(pd.Name, pd.Sequence, pd.Attributes));
			foreach (var gp in method.GenericParameters) {
				var newGp = new GenericParamUser(gp.Number, gp.Flags, gp.Name);
				foreach (var gpc in gp.GenericParamConstraints)
					newGp.GenericParamConstraints.Add(new GenericParamConstraintUser(gpc.Constraint));
				newMethod.GenericParameters.Add(newGp);
			}
			newMethod.Body = new CilBody();
			CopyBodyFromTo(method, newMethod);
			return newMethod;
		}
		/// <summary>
		/// Create an entry point method which calls all virtualizable methods.
		/// </summary>
		/// <param name="module">Module</param>
		/// <param name="methods">Methods to call</param>
		/// <returns>Entry point method</returns>
		MethodDef CreateEntryPoint(ModuleDef module, IList<MethodDef> methods)
		{
			MethodDef entryPoint = new MethodDefUser("Main",
				MethodSig.CreateStatic(module.CorLibTypes.Int32, new SZArraySig(module.CorLibTypes.String)));

			entryPoint.Attributes = MethodAttributes.Private | MethodAttributes.Static |
				MethodAttributes.HideBySig | MethodAttributes.ReuseSlot;
			entryPoint.ImplAttributes = MethodImplAttributes.IL | MethodImplAttributes.Managed;
			entryPoint.ParamDefs.Add(new ParamDefUser("args", 1));

			entryPoint.Body = new CilBody();
			var instructions = entryPoint.Body.Instructions;

			foreach (var method in methods)
				instructions.Add(OpCodes.Call.ToInstruction(method));

			instructions.Add(OpCodes.Ldc_I4_0.ToInstruction());
			instructions.Add(OpCodes.Ret.ToInstruction());

			// Set itself as entry point
			module.EntryPoint = entryPoint;

			return entryPoint;
		}