Skip to content

Instantly share code, notes, and snippets.

@pawlos
Last active October 25, 2019 19:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pawlos/4758365fdef3bcbf733ba73e636fcfb7 to your computer and use it in GitHub Desktop.
Save pawlos/4758365fdef3bcbf733ba73e636fcfb7 to your computer and use it in GitHub Desktop.
Uses Mono.Cecil to instrument the .NET application
using System;
using System.IO;
using System.Linq;
using Mono.Cecil;
using Mono.Cecil.Cil;
namespace TraceIL
{
class TraceIL
{
static void Main(string[] args)
{
if (args.Length != 1)
{
Console.WriteLine("TraceIL.exe <assembly>");
return;
}
string fileName = args[0];
ModuleDefinition module = ModuleDefinition.ReadModule(fileName);
MethodReference consoleWriteLine =
module.ImportReference(typeof(Console).GetMethod("WriteLine", new Type[] {typeof(object)}));
foreach (TypeDefinition type in module.Types)
{
foreach (var methodDefinition in type.Methods)
{
var ilBody = methodDefinition.Body;
var ilProcessor = ilBody.GetILProcessor();
var firstOp = methodDefinition.Body.Instructions.First();
var ldstrEntering = Instruction.Create(OpCodes.Ldstr, $"--Entering {methodDefinition.Name}");
ilProcessor.InsertBefore(firstOp, ldstrEntering);
var call = Instruction.Create(OpCodes.Call, consoleWriteLine);
ilProcessor.InsertBefore(firstOp, call);
var ldstrLeaving = Instruction.Create(OpCodes.Ldstr, $"--Leaving {methodDefinition.Name}");
var lastOp = methodDefinition.Body.Instructions.Last();
ilProcessor.InsertBefore(lastOp, ldstrLeaving);
ilProcessor.InsertBefore(lastOp, call);
}
}
module.Write(Path.GetFileNameWithoutExtension(fileName)+".modified"+Path.GetExtension(fileName));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment