开发者

Self-cloning executable with .NET reflection

开发者 https://www.devze.com 2023-04-09 18:50 出处:网络
I\'m trying a sort of experiment in C# .NET. I\'d like to create a program that clones itself (eventually as a mutated clone).Finally, I want it to produce a \"son\" that also needs to have the abilit

I'm trying a sort of experiment in C# .NET. I'd like to create a program that clones itself (eventually as a mutated clone). Finally, I want it to produce a "son" that also needs to have the ability to clone himself and so on!

I want to make something like this:

static void Main(string[] args)
        {

            string Son_Name = "son";
            string Full_Son_Name = Son_Name + ".exe";
            AssemblyName aName = new AssemblyName(Son_Name);
            AssemblyBuilder aBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(aName, AssemblyBuilderAccess.Save);
            ModuleBuilder mBuilder = aBuilder.DefineDynamicModule("Module", Full_Son_Name, false);
            TypeBuilder tBuilder = mBuilder.DefineType("Program", TypeAttributes.Public);
            MethodBuilder methodBuilder = tBuilder.DefineMethod("Main", MethodAttributes.Public | MethodAttributes.Static);
            ILGenerator ilGenerator = methodBuilder.GetILGenerator();
            MethodInfo m_ReadLine = typeof(System.Console).GetMethod("ReadLine", BindingFlags.Public | BindingFlags.Static);

            Clone_My_Main_method(methodbuilder);//I need something to do THAT 
            aBuilder.SetEntryPoint(methodBuilder);
       开发者_StackOverflow     tBuilder.CreateType();
            aBuilder.Save(Full_Son_Name);

So, with this code I succeded in making a dynamic assembly at runtime, and save it as "son.exe" or execute it. Now I need to "build" that assembly, reading my main and copying it into the son assembly.

I started using ilgenerator.emit, but I'm going into an infinite "programming" loop. I thought to make the parent.exe, disassemble it with ildasm, translate all the CIL code in ilgenerator.emit opcodes and emit all of that with ilgenerator.emit. Simply, I think this is a tedious work and cannot...work.

In fact, I'd like to READ at runtime my own main method, and then put it onto the dynamic assembly with some trick.

Anyone has any idea? Thanks :)


You should use Mono Cecil, which can read and modify .Net assemblies.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号