How to write _start function to call the main function in C

174 Views Asked by At

By using inline assembly asm volatile, how can I implement _start function in C which can call the main function

int main(int argc, char *argv[], char *envp[])

I tried alot, but it didn't work at all, and I'm a beginner in inline asm.

I tried this program

#include <stdio.h>

int main(int argc, char *argv[], char *envp[])
{
    printf("Hello, World!\n");
    return 0;
}

void _start()
{
    int argc;
    char **argv, **envp;
    int ret = 0;
    asm volatile(
        "mov %%edi, %0\n\t"
        "mov %%esi, %1\n\t"
        "mov %%edx, %2\n\t"
        : "=m"(argc), "=m"(argv), "=m"(envp)
    );
    asm volatile(
        "mov %0, %%edi\n\t"
        "mov %1, %%esi\n\t"
        "mov %2, %%edx\n\t"
        "call _main\n\t"
        "mov %%eax, %%ebx\n\t"
        :
        : "g"(argc), "g"(argv), "g"(envp), "g"(ret)
        : "%edi", "%esi", "%edx", "%ebx"
    );
    asm volatile(
        "mov %0, %%edi\n\t"
        "mov $60, %%eax\n\t"
        "syscall"
        :
        : "g"(ret)
    );
}

It's working on Windows, but not on Linux Ubuntu, so how can I fix that please?

0

There are 0 best solutions below