How to change entry point of C program with gcc?

2019-01-05 01:08发布

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;
 }

3条回答
爷、活的狠高调
2楼-- · 2019-01-05 01:39

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

查看更多
混吃等死
3楼-- · 2019-01-05 01:41

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
  1. You first compile it using -c to generate a relocatable object file:

    $ gcc -c program.c -o program.o
    
  2. Then you redefine entry to be main:

    $ objcopy --redefine-sym entry=main program.o
    
  3. Now 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
查看更多
【Aperson】
4楼-- · 2019-01-05 01:58

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
查看更多
登录 后发表回答