Search code examples
assemblynasmsubroutine

How subroutine gets executed without being called?


I'm very new to assembly (x86_64) and came across to a tutorial who provides a simple program to print strings with non-defined lengths. The program is as follows:

section .data
        text db "Hello, World!",10,0

section .text
        global _start

_start:
    mov rax, text
    call _print

    mov rax, 60
    mov rdi, 0
    syscall

_print:
        push rax
        mov rbx, 0

_printLoop:
        inc rax
        inc rbx
        mov cl, [rax]
        cmp cl, 0
        jne _printLoop

        mov rax, 1
        mov rdi, 1
        pop rsi
        mov rdx, rbx
        syscall

        ret

I understood the logic of it except one thing, how _printLoop subroutine is getting executed while it was not being called at all? Is it like... falling through because _print has no ret statement? Aren't labels encapsulations? Thanks in advance for any explanation!


Solution

  • As @ped7g has pointed out , the reason the routine is executed is because it falls through from the print routine.

    In assembly, the call instruction saves the return address to memory (on the stack) and doesn't pop it (i.e return to said point) until it encounters a ret statement. Execution always continues on to the next instruction unless there's some kind of jump (call/ret/jmp), regardless of labels.

    As for the labels, they are simply "nicknames" for certain memory locations to make it easier for programmers to write assembly code. Instead of memorizing a hex address and jumping to it, you can just use the label to reference it. That is their only function; this connection (between hex address and label) is done by the assembler (and the linker for labels outside the current file, or for absolute instead of relative references).