Search code examples
disassemblysystem.reflectioncil

How to parse a method invocation in IL bytes?


I know how to use the System.Reflection API, but not how to parse IL (Intermediate Language), though I do know how to parse x86 opcodes for what that's worth.

Now I want to find all the methods in an assembly which invoke a given method -- e.g., given a method named Namespace.Classname.Methodname, which methods in the assembly invoke it?

Assume I have the MethodInfo for the method in question.

To do this I suppose I must parse the bytes returned from the MethodBody.GetILAsByteArray method (which I don't know how to do).

The Note in the API Help says,

Parsing method bodies requires a thorough understanding of metadata and MSIL instruction formats. Information can be found in the Common Language Infrastructure (CLI) documentation, especially "Partition II: Metadata Definition and Semantics".

... which is a 500-page document.

Can you give me any hint of how to do it, outline the algorithm I'll implement, suggest an easy way to do it using a tool or library like ILSpy, or reference a suitable introduction to the topic before I start the wade through the referfence manual?

If it helps, I don't want to parse everything in the IL -- only to parse it just enough to find the method calls, especially the calls to constructors.


Solution

  • The IL byte stream can be parsed using the System.Reflection.Emit.OpCodes class. The opcodes OperandType field tells you how many bytes to read, to reach the next opcode. While iterating over the stream, metadata tokens can be resolved using the Module.ResolveMember method. Have a look here for an example on how to find property getter tokens: Find all property references using reflection. The code can easily adapted to search for any kind of tokens or instructions you are interested in.