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 GetILAsByteArray
method, 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 OpCodes
structure (MSDN) from System.Reflection.Emit
. If you enumerate over all the fields, you can quite easily build a lookup table for reading of the bytes:
// Iterate over all byte codes to build lookup table
for fld in typeof<OpCodes>.GetFields() do
let code = fld.GetValue(null) :?> OpCode
printfn "%A (%d + %A)" code.Name code.Size code.OperandType
The code.Value
property gives you eithre byte
or int16
value of the code. The code.Size
property tells you whether this is 1 or 2 byte code and OperandType
property 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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With