1

There is this code for reversing a string

.386
.model flat,stdcall
.stack 4096
ExitProcess proto,dwExitCode:dword

.data
source  BYTE  "This is the source string",0
target  BYTE  SIZEOF source DUP('#')
 .code
 main PROC
; Point ESI to the last character in the source string:
    mov  esi,OFFSET target - 2

; Point EDI to the beginning of the target string:
; We do not copy the null terminator byte.

mov  edi,OFFSET target
mov  ecx,SIZEOF source-1        ; loop counter

L1: mov  al,[esi]                   ; get a character from source
    mov  [edi],al                   ; store it in the target
    dec  esi                        ; move to next character
    inc  edi
    loop L1                         ; repeat for entire string

    mov BYTE PTR [edi],0            ; add a null byte to the target

    invoke ExitProcess,0
main endp
end main

Can someone explain to me what this all means? I watch the registers move and it seems that the loop ends when ECX equals 0. Why is this? Care to explain each section of code?

Edit 1: I see that ecx is defined at "mov ecx, SIZEOF source-1" which takes away 1 each time.

Mooing Duck
  • 64,318
  • 19
  • 100
  • 158
jake craigslist
  • 303
  • 3
  • 12

2 Answers2

5

As you can read about here the loop instruction decrements ECX, jumps if it's not 0 and continues if it's 0.

edi is used as a pointer to the end of the string. ecx is set to the length of the string

This line is sneaky: mov esi,OFFSET target - 2

The loop is the equivalent of:

a = 0;
b = source.length - 1;
for (int i = source.length; i >= 0; i++) {
   target[a] = source[b];
   a++;
   b--;
}
Community
  • 1
  • 1
Eric Hughes
  • 831
  • 6
  • 19
2

LOOP uses ECX as a loop counter, it decreases it and then jumps to the label if it is not zero.

dhcarmona
  • 402
  • 2
  • 10
  • 29