Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assembly: REP MOVS mechanism

Tags:

x86

assembly

Looking at the following assembly code:

MOV ESI, DWORD PTR [EBP + C]
MOV ECX, EDI
MOV EAX, EAX
SHR ECX, 2
LEA EDI, DWORD PTR[EBX + 18]
REP MOVS DWORD PTR ES:[EDI], DWORD PTR [ESI]
MOV ECX, EAX
AND ECX, 3
REP MOVS BYTE PTR ES:[EDI], BYTE PTR[ESI]

The book I got the code excerpt from explains the first REP MOVS as copying over 4-byte chunks, with the second REP MOVS copying the remaining 2-byte chunk, if it exists.

How do the REP MOVS instructions operate? According to MSDN, "The instruction can be prefixed by REP to repeat the operation the number of times specified by the ecx register." Wouldn't that just repeat the same operation over and over again?

like image 772
Abundance Avatar asked Jan 06 '15 18:01

Abundance


People also ask

What does MOVS do in assembly?

The MOVS instruction is used to copy a data item (byte, word or doubleword) from the source string to the destination string. The source string is pointed by DS:SI and the destination string is pointed by ES:DI.

What is Rep Movsb in assembly language?

In short, rep repeats the following string operation ecx times. movs copies data from ds:esi to es:edi and increments or decrements the pointers based on the setting of the direction flag. As such, repeating it will move a range of memory to somewhere else.


1 Answers

For questions about particular instructions always consult the instruction set reference.

In this case, you will need to look up rep and movs. In short, rep repeats the following string operation ecx times. movs copies data from ds:esi to es:edi and increments or decrements the pointers based on the setting of the direction flag. As such, repeating it will move a range of memory to somewhere else.

PS: usually the operation size is encoded as an instruction suffix, so people use movsb and movsd to indicate byte or dword operation. Some assemblers however allow specifying the size as in your example, by byte ptr or dword ptr. Also, the operands are implicit in the instruction, and you can not modify them.

like image 200
Jester Avatar answered Nov 15 '22 07:11

Jester