Monitoring execution using Mono Cecil

This post will demonstrate how to monitor the execution of .Net code using Mono Cecil. This can be useful for logging, for performance analysis and just for fun. The concept is obviously IL weaving. We’ll look for entry points and existing IL instructions to weave around the new IL. In this post we’ll show only four types of monitoring, in reality we have some more. The four types are: Enter method, Exit method, Jump from method and Jump back to method. Jump in this context means call another method and return from the other method.
In our example we’ll assume we have some simple ‘notifier’ which the weaved code will call:

public class Notifier
{
public static Action<string> Enter;
public static Action<string> Exit;
public static Action<string> JumpOut;
public static Action<string> JumpBack;

public static void NotifyEnter(string methodName)
{
if (Enter != null)
{
Enter(methodName);
}
}

public static void NotifyExit(string methodName)
{
if (Exit != null)
{
Exit(methodName);
}
}

public static void NotifyJumpOut(string methodName)
{
if (JumpOut != null)
{
JumpOut(methodName);
}
}

public static void NotifyJumpBack(string methodName)
{
if (JumpBack != null)
{
JumpBack(methodName);
}
}
}

Monitoring enter

This is the most trivial weave, which inserts a call to Enter callback before the first instruction in the method body. In order to do so, we first need to load the assembly and find all the methods into which we can weave:

public void Weave()
{
AssemblyDefinition assembly = AssemblyDefinition.ReadAssembly(assemblyPath);

IEnumerable<MethodDefinition> methodDefinitions = assembly.MainModule.GetTypes()
.SelectMany(type => type.Methods).Where(method => method.HasBody);
foreach (var method in methodDefinitions)
{
WeaveMethod(assembly, method);
}

assembly.Write(assemblyPath);
}

Now we add reference to the the callbacks into the weaved assembly. This is not yet the weaving, this is required definition for the assembly to use in the weaved assembly. We’ll get the called methods using reflection:

Type notifierType = typeof (Notifier);
enterMethod = notifierType.GetMethod(
"NotifyEnter", BindingFlags.Public | BindingFlags.Static, null, new[] {typeof (string)}, null);
exitMethod = notifierType.GetMethod(
"NotifyExit", BindingFlags.Public | BindingFlags.Static, null, new[] {typeof (string)}, null);
jumpFromMethod = notifierType.GetMethod(
"NotifyJumpOut", BindingFlags.Public | BindingFlags.Static, null, new[] {typeof (string)}, null);
jumpBackMethod = notifierType.GetMethod(
"NotifyJumpBack", BindingFlags.Public | BindingFlags.Static, null, new[] {typeof (string)}, null);

Afterwards, we’ll add the references to the weaved assembly:

MethodReference enterReference = assembly.MainModule.Import(enterMethod);
MethodReference exitReference = assembly.MainModule.Import(exitMethod);
MethodReference jumpFromReference = assembly.MainModule.Import(jumpFromMethod);
MethodReference jumpBackReference = assembly.MainModule.Import(jumpBackMethod);

So our weave method looks like:

private static void WeaveMethod(AssemblyDefinition assembly, MethodDefinition method)
{
MethodReference enterReference = assembly.MainModule.Import(enterMethod);
MethodReference exitReference = assembly.MainModule.Import(exitMethod);
MethodReference jumpFromReference = assembly.MainModule.Import(jumpFromMethod);
MethodReference jumpBackReference = assembly.MainModule.Import(jumpBackMethod);

string name = method.DeclaringType.FullName + "." + method.Name;

WeaveEnter(method, enterReference, name);
WeaveJump(method, jumpFromReference, jumpBackReference, name);
WeaveExit(method, exitReference, name);
}

Now, we have everything ready to weave the enter monitoring code:

private static void WeaveEnter(MethodDefinition method, MethodReference methodReference, string name)
{
var ilProcessor = method.Body.GetILProcessor();

Instruction loadNameInstruction = ilProcessor.Create(OpCodes.Ldstr, name);
Instruction callEnterInstruction = ilProcessor.Create(OpCodes.Call, methodReference);

ilProcessor.InsertBefore(method.Body.Instructions.First(), loadNameInstruction);
ilProcessor.InsertAfter(loadNameInstruction, callEnterInstruction);
}

The ILProcessor is a helper utility which Cecil provides to make the weaving simpler. The first instruction we weave is loading of a string which is the name of the method being entered. The second instruction we weave is a call instruction which uses as argument the loaded string. We insert the instructions in the beginning of the method and from now on every time the method is entered the callback will be invoked.

Monitoring exit

Monitoring exit is a little more interesting. In contrast to enter where we have a single weaving point, exit may have multiple exit points – multiple return statements, thrown exceptions, etc…
Here we’ll monitor for simplicity return statements only:

private static void WeaveExit(MethodDefinition method, MethodReference exitReference, string name)
{
ILProcessor ilProcessor = method.Body.GetILProcessor();

List<Instruction> returnInstructions = method.Body.Instructions.Where(instruction => instruction.OpCode == OpCodes.Ret).ToList();
foreach (var returnInstruction in returnInstructions)
{
Instruction loadNameInstruction = ilProcessor.Create(OpCodes.Ldstr, name);
Instruction callExitReference = ilProcessor.Create(OpCodes.Call, exitReference);

ilProcessor.InsertBefore(returnInstruction, loadNameInstruction);
ilProcessor.InsertAfter(loadNameInstruction, callExitReference);
}
}

As can be seen, we first find all the return instructions. Afterwards, we insert before them call to our callback before them in a similar way to the enter callback.

Monitoring method jumps

This monitoring type will let us know when we jump to another method. If we are doing performance measuring, in an “ideal” world (where we have a single thread and no context switches) this would be the place where we stop and resume measuring the time for the executed method. Here for simplicity we’ll weave around simple call instructions, ignoring other types of call (like callvirt).

private static void WeaveJump(MethodDefinition method, MethodReference jumpFromReference, MethodReference jumpBackReference, string name)
{
ILProcessor ilProcessor = method.Body.GetILProcessor();

List<Instruction> callInstructions = method.Body.Instructions.Where(instruction => instruction.OpCode == OpCodes.Call).ToList();
foreach (var callInstruction in callInstructions)
{
Instruction loadNameForFromInstruction = ilProcessor.Create(OpCodes.Ldstr, name);
Instruction callJumpFromInstruction = ilProcessor.Create(OpCodes.Call, jumpFromReference);

ilProcessor.InsertBefore(callInstruction, loadNameForFromInstruction);
ilProcessor.InsertAfter(loadNameForFromInstruction, callJumpFromInstruction);

Instruction loadNameForBackInstruction = ilProcessor.Create(OpCodes.Ldstr, name);
Instruction callJumpBackInstruction = ilProcessor.Create(OpCodes.Call, jumpBackReference);

ilProcessor.InsertAfter(callInstruction, loadNameForBackInstruction);
ilProcessor.InsertAfter(loadNameForBackInstruction, callJumpBackInstruction);
}
}

Here, we find all the call instructions and insert a call to JumpFrom before them and a call to JumpBack after them. This way we get a call before leaving and returning to the method.

Example

public void MethodA()
{
MethodB();
}

private void MethodB()
{
}

If we execute MethodA we’re about to receive these calls:

  1. Enter MethodA
  2. JumpFrom MethodA
  3. Enter MethodB
  4. Exit MethodB
  5. JumpBack MethodA
  6. ExitMethod A

Summary

Mono Cecil can be used for low level AOP where the aspects’ targets are IL instructions. There are already some great tools out there for AOP like PostSharp, but it is cool to know how simply a solution can be implemented using Cecil.

Advertisements