jackson blackson
jackson blackson

Reputation: 311

Assembly x86 MASM loop analysis

The following is a piece of loop code I am trying analyze and understand how loops work:

;the ecx register is the loop counter

  mov ecx,6
  mov edx, offset space 
myloop:
  mov eax,ecx
  dec eax
  call writedec 
  call writestring 
loop myloop 
  call crlf 

  mov ecx,6
  mov edx, offset space 
myloop2:
  mov eax,6
  sub eax, ecx 
  call writedec
  call writestring 
loop myloop2

My questions are:

  1. What does offset space mean?
  2. What does mov edx, offset space mean?
  3. I don't understand how the offset space is the source?
  4. How do you move register ecx into register eax?
  5. Why is the offset space the source and register edx the destination?

Thank you so much for all your help.

Upvotes: 3

Views: 498

Answers (1)

Alexander van Oostenrijk
Alexander van Oostenrijk

Reputation: 4764

The offset operator returns the offset of a memory location relative to the beginning of the segment (DS in the case of MOV) to which the location belongs (see here). space is likely a variable that's defined somewhere earlier in the code, so that offset space would return the number of bytes relative to the beginning of the segment (usually the DS data segment) to that variable.

In other words, mov edx, offset space will copy a pointer to the space variable (of type DWORD, 32-bit) to be placed in the edx register. The reason it's placed in edx must be found in the writedec and writestring routines.

As for the loop you're asking about, that's where the ecx register comes in. The loop instruction will cause the code pointer to move to its destination as long as ecx is not zero, decreasing it by 1 immediately before checking it. The loop value is also used by your code somewhere, which is why it's copied to eax so that other code will not change the value of ecx and mess up your loop.

Upvotes: 1

Related Questions