65.9K
CodeProject is changing. Read more.
Home

NetDasm - A tool to disassemble and patch .NET assemblies

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.87/5 (25 votes)

May 31, 2007

CPOL

1 min read

viewsIcon

141260

downloadIcon

8312

Disassemble and patch .NET assemblies using the Mono.Cecil library.

Screenshot - Screen.jpg

Introduction

This article illustrates a little tool for disassembling a .NET assembly IL code and making some patches.

Background

For my application, I have used Mono.Cecil, a very powerful library for modifying IL code. If you want more info, visit the Cecil homepage.

Another Cecil article I found to be helpful is the one by ronnyek: MonoCecilChapter1.asp.

Using the code

You only need to load an assembly and look at all the types that it contains. When you click on one type, its methods and some information appear in the right. You can delete a type, delete a method, or edit the code of a method. In the Edit Code form, you can watch the IL code, remove a sentence, or insert a new sentence.

The basic code for using Cecil is:

AssemblyDefinition assembly = AssemblyFactory.GetAssembly("assembly.exe");
 
//Gets all types of the MainModule of the assembly

foreach(TypeDefinition type in assembly.MainModule.Types)
{
    if(type.Name != "<Module>")
    {
        //Gets all methods of the current type

        foreach(MethodDefinition method in type.Methods)
        {
            //Gets the CilWorker of the method for working with CIL instructions

            CilWorker worker = method.Body.CilWorker;
            //Creates the MSIL instruction for inserting the sentence

                   Instruction insertSentence = worker.Create(OpCodes.Ldstr, "Text");
 
 
            //Inserts the insertSentence instruction before the first //instruction

            method.Body.CilWorker.InsertBefore(method.Body.Instructions[0], 
                                               insertSentence);
        }
        //Import the modifying type into the AssemblyDefinition

        assembly.MainModule.Import(type);
    }    
} 
 
//Save the new assembly

AssemblyFactory.SaveAssembly(assembly, "new.exe");

Points of Interest

I want to improve the program and add some more options like methods insertion, feature to show C# code (like Reflector), and an improved instructions insertion.

History

  •  22/04/2013 - Created github repository 
  • 2/06/2007 - Update version
    • Code for IL tool added (only C# code)
    • Support for edit instructions
    • Filter for instructions
    • Some minor changes and bugs fixed
  • 1/06/2007 - Update version
    • Instructions documentation and auto-complete
    • Some interface changes
    • Multi-instructions remover
  • 31/05/2007 - First version