Search code examples
assemblyx86-64att

x64 Assembly GNU syntax, how the loop returns


This is a program in Assembler x64 GNU syntax

    .global main
    .text
main: 
    xor  %rax, %rax
    mov  %rax, %rbx

.L1:
    add  $1, %rbx
    add  %rbx, %rax
    cmp  $10, %rbx
    jne  .L1
    ret

I did the loop manually and I found out that when the loop terminates hit the return function (ret), the rbx = 10 and rax = 45, but I do not understand how they go back to main function, and what happens when they go back there?


Solution

  • The ret instruction doesn't return to the main but it returns from the main to start the termination of your program. The loop you written isn't a function, you are just jumping back to an earlier line of your code and you don't need to terminate that with a ret instruction. Though you need that ret to terminate your program.

    To answer the question about where your values go, they don't go anywhere. If we simplify things a little bit and don't consider context switches, your values remain physically stored in the registers until you or some piece of other code in case of a function call reuses them. To find out what to do with registers at function calls and how to pass arguments to functions look into calling conventions.