Search code examples
functionassemblyparametersx86nasm

Can't pass parameters to function in assembly x86


I'm trying to pass a string and it's length to the registers ecx and edx through the stack, but i'm getting a segmentation fault:

global main

section .data
        var db "this is the message",0
        varlen equ $- var

section .text

print:
        mov  eax, 4
        mov  ebx, 1
        mov  ecx, [ebp + 4]
        mov  edx, [ebp + 8]
        int 0x80

        ret

main:
        push varlen
        push var
        call print

        mov  eax, 1
        mov  ebx, 0
        int 0x80

Solution

  • If you want, your function to have prologue and epilogue, do the following:

    print:
        push ebp
        mov  ebp, esp
        mov  eax, 4
        mov  ebx, 1
        mov  ecx, [ebp + 8]
        mov  edx, [ebp + 12]
        int  0x80
        mov  esp, ebp
        pop  ebp
        ret
    

    otherwise:

    print:
        mov  eax, 4
        mov  ebx, 1
        mov  ecx, [esp + 4]
        mov  edx, [esp + 8]
        int  0x80
        ret
    

    and in your main:

    main:
        push varlen
        push var
        call print
        add  esp, 8
        mov  eax, 1
        xor  ebx, ebx
        int 0x80