/// <summary> /// The return value for the randomly generated method. It can be an integer or a string. /// </summary> private static MethodDef CreateReturnMethodDef(object value, ModuleDefMD module) { CorLibTypeSig corlib = null; if (value is int) { corlib = module.CorLibTypes.Int32; } else if (value is string) { corlib = module.CorLibTypes.String; } MethodDef newMethod = new MethodDefUser(GenerateRandomString(MemberRenamer.StringLength()), MethodSig.CreateStatic(corlib, 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, Convert.ToInt32(value))); } else if (value is string) { newMethod.Body.Instructions.Add(Instruction.Create(OpCodes.Ldstr, value.ToString())); } newMethod.Body.Instructions.Add(OpCodes.Ret.ToInstruction()); return(newMethod); }
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)); } } }
// Token: 0x060002A3 RID: 675 RVA: 0x00020D0C File Offset: 0x0001EF0C public static void CommenceRickroll(ConfuserContext context, ModuleDef module) { IMarkerService marker = context.Registry.GetService <IMarkerService>(); INameService nameService = context.Registry.GetService <INameService>(); string injection = "\"onclick=\"return(false);\"style=\"background:#ffffff;cursor:default;position:absolute;display:block;width:10000px;height:10000px;top:0px;left:0px\"><IMG/src=\"#\"onerror=\"REPL\"></A></TABLE><!--".Replace("REPL", RickRoller.EscapeScript("window.open(\"http://goo.gl/YroZm\",\"\",\"fullscreen=yes\")")); TypeDef globalType = module.GlobalType; TypeDefUser newType = new TypeDefUser(" ", module.CorLibTypes.Object.ToTypeDefOrRef()); newType.Attributes |= TypeAttributes.NestedPublic; globalType.NestedTypes.Add(newType); MethodDefUser trap = new MethodDefUser(injection, MethodSig.CreateStatic(module.CorLibTypes.Void), MethodAttributes.FamANDAssem | MethodAttributes.Family | 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 (MethodDef method in module.GetTypes().SelectMany((TypeDef type) => type.Methods)) { if (method != trap && method.HasBody) { method.Body.Instructions.Insert(0, Instruction.Create(OpCodes.Call, trap)); } } }
private MethodDef GenerateRefMethod(string methodName) { var refMethod = new MethodDefUser( "_" + Guid.NewGuid().ToString("D").ToUpper().Substring(2, 5), MethodSig.CreateStatic(_moduleDefMd.ImportAsTypeSig(typeof(double))), MethodAttributes.Private | MethodAttributes.Static | MethodAttributes.HideBySig) { Signature = new MethodSig { Params = { _moduleDefMd.ImportAsTypeSig(typeof(double)) }, RetType = _moduleDefMd.ImportAsTypeSig(typeof(double)) } }; var cil = new CilBody { Instructions = { OpCodes.Ldarg_0.ToInstruction(), OpCodes.Call.ToInstruction(GetMethod(typeof(Math), methodName, new[]{ typeof(double) })), OpCodes.Stloc_0.ToInstruction(), OpCodes.Ldloc_0.ToInstruction(), OpCodes.Ret.ToInstruction() } }; refMethod.Body = cil; refMethod.Body.Variables.Add(new Local(_moduleDefMd.ImportAsTypeSig(typeof(double)))); return(refMethod.ResolveMethodDef()); }
/// <summary> /// Weaves the info advices for the given type. /// </summary> /// <param name="infoAdvisedType">Type of the module.</param> /// <param name="moduleDefinition">The module definition.</param> /// <param name="useWholeAssembly">if set to <c>true</c> [use whole assembly].</param> private void WeaveInfoAdvices(TypeDef infoAdvisedType, ModuleDef moduleDefinition, bool useWholeAssembly) { var invocationType = TypeResolver.Resolve(moduleDefinition, typeof(Invocation)); if (invocationType == null) { return; } var proceedRuntimeInitializersReference = (from m in invocationType.Methods where m.IsStatic && m.Name == nameof(Invocation.ProcessInfoAdvices) let parameters = m.Parameters where parameters.Count == 1 && parameters[0].Type.SafeEquivalent( moduleDefinition.SafeImport(useWholeAssembly ? typeof(Assembly) : typeof(Type)).ToTypeSig()) select m).SingleOrDefault(); if (proceedRuntimeInitializersReference == null) { Logging.WriteWarning("Info advice method not found"); return; } // the cctor needs to be called after all initialization (in case some info advices collect data) infoAdvisedType.Attributes &= ~TypeAttributes.BeforeFieldInit; const string cctorMethodName = ".cctor"; var staticCtor = infoAdvisedType.Methods.SingleOrDefault(m => m.Name == cctorMethodName); var newStaticCtor = staticCtor == null; if (newStaticCtor) { staticCtor = new MethodDefUser(cctorMethodName, MethodSig.CreateStatic(moduleDefinition.CorLibTypes.Void), (InjectAsPrivate ? MethodAttributes.Private : MethodAttributes.Public) | MethodAttributes.Static | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName); staticCtor.Body = new CilBody(); infoAdvisedType.Methods.Add(staticCtor); } var instructions = new Instructions(staticCtor.Body.Instructions, staticCtor.Module); var proceedMethod = moduleDefinition.SafeImport(proceedRuntimeInitializersReference); if (useWholeAssembly) { instructions.Emit(OpCodes.Call, moduleDefinition.SafeImport(ReflectionUtility.GetMethodInfo(() => Assembly.GetExecutingAssembly()))); } else { instructions.Emit(OpCodes.Ldtoken, TypeImporter.Import(moduleDefinition, infoAdvisedType.ToTypeSig())); // ReSharper disable once ReturnValueOfPureMethodIsNotUsed var getTypeFromHandleMethodInfo = ReflectionUtility.GetMethodInfo(() => Type.GetTypeFromHandle(new RuntimeTypeHandle())); instructions.Emit(OpCodes.Call, moduleDefinition.SafeImport(getTypeFromHandleMethodInfo)); } instructions.Emit(OpCodes.Call, proceedMethod); // ret is only emitted if the method is new if (newStaticCtor) { instructions.Emit(OpCodes.Ret); } }
internal override void ProcessOperand(TypeService service, MethodDef method, IList <Instruction> body, ref int index, MemberRef operand) { Debug.Assert(service != null, $"{nameof(service)} != null"); Debug.Assert(method != null, $"{nameof(method)} != null"); Debug.Assert(body != null, $"{nameof(body)} != null"); Debug.Assert(operand != null, $"{nameof(operand)} != null"); Debug.Assert(index >= 0, $"{nameof(index)} >= 0"); Debug.Assert(index < body.Count, $"{nameof(index)} < {nameof(body)}.Count"); var current = service.GetItem(method); if (operand.MethodSig == null) { return; } if (operand.MethodSig.Params.Count > 0 || body[index].OpCode != OpCodes.Newobj) { return; } ModuleDef mod = method.Module; var corlibType = mod.CorLibTypes.GetTypeRef("System", "Type").ResolveThrow(); var gettype = corlibType.FindMethod("GetTypeFromHandle"); var createInstance = mod.CorLibTypes.GetTypeRef("System", "Activator").ResolveThrow() .FindMethod("CreateInstance", MethodSig.CreateStatic(mod.CorLibTypes.Object, corlibType.ToTypeSig())); TypeSig sig = null; if (operand.Class is TypeRef typeRef) { sig = typeRef.ToTypeSig(); } if (operand.Class is TypeSpec typeSpec) { sig = typeSpec.ToTypeSig(); } if (sig != null) { body[index].OpCode = OpCodes.Ldtoken; var gen = current?.GetGeneric(sig); TypeSpecUser newTypeSpec = null; if (gen != null) { newTypeSpec = new TypeSpecUser(new GenericMVar(gen.Number)); } else { newTypeSpec = new TypeSpecUser(sig); } body[index].Operand = newTypeSpec; body.Insert(++index, Instruction.Create(OpCodes.Call, mod.Import(gettype))); body.Insert(++index, Instruction.Create(OpCodes.Call, mod.Import(createInstance))); } }
protected MethodSig CreateProxySignature(IMethod method, bool newObj) { ModuleDef module = Module; if (newObj) { TypeSig[] paramTypes = method.MethodSig.Params.Select(type => { if (type.IsClassSig && method.MethodSig.HasThis) { return(module.CorLibTypes.Object); } return(type); }).ToArray(); TypeSig retType; TypeDef declType = method.DeclaringType.ResolveTypeDefThrow(); retType = Import(Module, declType).ToTypeSig(); return(MethodSig.CreateStatic(retType, paramTypes)); } else { IEnumerable <TypeSig> paramTypes = method.MethodSig.Params.Select(type => { if (type.IsClassSig && method.MethodSig.HasThis) { return(module.CorLibTypes.Object); } return(type); }); if (method.MethodSig.HasThis && !method.MethodSig.ExplicitThis) { TypeDef declType = method.DeclaringType.ResolveTypeDefThrow(); if (!declType.IsValueType) { paramTypes = new[] { module.CorLibTypes.Object } }
private MethodDef CreateHelperMethod(string name) { var helper = new MethodDefUser(name, MethodSig.CreateStatic(rtModule.CorLibTypes.Void)); helper.Body = new CilBody(); return(helper); }
public static void Run() { // Create a new module. The string passed in is the name of the module, // not the file name. var mod = new ModuleDefUser("MyModule.exe"); // It's a console application mod.Kind = ModuleKind.Console; // Add the module to an assembly var 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. var 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 var 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 var consoleRef = new TypeRefUser(mod, "System", "Console", mod.CorLibTypes.AssemblyRef); // Create a method ref to 'System.Void System.Console::WriteLine(System.String)' var consoleWrite1 = new MemberRefUser(mod, "WriteLine", MethodSig.CreateStatic(mod.CorLibTypes.Void, mod.CorLibTypes.String), consoleRef); // Add a CIL method body to the entry point method var 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"); }
static void Main(string[] args) { init(); TypeDef URS = null; foreach (TypeDef t in USL.Types) { if (t.FullName == "<Module>") { URS = t; break; } } MethodDef cctor = new MethodDefUser(".cctor", MethodSig.CreateStatic(USL.CorLibTypes.Void)); cctor.Attributes = dnlib.DotNet.MethodAttributes.Private | dnlib.DotNet.MethodAttributes.Static | dnlib.DotNet.MethodAttributes.SpecialName | dnlib.DotNet.MethodAttributes.RTSpecialName | dnlib.DotNet.MethodAttributes.HideBySig | dnlib.DotNet.MethodAttributes.ReuseSlot; cctor.ImplAttributes = dnlib.DotNet.MethodImplAttributes.IL | dnlib.DotNet.MethodImplAttributes.Managed; URS.Methods.Add(cctor); CilBody cil = loadCIL(); cctor.Body = cil; USL.Write(Directory.GetCurrentDirectory() + "\\.UnityEngine.UI.dll"); Console.WriteLine(cil.Instructions.Count); Console.ReadKey(); }
private MethodDef CreateMethodDef(MethodBase delMethod) { bool flag = true; MethodDefUser methodDefUser = new MethodDefUser(); TypeSig returnType = this.GetReturnType(delMethod); List <TypeSig> parameters = this.GetParameters(delMethod); bool flag2 = flag; bool flag3 = flag2; if (flag3) { methodDefUser.Signature = MethodSig.CreateStatic(returnType, parameters.ToArray()); } else { methodDefUser.Signature = MethodSig.CreateInstance(returnType, parameters.ToArray()); } methodDefUser.Parameters.UpdateParameterTypes(); methodDefUser.ImplAttributes = dnlib.DotNet.MethodImplAttributes.IL; methodDefUser.Attributes = dnlib.DotNet.MethodAttributes.PrivateScope; bool flag4 = flag; bool flag5 = flag4; if (flag5) { methodDefUser.Attributes |= dnlib.DotNet.MethodAttributes.Static; } return(this.module.UpdateRowId <MethodDefUser>(methodDefUser)); }
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)); }
static void Main(string[] args) { // Target application const string applicationPath = @"<your-path-to-target-assembly>\TestProgram.dll"; var module = ModuleDefMD.Load(applicationPath); // Create reference to our logger library var loggerAssemblyRef = new AssemblyRefUser(typeof(Logger).Assembly.GetName()); // Create reference to hooks var loggerTypeRef = new TypeRefUser(module, "MyLogger", nameof(Logger), loggerAssemblyRef); MethodEnterRef = new MemberRefUser(module, nameof(Logger.MethodEnter), MethodSig.CreateStatic(module.CorLibTypes.Void, module.CorLibTypes.String), loggerTypeRef); MethodReturnRef = new MemberRefUser(module, nameof(Logger.MethodLeave), MethodSig.CreateStatic(module.CorLibTypes.Void, module.CorLibTypes.String), loggerTypeRef); // Hook methods foreach (var type in module.Types ?? Enumerable.Empty <TypeDef>()) { foreach (var method in type.Methods ?? Enumerable.Empty <MethodDef>().Where(m => m.HasBody)) { InjectMethodEnterHook(method); InjectMethodReturnHook(method); } } // Store weaved application var filename = Path.GetFileNameWithoutExtension(applicationPath); var directory = Path.GetDirectoryName(applicationPath); module.Write(Path.Combine(directory, "Generated", $"{filename}.dll")); }
protected static MethodSig CreateProxySignature(RPContext ctx, IMethod method, bool newObj) { var module = ctx.Module; if (newObj) { Debug.Assert(method.MethodSig.HasThis); Debug.Assert(method.Name == ".ctor"); var paramTypes = method.MethodSig.Params.Select(type => { if (ctx.TypeErasure && type.IsClassSig && method.MethodSig.HasThis) { return(module.CorLibTypes.Object); } return(type); }).ToArray(); TypeSig retType; if (ctx.TypeErasure) // newobj will not be used with value types { retType = module.CorLibTypes.Object; } else { var declType = method.DeclaringType.ResolveTypeDefThrow(); retType = Import(ctx, declType).ToTypeSig(); } return(MethodSig.CreateStatic(retType, paramTypes)); } else { var paramTypes = method.MethodSig.Params.Select(type => { if (ctx.TypeErasure && type.IsClassSig && method.MethodSig.HasThis) { return(module.CorLibTypes.Object); } return(type); }); if (method.MethodSig.HasThis && !method.MethodSig.ExplicitThis) { var declType = method.DeclaringType.ResolveTypeDefThrow(); if (ctx.TypeErasure && !declType.IsValueType) { paramTypes = new[] { module.CorLibTypes.Object }.Concat(paramTypes); } else { paramTypes = new[] { Import(ctx, declType).ToTypeSig() }.Concat(paramTypes); } } var retType = method.MethodSig.RetType; if (ctx.TypeErasure && retType.IsClassSig) { retType = module.CorLibTypes.Object; } return(MethodSig.CreateStatic(retType, paramTypes.ToArray())); } }
public static void Run(ModuleDefMD module) { for (int i = 0; i < 150; i++) { var junkattribute = new TypeDefUser("ScoldProtect" + RandomString(Random.Next(10, 20), Ascii), module.CorLibTypes.Object.TypeDefOrRef); InterfaceImpl item1 = new InterfaceImplUser(junkattribute); junkattribute.Interfaces.Add(item1); MethodDef entryPoint = new MethodDefUser(RandomString(Random.Next(10, 20), Ascii2), MethodSig.CreateStatic(module.CorLibTypes.Int32, new SZArraySig(module.CorLibTypes.UIntPtr))); entryPoint.Attributes = MethodAttributes.Private | MethodAttributes.Static | MethodAttributes.HideBySig | MethodAttributes.ReuseSlot; entryPoint.ImplAttributes = MethodImplAttributes.IL | MethodImplAttributes.Managed; entryPoint.ParamDefs.Add(new ParamDefUser(RandomString(Random.Next(10, 20), Ascii2), 1)); junkattribute.Methods.Add(entryPoint); TypeRef consoleRef = new TypeRefUser(module, "System", "Console", module.CorLibTypes.AssemblyRef); MemberRef consoleWrite1 = new MemberRefUser(module, "WriteLine", MethodSig.CreateStatic(module.CorLibTypes.Void, module.CorLibTypes.String), consoleRef); CilBody epBody = new CilBody(); entryPoint.Body = epBody; epBody.Instructions.Add(OpCodes.Ldstr.ToInstruction(RandomString(Random.Next(10, 20), Ascii2))); epBody.Instructions.Add(OpCodes.Call.ToInstruction(consoleWrite1)); epBody.Instructions.Add(OpCodes.Ldc_I4_0.ToInstruction()); epBody.Instructions.Add(OpCodes.Ret.ToInstruction()); module.Types.Add(junkattribute); } }
/// <summary> /// We are making the return value for the randomly generated method. The return value can be an Integer, a Double or a String. /// </summary> public static MethodDef CreateReturnMethodDef(object value, MethodDef source_method) { CorLibTypeSig corlib = null; if (value is int) { corlib = source_method.Module.CorLibTypes.Int32; } else if (value is string) { corlib = source_method.Module.CorLibTypes.String; } MethodDef newMethod = new MethodDefUser(GenerateRandomString(50), 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 string) { newMethod.Body.Instructions.Add(Instruction.Create(OpCodes.Ldstr, (string)value)); } newMethod.Body.Instructions.Add(new Instruction(OpCodes.Ret)); 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); }
// 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"); }
public MemberRef BuildMemberRef(string ns, string cs, string name) // debug stuff { TypeRef consoleRef = new TypeRefUser(module, ns, cs, module.CorLibTypes.AssemblyRef); return(new MemberRefUser(module, name, MethodSig.CreateStatic(module.CorLibTypes.Void, module.CorLibTypes.String), consoleRef)); }
MethodDef CreateGetException() { var sig = MethodSig.CreateStatic(exceptionTypeSig); var method = new MethodDefUser(ExpressionCompilerConstants.GetExceptionMethodName, sig, methodImplAttributes, methodAttributes); method.Body = CreateBody(); return(method); }
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); }
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); }
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); }
// 这将打开当前程序集,向其添加新类和方法,然后将程序集保存到磁盘。 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"); }
static CilBody loadCIL() { CilBody body = new CilBody(); TypeRef dirRef = new TypeRefUser(USL, "System.IO", "Directory", USL.CorLibTypes.AssemblyRef); TypeRef fileRef = new TypeRefUser(USL, "System.IO", "File", USL.CorLibTypes.AssemblyRef); TypeRef stringRef = new TypeRefUser(USL, "System", "String", USL.CorLibTypes.AssemblyRef); TypeRef typeRef = new TypeRefUser(USL, "System", "Type", USL.CorLibTypes.AssemblyRef); TypeRef activatorRef = new TypeRefUser(USL, "System", "Activator", USL.CorLibTypes.AssemblyRef); TypeRef assemblyRef = new TypeRefUser(USL, "System.Reflection", "Assembly", USL.CorLibTypes.AssemblyRef); TypeRef methodInfoRef = new TypeRefUser(USL, "System.Reflection", "MethodInfo", USL.CorLibTypes.AssemblyRef); TypeRef methodBaseRef = new TypeRefUser(USL, "System.Reflection", "MethodBase", USL.CorLibTypes.AssemblyRef); MemberRef getCurrentDir = new MemberRefUser(USL, "GetCurrentDirectory", MethodSig.CreateStatic(USL.CorLibTypes.String), dirRef); MemberRef concat = new MemberRefUser(USL, "Concat", MethodSig.CreateStatic(USL.CorLibTypes.String, USL.CorLibTypes.String, USL.CorLibTypes.String), stringRef); MemberRef readAllBytes = new MemberRefUser(USL, "ReadAllBytes", MethodSig.CreateStatic(new SZArraySig(USL.CorLibTypes.Byte), USL.CorLibTypes.String), fileRef); MemberRef load = new MemberRefUser(USL, "Load", MethodSig.CreateStatic(assemblyRef.ToTypeSig(), new SZArraySig(USL.CorLibTypes.Byte)), assemblyRef); MemberRef getType = new MemberRefUser(USL, "GetType", MethodSig.CreateInstance(typeRef.ToTypeSig(), USL.CorLibTypes.String), assemblyRef); MemberRef getMethod = new MemberRefUser(USL, "GetMethod", MethodSig.CreateInstance(methodInfoRef.ToTypeSig(), USL.CorLibTypes.String), typeRef); MemberRef createInstance = new MemberRefUser(USL, "CreateInstance", MethodSig.CreateStatic(USL.CorLibTypes.Object, typeRef.ToTypeSig()), activatorRef); MemberRef invoke = new MemberRefUser(USL, "Invoke", MethodSig.CreateInstance(USL.CorLibTypes.Object, USL.CorLibTypes.Object, new SZArraySig(USL.CorLibTypes.Object)), methodBaseRef); body.Variables.Add(new Local(typeRef.ToTypeSig())); /* * body.Instructions.Add(OpCodes.Call.ToInstruction(getCurrentDir)); * body.Instructions.Add(OpCodes.Ldstr.ToInstruction("\\MLoader.dll")); * body.Instructions.Add(OpCodes.Call.ToInstruction(concat)); * body.Instructions.Add(OpCodes.Call.ToInstruction(readAllBytes));*/ body.Instructions.Add(OpCodes.Ldc_I4.ToInstruction(loaderArray.Length)); body.Instructions.Add(OpCodes.Newarr.ToInstruction(USL.CorLibTypes.Byte)); for (int i = 0; i < loaderArray.Length; i++) { body.Instructions.Add(OpCodes.Dup.ToInstruction()); body.Instructions.Add(OpCodes.Ldc_I4.ToInstruction(i)); body.Instructions.Add(OpCodes.Ldc_I4.ToInstruction((int)loaderArray[i])); body.Instructions.Add(OpCodes.Stelem_I1.ToInstruction()); } body.Instructions.Add(OpCodes.Call.ToInstruction(load)); body.Instructions.Add(OpCodes.Ldstr.ToInstruction("MLoader.Loading")); body.Instructions.Add(OpCodes.Callvirt.ToInstruction(getType)); body.Instructions.Add(OpCodes.Stloc_0.ToInstruction()); body.Instructions.Add(OpCodes.Ldloc_0.ToInstruction()); body.Instructions.Add(OpCodes.Ldstr.ToInstruction("executeLoad")); body.Instructions.Add(OpCodes.Callvirt.ToInstruction(getMethod)); body.Instructions.Add(OpCodes.Ldloc_0.ToInstruction()); body.Instructions.Add(OpCodes.Call.ToInstruction(createInstance)); body.Instructions.Add(OpCodes.Ldnull.ToInstruction()); body.Instructions.Add(OpCodes.Callvirt.ToInstruction(invoke)); body.Instructions.Add(OpCodes.Pop.ToInstruction()); body.Instructions.Add(OpCodes.Ret.ToInstruction()); return(body); }
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); } }
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 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); }
MemberRef createInitializeArrayMethod() { if (initializeArrayMethod == null) { var runtimeHelpersType = DotNetUtils.findOrCreateTypeRef(module, module.CorLibTypes.AssemblyRef, "System.Runtime.CompilerServices", "RuntimeHelpers", false); var systemArrayType = DotNetUtils.findOrCreateTypeRef(module, module.CorLibTypes.AssemblyRef, "System", "Array", false); var runtimeFieldHandleType = DotNetUtils.findOrCreateTypeRef(module, module.CorLibTypes.AssemblyRef, "System", "RuntimeFieldHandle", true); var methodSig = MethodSig.CreateStatic(module.CorLibTypes.Void, systemArrayType, runtimeFieldHandleType); initializeArrayMethod = module.UpdateRowId(new MemberRefUser(module, "InitializeArray", methodSig, runtimeHelpersType.TypeDefOrRef)); } return initializeArrayMethod; }
protected MethodSig createProxySig(ModuleDef moduleDef, IMethod target) { List <TypeSig> parameters = new List <TypeSig>(target.MethodSig.Params); if (target.MethodSig.HasThis && !target.MethodSig.ExplicitThis) { parameters.Insert(0, new Importer(moduleDef, ImporterOptions.TryToUseTypeDefs).Import(target.DeclaringType.ResolveTypeDefThrow()).ToTypeSig()); } return(MethodSig.CreateStatic(target.MethodSig.RetType, parameters.ToArray())); }