I'm taking my first steps into assembly x86 on Windows.
My question is why does ecx decrease with each loop, and why does the program know when to break the loop?
I'm posting the code, debugger output and some comments
Code:
.386
.model flat
.data
intArray DWORD 1h,2h,3h,4h;
.code
start proc
mov edi,OFFSET intArray
mov ecx,LENGTHOF intArray
mov eax,0
LP:
add eax,[edi]
add edi,TYPE intArray
loop LP
ret
start endp
end
In the debugger I can see that with each loop the value of ecx decreases by one:
LP 0:
ecx = 4
LP 1:
ecx = 3
LP 2:
ecx = 2
LP 3:
ecx = 1
LP 4:
ecx = 0
At the begining mov ecx,LENGTHOF intArray it's moving 4 to ecx.
According to the docs
LENGTHOF
Returns the number of data objects in variable.
- https://learn.microsoft.com/en-us/cpp/assembler/masm/operator-lengthof?view=msvc-170
it should simply move value
4intoecx, there is no information about tracking theintArrayand updating it in runtime, so why it is decreasing?
If I understand the code correctly, it should work like this:
#include <iostream>
using namespace std;
int main()
{
int intArray[4] = { 1, 2, 3, 4 };
int *edi = intArray;
int ecx = sizeof(intArray) / sizeof(int);
int eax = 0;
for(int i = 0; i < 4; i++) {
eax += *edi;
ecx -= 1;
edi = (int*)(((intptr_t)edi) + sizeof(int));
}
return 0;
}
but in assembly language the for loop condition and ecx decrementation are missing (I don't know where to look for it).
Is it hidden in flags?
Maybe someone could recommend a source that explains this problem?
Thank you!
Registers output
- stopped at the line
add edi,TYPE intArray
EAX = 00000001 EBX = 01028000 ECX = 00000004 EDX = 00A71005 ESI = 00A71005 EDI = 00A74000 EIP = 00A71021 ESP = 012FFDAC EBP = 012FFDB8 EFL = 00000202
OV = 0 UP = 0 EI = 1 PL = 0 ZR = 0 AC = 0 PE = 0 CY = 0
- stopped at the line
add edi,TYPE intArray
EAX = 00000003 EBX = 01028000 ECX = 00000003 EDX = 00A71005 ESI = 00A71005 EDI = 00A74004 EIP = 00A71021 ESP = 012FFDAC EBP = 012FFDB8 EFL = 00000206
OV = 0 UP = 0 EI = 1 PL = 0 ZR = 0 AC = 0 PE = 1 CY = 0
- stopped at the line
add edi,TYPE intArray
EAX = 00000006 EBX = 01028000 ECX = 00000002 EDX = 00A71005 ESI = 00A71005 EDI = 00A74008 EIP = 00A71021 ESP = 012FFDAC EBP = 012FFDB8 EFL = 00000206
OV = 0 UP = 0 EI = 1 PL = 0 ZR = 0 AC = 0 PE = 1 CY = 0
- stopped at the line
add edi,TYPE intArray
EAX = 0000000A EBX = 01028000 ECX = 00000001 EDX = 00A71005 ESI = 00A71005 EDI = 00A7400C EIP = 00A71021 ESP = 012FFDAC EBP = 012FFDB8 EFL = 00000206
OV = 0 UP = 0 EI = 1 PL = 0 ZR = 0 AC = 0 PE = 1 CY = 0
- stopped at the line
ret
EAX = 0000000A EBX = 01028000 ECX = 00000000 EDX = 00A71005 ESI = 00A71005 EDI = 00A74010 EIP = 00A71026 ESP = 012FFDAC EBP = 012FFDB8 EFL = 00000212
OV = 0 UP = 0 EI = 1 PL = 0 ZR = 0 AC = 1 PE = 0 CY = 0