问题
How to change the entry point of a C program compiled with gcc ?
Just like in the following code
#include<stdio.h>
int entry() //entry is the entry point instead of main
{
return 0;
}
回答1:
It's a linker setting:
-Wl,-eentry
the -Wl,... thing passes arguments to the linker, and the linker takes a -e argument to set the entry function
回答2:
You can modify your source code as:
#include<stdio.h>
const char my_interp[] __attribute__((section(".interp"))) = "/lib/ld-linux.so.2";
int entry() //entry is the entry point instead of main
{
exit(0);
}
The ".interp" section will let your program able to call external shared library. The exit call will make your entry function to exit program instead of return.
Then build the program as a shared library which is executable:
$ gcc -shared -fPIC -e entry test_main.c -o test_main.so
$ ./test_main
回答3:
If you are on a system that provides GNU Binutils (like Linux),
you can use the objcopy command
to make an arbitrary function the new entry point.
Suppose a file called program.c containing the entry function:
$ cat > program.c
#include <stdio.h>
int entry()
{
return 0;
}
^D
You first compile it using
-cto generate a relocatable object file:$ gcc -c program.c -o program.oThen you redefine
entryto bemain:$ objcopy --redefine-sym entry=main program.oNow use gcc to compile the new object file:
$ gcc program.o -o program
NOTE: If your program already has a function called main, before step 2, you can perform a separate objcopy invocation:
objcopy --redefine-sym oldmain=main program.o
回答4:
Minimal runnable example and notes on other answers
main.c
#include <stdio.h>
#include <stdlib.h>
int mymain(void) {
puts("hello");
exit(0);
}
compile and run:
gcc -nostartfiles -Wl,-eentry=mymain -o main.out main.c
./main.out 1 2 3
The notes:
without
-nostartfiles, the link fails with:/usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu/Scrt1.o: In function `_start': (.text+0x20): undefined reference to `main' collect2: error: ld returned 1 exit statuspresumably because the glibc setup code that runs before main in
_startnormally callsmain.command line arguments are not setup for you, presumably because they would be setup by the glibc code that runs before main, so trying to use them prints undefined values. I haven't found a method that works for them.
I get a warning
/usr/bin/ld: warning: cannot find entry symbol entry=mymain; defaulting to 0000000000000390, not sure if is serious or how to get rid of it
Tested in Ubuntu 18.04.
来源:https://stackoverflow.com/questions/7494244/how-to-change-entry-point-of-c-program-with-gcc