问题
How can I pass an argument from a C main function to an assembly function? I know that my custom function has to look something like:
void function(char *somedata) __attribute__((cdecl));
Now how would I use somedata
in an assembly file. My operation system is Linux Ubuntu and my processor is x86.
回答1:
I'm a bit of a noob at this but hopefully this example will get you on your way. I've tested it and it works, the only issue you might have is software not being available. I'm using nasm for assembly.
main.c
extern void myFunc(char * somedata);
void main(){
myFunc("Hello World");
}
myFunc.asm
section .text
global myFunc
extern printf
myFunc:
push ebp
mov ebp, esp
push dword [ebp+8]
call printf
mov esp, ebp
pop ebp
ret
COMPILE
nasm -f elf myFunc.asm
gcc main.c myFunc.o -o main
Notes:
You need to install nasm (assembler) (ubuntu it is: sudo apt-get install nasm)
What basically happens in the c code calls the myFunc with a message. In myFunc.asm we get the address of the first character of the string (which is in [ebp+8] see here for information (http://www.nasm.us/xdoc/2.09.04/html/nasmdoc9.html see 9.1.2 which describes c calling conventions somewhat.) and we pass it to the printf function (by pushing it onto the stack). printf is in the c standard library which gcc will automatically link into our code by default unless we say not to.
We have to export myFunc in the assembly file and declare myFunc as an extrnal function in the main.c file. In myFunc.asm we are also importing the printf function from stdlib so that we can output the message as simply as possible.
Hope this helps somewhat.
来源:https://stackoverflow.com/questions/4330604/pass-an-argument-from-c-to-assembly