I can compile instructions to bytecode and even execute them easily but the only function I have found to extract CIL is GetILAsByteArray and, as the name implies, it just returns bytes and not CIL instructions.
So how do you programmatically disassemble CIL on .NET?
Note that I don’t want the result in human-readable form. I want to write metaprograms to manipulate the CIL generated from other programs.
You can get reasonably far just using the byte array from
GetILAsByteArraymethod, but you’ll need to write parsing of the bytes yourself (if you don’t want to rely on 3rd party library).The structure of the array is that there is one or two bytes identifying the instruction followed by operands for the instruction (which is either nothing, some 4 byte token or a 8 byte number).
To get the codes, you can look at the
OpCodesstructure (MSDN) fromSystem.Reflection.Emit. If you enumerate over all the fields, you can quite easily build a lookup table for reading of the bytes:The
code.Valueproperty gives you eithrebyteorint16value of the code. Thecode.Sizeproperty tells you whether this is 1 or 2 byte code andOperandTypeproperty specifies what arguments follow the code (the number of bytes and the meaning is explained on MSDN). I don’t remember how exactly you need to process things like tokens that refer to i.e.MethodInfo, but I guess you’ll be able to figure that out!