Search code examples
assemblyx86subroutine

Return value from a subroutine in assembly


I'm writing a simple program that calls a subroutine and expects a value back. so far I have:

%include "asm_io.inc"
SECTION .data
SECTION .bss
SECTION .text
    global asm_main
asm_main: 
enter 0,0
pusha 
mov ebx, dword [ebp+12]
mov eax, dword [ebx+4]
push eax
call maxLyn
push eax        ; contains value 4
call print_int
popa
leave 
ret

maxLyn:
enter 0,0
pusha
mov ebx, dword[ebp+12]
mov eax, [ebx+4]
add eax, dword 2
push eax
ret

So when I run code lynarr abc 2, I'm expecting a value of 4 to be displayed. But it's not showing any results. any ideas would be really helpful!


Solution

    • Since you're calling your program with "lynarr abc 2" to get a pointer to the 2nd commandline argument you need to use mov ebx, dword [ebp+12] mov eax, dword [ebx+8]

    • Your call to maxLyn has only 1 argument. It can be found at [EBP+8]. You wrote [EBP+12].

    • You can't use push before the return. Use leave

    • Don't use pusha here. Just push/pop EBX.

    • Why do you use print_int when AL/EAX contains a character "4"

    maxLyn becomes:

    enter 0,0
    push  ebx
    mov   ebx, dword [ebp+8]
    movzx eax, byte [ebx]   ;Character "2"
    add   eax, dword 2
    pop   ebx
    leave
    ret