Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the "rep stos" x86 assembly instruction sequence do?

Tags:

x86

assembly

I recently stumbled across the following assembly instruction sequence:

rep stos    dword ptr [edi] 
like image 939
COMer Avatar asked Sep 29 '10 05:09

COMer


People also ask

What is Rep x86 assembly?

Use the rep (repeat while equal), repnz (repeat while nonzero) or repz (repeat while zero) prefixes in conjunction with string operations. Each prefix causes the associated string instruction to repeat until the count register (CX) or the zero flag (ZF) matches a tested condition.

What does Stosd do in assembly?

The STOS instruction copies the data item from AL (for bytes - STOSB), AX (for words - STOSW) or EAX (for doublewords - STOSD) to the destination string, pointed to by ES:DI in memory.


1 Answers

For ecx repetitions, stores the contents of eax into where edi points to, incrementing or decrementing edi (depending on the direction flag) by 4 bytes each time. Normally, this is used for a memset-type operation.

Usually, that instruction is simply written rep stosd. Experienced assembly coders know all the details mentioned above just by seeing that. :-)


ETA for completeness (thanks PhiS): Each iteration, ecx is decremented by 1, and the loop stops when it reaches zero. For stos, the only thing you will observe is that ecx is cleared at the end. But, for scas or the like, where the repz/repnz prefixes are used, ecx can be greater than zero if the operation stopped before exhausting ecx bytes/words/whatevers.

Before you ask, scas is used for implementing strchr-type operations. :-P

like image 76
Chris Jester-Young Avatar answered Oct 12 '22 21:10

Chris Jester-Young