Mono Cecil

Cecil is a library written by Jb Evain to generate and inspect programs and libraries in the ECMA CIL format. It has full support for generics, and support some debugging symbol format.

http://www.mono-project.com/Cecil

http://www.mono-project.com/Cecil:FAQ

https://github.com/jbevain/cecil/wiki/Importing

Download Cecil assembly http://obfuscar.googlecode.com/svn-history/r83/trunk/ThirdParty/Mono/Mono.Cecil.dll

IL Code rewriting

Sample program to change with Mono.Cecil

   1 /*
   2 mcs samples.cs
   3 mono sample.exe
   4 */
   5 public class Acme{
   6     public int Add(int arg1,int arg2){
   7       return arg1 + arg2;  
   8     }
   9 }
  10 
  11 public class Sample{
  12     public static void Main(string []args){
  13       new Acme().Add(4,9);  
  14     }
  15 }

Program to rewrite the sample program

   1 /*
   2 mcs rewrite.cs /r:Mono.Cecil.dll
   3 mono rewrite.exe 
   4 */
   5 using Mono.Cecil;
   6 using Mono.Cecil.Cil;
   7 
   8 public class RewriteIL{
   9   public static void Main(string []args){
  10     AssemblyDefinition ad = AssemblyDefinition.ReadAssembly("sample.exe");
  11     
  12     foreach(TypeDefinition td in ad.MainModule.Types){
  13       
  14       foreach(MethodDefinition md  in td.Methods){
  15         
  16         if(md.Name=="Add"){
  17           System.Console.WriteLine(td+"."+md);
  18 
  19           System.Console.WriteLine("Original IL Code:");
  20           foreach(Instruction inst in md.Body.Instructions){
  21             System.Console.WriteLine(inst);
  22           }
  23 
  24           var il = md.Body.GetILProcessor();
  25           var arg1 = il.Create (OpCodes.Ldarg_1);
  26           var arg2 = il.Create (OpCodes.Ldarg_2);
  27           MethodReference writeline = md.Module.Import( typeof(System.Console).GetMethod("WriteLine", new [] { typeof (int) }));
  28           var call = il.Create(OpCodes.Call,writeline);
  29 
  30           // insert the IL code in reversed order, at top of the method.
  31           // "normal" order would be ldarg.2 call ldarg.1 call ...
  32           il.InsertBefore (md.Body.Instructions[0], call);
  33           il.InsertBefore (md.Body.Instructions[0], arg2);
  34           il.InsertBefore (md.Body.Instructions[0], call);
  35           il.InsertBefore (md.Body.Instructions[0], arg1);
  36 
  37           System.Console.WriteLine("New IL Code:");
  38           foreach(Instruction inst in md.Body.Instructions){
  39             System.Console.WriteLine(inst);
  40           }
  41 
  42         }
  43       }
  44       
  45     }
  46 
  47     ad.Write("sampleRewrite.exe");
  48   }
  49 }

In the rewritten program the arguments for the Add method will appear on the console.

CSharp/MonoCecil (last edited 2014-03-06 21:29:40 by 188)