简体   繁体   中英

Is there any way to get the total bytes of an instruction at an address in C++?

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);
    }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM