Loop in Intel x86 Assembly going on forever

2020-02-15 07:57发布

I'm currently learning Intel x86 Assembly, and I've run into a problem while trying to construct a simple loop, which loops 10 times. It's supposed to stop after the 10 loops, but it keeps going on and on, forever.

This is the code that I am using:

    section .data
    msg     db      "Hello, World!", 0x0a
    len     equ     $-msg

    section .text
    global _start

    _start:
            mov     cx, 10  ; loop counter

            _loop_start:
                    mov     ebx, 0x01
                    mov     ecx, msg
                    mov     edx, len
                    mov     eax, 0x04
                    int     0x80

                    dec     cx
                    cmp     cx, 0
                    jge     _loop_start

            _done:
                    mov     ebx, 0x00
                    mov     eax, 0x01
                    int     0x80

Before attempting to write this code, I looked at this tutorial for doing simple arithmetic.

I compile it like so:

   nasm -f elf64 test.s -o test.o

And link like this:

   ld -s -o test_exec test.o

Thanks in advance, Anickyan

2条回答
再贱就再见
2楼-- · 2020-02-15 08:36

If the "overwriting"-problem is solved and if we are begining with a counter of 10 for decreasing the counter each circuit and if we branch if the value of the counter is greater or equal than 0, then we become a looping of 11 times.

Alternativly we can also use the zeroflag to branch (if the zeroflag is not set):

                dec     cl
                jnz     _loop_start

The "dec" instruction already involve the flag register, so we do not need the "cmp"-instruction, if we want to check if a value was decreasing to zero.

Dirk

查看更多
等我变得足够好
3楼-- · 2020-02-15 08:47

cx is the lower 16 bit portion of ecx. Your code suggest that you may think that your loop will run 10 times (you set cx to 10 before the loop). But then you overwrite the value with the address of msg with mov ecx, msg. So you'll start to count down to 0 from the lower 16 bit of that number. But the decrement doesn't even have an effect since during the next iteration you overwrite the ecx again with the msg's address. And the loop start again. It's an infinite loop. Did you check the software in debugger? That can help a lot.

查看更多
登录 后发表回答