Assembly How to convert REP STOS to C code

SSpoke picture SSpoke · Oct 14, 2011 · Viewed 8.3k times · Source

I been debugging REP STOS DWORD PTR ES:[EDI] for a while now

From my conclusion it always uses

ECX as counter. EAX as the value that will be copied over EDI and then appended ECX times so after putting in the pointed dump of EDI

it seems to overwrite the pointed data at EDI with what's it seems it always only uses ECX as a counter, while changing EDI by 4 bytes. it stops working when counter hits 0

So I came up with this kind of code

while(regs.d.ecx != 0)
{
    *(unsigned int *)(regs.d.edi) = regs.d.eax;
    regs.d.edi += 4;
    regs.d.ecx--;
}

Seems to work.. but i'm concerned since I just did this by luck and guess work. Is it solid? like will it always be ECX as counter, EAX as data, and it always copies 4 bytes never less?

Answer

caf picture caf · Oct 14, 2011

You are almost correct. The only difference is that the direction flag (DF) controls whether 4 is added or subtracted from EDI (and it actually is offset from the ES segment base, but you probably don't care about that):

for (; regs.d.ecx != 0; regs.d.ecx--)
{
    *(unsigned int *)(regs.d.edi) = regs.d.eax;
    regs.d.edi += regs.eflags.df ? -4 : 4;
}

Note that the for (; regs.d.ecx != 0; regs.d.ecx--) { } is the action of the REP prefix, and the body of the loop is the action of STOS DWORD....

Since you are asking a lot of these questions, I think you will find the Intel 64 and IA-32 Architectures Software Developer’s Manual, Volumes 2A and 2B to be useful. These contain descriptions of each instruction and prefix, including pseudo-code descriptions.