Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Infinite loop when using cmpq and je

I'm decrementing RAX on each iteration. If RAX is zero, the program should change flow.

# AT&T syntax
start_calc_factorial:
  decq %rax
  cmpq $0, %rax
  je quit_calc_factorial
  mulq %rcx
  jmp start_calc_factorial

However, the program never terminates. The debugger tells me that RAX has a value of 0xa0257c7238581842 (it probably underflowed, but it shouldn't because of the je instruction). The initial value of RAX is 7.

What could be the problem?

like image 543
Dutchman Avatar asked Sep 10 '26 00:09

Dutchman


2 Answers

I believe the result of the multiplication is stored in the RAX register, so that would definitely mess up the looping.

like image 108
Mark Wilkins Avatar answered Sep 16 '26 18:09

Mark Wilkins


The problem is that you use the same register, rax, as both, the argument and product. Your code is equivalent to this C code:

while (1)
{
  rax = rax - 1;
  if (rax == 0) break;
  rax = rax * rcx;
}

It can loop for a long time if not forever.

What you probably want is this:

while (1)
{
  rcx = rcx - 1;
  if (rcx == 0) break;
  rax = rax * rcx;
}
like image 33
Alexey Frunze Avatar answered Sep 16 '26 18:09

Alexey Frunze



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!