loading...

.NET Assembly Roundtripping

vijesh_salian profile image Vijesh Salian ・2 min read

What the heck is Roundtripping?

Assembly roundtripping is the act of decompiling an assembly to its IL( Intermediate Language) to edit it and then recompiling it to generate the assembly back.

In this post I am going to demonstrate how to roundtrip a .NET assembly.
To roundtrip, we need to

  1. Decompile to IL
  2. Edit IL
  3. Recompile to assembly
Tools required
  • ildasm
  • Visual Studio Developer Command Prompt
  • csc.exe - The C# compiler

Here is the C# file we are going to use for our demo.

using System;

public class Program
{
    public static void Main()
    {
        int x = 10;
        int y = 20;
        Console.WriteLine("The answer is {0}", x + y);
        Console.WriteLine("Hello, World!");
    }
}

I am going to name this file as roundtrip.cs.

In the VS developer command prompt, navigate to the location of the file roundtrip.cs. Now, I am going to compile this cs file into an assembly, an exe in this case. Here is the command.

csc.exe roundtrip.cs

There is an assembly created. roundtrip.exe. If you run this program you should get the following output. Nothing out of normal here.

The answer is 30
Hello, World!
Decompile to IL

Let's create an IL file for roundtrip.exe using ildasm with the following command.

ildasm /out=roundtrip.il roundtrip.exe

This will create a file roundtrip.il with IL code for roundtrip.exe.

Open this roundtrip.il in any editor. You will find all the IL code in the file. The main method in our C# file has a corresponding section in the IL. Look for the following line the IL file.

.method public hidebysig static void  Main() cil managed

In this section you should find a set of instructions that correspond to declaring and initializing the integers with 10, 20 respectively. There is a string that we are using. You will find that too.

.locals init (int32 V_0,
             int32 V_1)
    IL_0000:  nop
    IL_0001:  ldc.i4.s   10
    IL_0003:  stloc.0
    IL_0004:  ldc.i4.s   20
    IL_0006:  stloc.1
    IL_0007:  ldstr      "The answer is {0}"
    IL_000c:  ldloc.0
    IL_000d:  ldloc.1
    IL_000e:  add
Edit IL

Now for the edit part, let change the add operation to a multiplication. Replace add to mul

IL_000e:  mul

There is a Hello World string, let's change that string to Hello Dev.

Before:

IL_001a:  ldstr      "Hello, World!"

After:

IL_001a:  ldstr      "Hello, Dev!"

Make sure to save the IL file.

Recompile to assembly

Now is the time to recompile. In the VS dev prompt, type the following command. Note that this time we use ILASM and not ILDASM. We pass the edited IL file to the command.

ilasm /exe roundtrip.il

If there are no mistakes made in the IL, then you should find the new roundtrip.exe. When you run it you should see the following output.

The answer is 200
Hello, Dev!

Hope you found this interesting. Thank you for your attention.

Cheers 🍺

Discussion

pic
Editor guide