-
Hi everyone, is there any way to get raw bytes of an instruction (byte []), I mean opcode bytes and its operand bytes, from instruction itself or from its method or from module or anyway can be retrieved those data, please provide sample code. thanks. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
It depends on what you need / what your situation is. If the instruction is stored in a method body that exists in an input binary, you can just read out the raw bytes of a method body and carve out the instruction from there: CilMethodBody body = ...;
CilInstruction instruction = ...;
// Get a raw method body code reader.
var bodyReader = body.Address.CreateReader();
var rawBody = CilRawMethodBody.FromReader(ref bodyReader);
var codeReader = rawBody.Code.CreateReader();
// Read raw bytes of single instruction.
byte[] instructionBytes = new byte[instruction.Size];
codeReader.RelativeOffset = (uint) instruction.Offset;
codeReader.ReadBytes(instructionBytes);
// Print
Console.WriteLine($"IL_{instruction.Offset:X4}: /* {Convert.ToHexString(instructionBytes)} */ {instruction.OpCode} {instruction.Operand}"); If the instruction is not part of an existing method body, you will have to (re-)assemble the instructions yourself to get a bytes representation of the instruction, e.g., using CilInstruction instruction = ...;
// Create an assembler
var tempCodeStream = new MemoryStream();
var assembler = new CilAssembler(
new BinaryStreamWriter(tempCodeStream),
new CilOperandBuilder(
new OriginalMetadataTokenProvider(module),
ThrowErrorListener.Instance
)
);
// Assemble the instruction
assembler.WriteInstruction(instruction);
byte[] instructionBytes = tempCodeStream.ToArray();
// Print
Console.WriteLine($"IL_{instruction.Offset:X4}: /* {Convert.ToHexString(instructionBytes)} */ {instruction.OpCode} {instruction.Operand}"); |
Beta Was this translation helpful? Give feedback.
It depends on what you need / what your situation is.
If the instruction is stored in a method body that exists in an input binary, you can just read out the raw bytes of a method body and carve out the instruction from there: