Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Modifying self with dnlib
C:\>ConsoleApp1.exe
dlroW olleH
using dnlib.DotNet;
using dnlib.DotNet.Emit;
using System;
using System.IO;
using System.Linq;
using System.Reflection;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
// Load ourself
var module = ModuleDefMD.Load(typeof(Program).Module);
// Get method definition of PrintStuff()
var method = module.Types
.FirstOrDefault(t => t.Name == "Program")
.Methods
.FirstOrDefault(m => m.Name == "PrintStuff");
// Overwrite the "Hello World" string
method.Body.Instructions.FirstOrDefault(i => i.OpCode == OpCodes.Ldstr).Operand = "dlroW olleH";
byte[] newAssembly;
// Output modified assembly to byte[]
using (var ms = new MemoryStream())
{
module.Write(ms);
newAssembly = ms.ToArray();
}
// Load new byte[]
var asm = Assembly.Load(newAssembly);
// Invoke the now modified PrintStuff method
asm.GetType("ConsoleApp1.Program").InvokeMember("PrintStuff", BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Static, null, null, null);
}
static void PrintStuff()
{
Console.WriteLine("Hello World");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment