Page 1 of 1

Calling extern function in asm

Posted: Wed Jul 10, 2013 9:16 am
by goku420
In an attempt to wrap my mind around how I could execute asm instructions from my kernel, I did a test. Here's my code:

Code: Select all

extern puts

global test

test:
	mov ebx,msg
	mov eax,puts
	call eax
	ret
	
SECTION .data
	msg     db  'Hello, world!',0xa  
Then I put the call to test in my main function. However when I run it, I get this:

Image

The 'default' and 'initializing' strings are supposed to be there.

I'm assuming that the 'mov ebx,msg' isn't really doing anything, but I don't know how I would pass the argument to the caller. What should I do?

Re: Calling extern function in asm

Posted: Wed Jul 10, 2013 10:19 am
by tiger717
1. Just call puts by

Code: Select all

call puts
- no need to change any registers.

2. In x86 32bit programming, the cdecl calling convention (or however you want to call it) is used which means
passing arguments over the stack (last one first = right to left), you (the caller) are responsible for saving eax, ecx and edx on the stack and you get your return value over eax. You also have to clean the stack, i.e. remove the arguments you have pushed on it.

Example:

Code: Select all

; int some_function(char* a, int b);
extern some_function

test:
    mov eax, some_important_value   ; save some important value in eax
    push eax     ; secure eax for ourselves - no need if we don't care about eax
    push second_argument    ; you can actually pass a variable, no need to lea first
    push first_argument
    call some_function    ; call the function
    mov edx, eax   ; somehow use the return value if you need it
    add esp, 8  ; remove our arguments from the stack
    pop eax   ; and get eax back
    ret
PS: Sorry for the badly aligned comments.

Note that this only applies to x86 (32 bits). In AMD64 (or however you want to call it), the AMD64 ABI is used which is really different - if you want to support Long Mode one day.

Re: Calling extern function in asm

Posted: Wed Jul 10, 2013 11:16 am
by Antti
@tiger717: If using cdecl, callee does not clean the stack.

Re: Calling extern function in asm

Posted: Wed Jul 10, 2013 11:45 am
by goku420
Thanks.

Code: Select all

test:
	push msg
	call puts
	add esp, 4 ; clean stack, 4 for 32 bit
	ret
Seems to do the trick.

Re: Calling extern function in asm

Posted: Wed Jul 10, 2013 1:38 pm
by tiger717
@Antii and remyabel: Err, yes. Sorry, haven't really coded anything using cdecl. Former message edited.