namespace X86Disassembler.X86.Handlers; /// /// Handler for TEST r/m32, r32 instruction (0x85) /// public class TestRegMemHandler : InstructionHandler { // ModR/M decoder private readonly ModRMDecoder _modRMDecoder; /// /// Initializes a new instance of the TestRegMemHandler class /// /// The buffer containing the code to decode /// The instruction decoder that owns this handler /// The length of the buffer public TestRegMemHandler(byte[] codeBuffer, InstructionDecoder decoder, int length) : base(codeBuffer, decoder, length) { _modRMDecoder = new ModRMDecoder(codeBuffer, decoder, length); } /// /// Checks if this handler can decode the given opcode /// /// The opcode to check /// True if this handler can decode the opcode public override bool CanHandle(byte opcode) { return opcode == 0x85; } /// /// Decodes a TEST r/m32, r32 instruction /// /// The opcode of the instruction /// The instruction object to populate /// True if the instruction was successfully decoded public override bool Decode(byte opcode, Instruction instruction) { // Set the mnemonic instruction.Mnemonic = "test"; int position = Decoder.GetPosition(); if (position >= Length) { return false; } // Read the ModR/M byte byte modRM = CodeBuffer[position++]; Decoder.SetPosition(position); // Extract the fields from the ModR/M byte byte mod = (byte)((modRM & 0xC0) >> 6); byte reg = (byte)((modRM & 0x38) >> 3); byte rm = (byte)(modRM & 0x07); // For direct register addressing (mod == 3), the r/m field specifies a register if (mod == 3) { // Get the register names string rmReg = GetRegister32(rm); string regReg = GetRegister32(reg); // Set the operands (TEST r/m32, r32) // In x86 assembly, the TEST instruction has the operand order r/m32, r32 // According to Ghidra and standard x86 assembly convention, it should be TEST ECX,EAX // where ECX is the r/m operand and EAX is the reg operand instruction.Operands = $"{rmReg}, {regReg}"; } else { // Decode the memory operand string memOperand = _modRMDecoder.DecodeModRM(mod, rm, false); // Get the register name string regReg = GetRegister32(reg); // Set the operands (TEST r/m32, r32) instruction.Operands = $"{memOperand}, {regReg}"; } return true; } /// /// Gets the 32-bit register name for the given register index /// /// The register index /// The register name private static string GetRegister32(byte reg) { string[] registerNames = { "eax", "ecx", "edx", "ebx", "esp", "ebp", "esi", "edi" }; return registerNames[reg & 0x07]; } }