Last active
October 25, 2019 19:52
-
-
Save pawlos/4758365fdef3bcbf733ba73e636fcfb7 to your computer and use it in GitHub Desktop.
Uses Mono.Cecil to instrument the .NET application
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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