3

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.

Mohit Deshpande
  • 53,877
  • 76
  • 193
  • 251

1 Answers1

14

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.

jwwishart
  • 2,865
  • 2
  • 23
  • 26
  • 3
    @jwwishart You have now 1337 reputation. Would be a shame if someone voted you up, woudln't it? ^^ – Stefan Falk Sep 11 '14 at 19:37
  • How does this work? Specifically the line `push dword [ebp+8]`. If I understand correctly this pushes the value at the memory address of ebp+8 onto the stack? And the width is 32 bits. I think this has something to do with an argument to the printf function - but can anyone explain it in more detail than that? – FreelanceConsultant May 22 '21 at 22:26
  • @FreelanceConsultant In 32 bits, the arguments are pushed to the stack. In this case it's pushing the first argument for `printf`. In this case, the value at `ebp+8` will be the first argument passed to `myFunc` (pushed ebp + return address on the stack = 8 bytes). The dword part is used to indicate that we are pushing 4 bytes. – trxgnyp1 Aug 29 '23 at 15:29