Alter binary by adding try / finally in method

Jul 2, 2011 at 7:10 AM


I want to add try/finally block in one of the method using this library. Do we have any samples for this?

I'm trying add try/finally in following code,

public void FunctionVoid()
   Console.WriteLine("FunctionVoid called!!");

so I wrote following code using PERWAPI, 

CILInstructions instructions = methodDef.GetCodeBuffer();

instructions.StartBlock(); //try block

while (true)
   CILInstruction instCurrent = instructions.GetNextInstruction();

   if (instCurrent == null)


TryBlock tryblk1 = instructions.EndTryBlock(); //try end
instructions.StartBlock(); //finally

but, somehow it doesn't add finally block. If you look at patched binary in ildasm,

method public hidebysig instance void  FunctionVoid() cil managed
  // Code size       13 (0xd)
  .maxstack  1
    IL_0000:  nop
    IL_0001:  ldstr      "FunctionVoid called!!"
    IL_0006:  call       void [mscorlib]System.Console::WriteLine(string)
    IL_000b:  nop
  }  // end handler
  IL_000c:  ret
} // end of method Validate::FunctionVoid

Is there any thing wrong in my code? Can any body suggest me the correct method to add finally block using PERWAPI?


Jul 11, 2011 at 12:00 PM


I guess you can find out what the ILASM should look like by looking at the ILDASM output from a short C# program.

In order to see what methods to call to make it happen you might have a look at my old book "Compiling for the .NET Common Language Runtime" Prentice-Hall PTR (2002).  Borrow a copy and have a look.  Otherwise you can have a look at the source code of the Component Pascal Compiler, available on CodePlex as GPCP.  If you need a bigger pointer send me a message and I shall dig out the details and reply.

Cheers, John