1
votes

I'm trying to write a function that will NOP an assembly instruction. Currently I have it NOPing the instruction, but I have to manually enter the instruction size...

It would be nice if I could just feed it the address, and by some magic it's able to calculate the total bytes for that instruction...

For example... In the following OllyDBG assembly line... The instruction is of size 6 (I've bolded the instruction bytes).

02235FF3 3B86 B8020000 CMP EAX,DWORD PTR DS:[ESI+2B8]

This is the function I have now...

void NOP(
    DWORD_PTR FromAddress,
    const int size)
{
    for (int i = 0; i < size; i++)
    {
        WriteProcessMemory(GetCurrentProcess(), (LPVOID)(FromAddress + i), "\x90", size, NULL);
    }
}

I imagine this would transform into something like this....

void NOP(
    DWORD_PTR Address)
{
    int TotalBytes = MagicFunctionToGetInstructionByteSizeFromAddress(Address);

    for (int i = 0; i < TotalBytes; i++)
    {
        WriteProcessMemory(GetCurrentProcess(), (LPVOID)(FromAddress + i), "\x90", size, NULL);
    }
}
1
There is no "magic" it depends on the instruction set architecture. Read about it, some of them have very uniform instruction set.Jean-Baptiste Yunès
Unfortunately x86 is very non-uniform with the possibility of having 1-15 bytes per instruction.Bo Persson

1 Answers

3
votes

Sure. But it's not simple. You must build a partial disassembler. Use an x86 instruction reference. Parse the instruction into parts: optional prefix bytes, opcode, mod/R/M, scale/index/base. This is enough information to decide how long the instruction must be.

There are a few disassembler libraries that you can probably coax to do this for you. See for example Udis86 and its documentation on the function ud_insn_len. But there are several other library options.