1

I am looking at some assembly code and can't get my head around it. The code below is shown in IDA. My question revolves on what happens in the loop.

Let me explain what I exactly don't understand in the loop: Above the little loop eax is set to be FFFFFFFFh, which is basically "1" in all the 32 bits in eax(?). In the little loop eax is incremented. But eax is at max value? What happens when I increment eax? Will it go back to 0?

enter image description here

2
  • 2
    "Will it go back to 0?" Yes – Paweł Łukasik Apr 8 '20 at 15:55
  • That answered my question. Thx. – Mr Krisey Apr 8 '20 at 19:46
3

As commented, incrementing a maximum value indeed wraps back to 0. However, I’d like to explain a little about why the code looks like this. The original source probably looked similar to:

int pos = 0;
while (buf[pos]==0) pos++;

Now, a naive/literal translation to assembly would have the check and conditional jump out of the loop at the start and an unconditional jump backwards at the end. However, by converting it into a do-while loop you can get rid of the unconditional jump and have only the conditional one at the end:

int pos = -1;
do
{
  pos++;
} while (buf[pos]==0);

While a minor optimization, it can improve branch prediction and over a bug binary result in substantial performance improvements. This is most likely why you see the initial value of -1 which is represented as 0FFFFFFFFh.

1

inc does not set carry flag (I mis commented earlier as overflow flag)

add eax, 1 will set the carry flag too

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.