dev
dev

Reputation: 321

while loop in masm32 loops infinitely

I am new to assembly language. so started writing small programs. I have written a basic loop program to print "*" pyramid. but the program goes into infinite loop. I am pasting the code below. can someone please help? start:

   mov ecx,2
   invoke StdOut, addr startProg

label_1:

   .while ecx > 0

   push ecx
       pop aInt

     .while aInt > 0
       invoke StdOut, addr star
       sub aInt, 1
     .endw

        dec ecx
    .endw

     ;invoke StdOut, addr newline


   jmp out_
out_:
   invoke ExitProcess, 0  

end start

Upvotes: 2

Views: 3903

Answers (3)

Cyclonecode
Cyclonecode

Reputation: 30001

Like @SecurityMatt stated, the reason you get trapped in a infinite loop is because the value of ecx is modified in your call to StdOut.
You can avoid this by preserving your registers using push and then restoring them using pop:

.while ecx > 0
   push ecx
   pop aInt
   ; preserve state of `ecx`
   push ecx
   .while aInt > 0
     invoke StdOut, addr star
     sub aInt, 1
   .endw
   ; restore ecx
   pop ecx
   dec ecx
.endw

You could also use pushad and popad in order to push/pop all general-purpose register values on and off the stack.

; push general-purpose registers values onto stack
pushad
invoke StdOut, addr star
; restore general-purpose registers
popad

Upvotes: 1

SecurityMatt
SecurityMatt

Reputation: 6743

Invoke calls the method via the __stdcall calling convention. Part of that convention is that EAX, ECX and EDX are not preserved over that call. This is why your ECX and EAX registers are not decrementing and causing the loop to stop.

Upvotes: 3

Vlad Krasnov
Vlad Krasnov

Reputation: 1027

You are probably confusing assembly instructions with macros. The .while is not an assembly instruction, it is a macro. Same for all directives that begin with '.'

Upvotes: 0

Related Questions