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

AssemblyX86

Assembly Problem Overview


I recently stumbled across the following assembly instruction sequence:

rep stos    dword ptr [edi]

Assembly Solutions


Solution 1 - Assembly

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

Solution 2 - Assembly

Empty array: 
char buff[256] = { }; 

 776      1c5:   48 8d 95 e0 fc ff ff    lea    -0x320(%rbp),%rdx
 777      1cc:   b8 00 00 00 00          mov    $0x0,%eax
 778      1d1:   b9 20 00 00 00          mov    $0x20,%ecx
 779      1d6:   48 89 d7                mov    %rdx,%rdi
 780      1d9:   f3 48 ab                **rep stos %rax,%es:(%rdi)**

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCOMerView Question on Stackoverflow
Solution 1 - AssemblyChris Jester-YoungView Answer on Stackoverflow
Solution 2 - AssemblyleesagaciousView Answer on Stackoverflow