|
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. |
Answered by
Washi1337
Dec 1, 2024
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}"); |
0 replies
Answer selected by
dashne
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to 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: