Archived

This topic is now archived and is closed to further replies.

barazor

interfacing NASM with GCC

Recommended Posts

seeing that gcc has that nasty at&t syntax, i've heard that you can write functions with nasm, then declare them as extern in your c source code, then link the object. however, i dont really have a clue how to do this, it sounds a bit complicated. id just appreciate if somebody posted some instructions on how to write the function in asm, then call it from C btw i know a bit of assembler, i just dont know the steps to doing this task... [edited by - barazor on May 4, 2002 12:40:05 PM]

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
Here''s a little example. (NOT TESTED)
Sorry for the lack of useful comments/explanations but I don''t have much time right now
but it should get you started until I come back with full explanations.

tip: learn/understand the C Calling Convention

asm_malloc.asm

  
;****************************************;
; asm_malloc.asm ;
; by PeaKe ;
; Just an example of mixing ASM with C. ;
; ->NOT TESTED!<- ;
;****************************************;

%define LINUX ; if compiled under GNU/Linux

%define arg_1 [EBP + 8] ; parameter position
%define arg_2 [EBP + 12] ; on the stack
%define arg_3 [EBP + 16] ; (double word boundry)

; C Callable:
; void *asm_malloc(int mem);
;
; mem - how many memory to allocate
; return adress of that allocated memory in EAX

segment .text

%ifdef LINUX
global asm_malloc ; no underscore under GNU/Linux
asm_malloc:
%else
global _asm_malloc
_asm_malloc:
%endif

push ebp ; ENTER POINT
mov ebp , esp ; respect C calling convention

push dword arg_1 ; arg_1 == mem
call _malloc ; malloc(mem)
add esp , 4 ; remove param from the stack

mov esp , ebp ; EXIT POINT
pop ebp ; respect C calling convention
ret ; allocated memory adress in EAX


And now our little C program that calls asm_malloc

driver.c

  
#include <stdlib.h>

extern void *asm_malloc(int mem);

int main(int argc, char *argc[])
{
int *ptr

ptr = asm_malloc( atoi(argv[1] );

free(ptr);

return(0);
}



now to compile:

Under Linux:
nasm -f elf asm_malloc.asm
gcc -o exasm driver.c asm_malloc.o

Under DJGPP
nasm -f coff asm_malloc.asm
gcc -o exasm.exe driver.c asm_malloc.o

For a list of valid output formats, use nasm -hf.

Share this post


Link to post
Share on other sites