C语言 如何使用gcc更改C程序的入口点?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7494244/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 09:41:17  来源:igfitidea点击:

How to change entry point of C program with gcc?

cmainentry-point

提问by asitm9

How to change the entry point of a C program compiled with gcc ?
Just like in the following code

如何更改用 gcc 编译的 C 程序的入口点?
就像在下面的代码中一样

#include<stdio.h>
int entry()  //entry is the entry point instead of main
 {
   return 0;
 }

回答by Foo Bah

It's a linker setting:

这是一个链接器设置:

-Wl,-eentry

the -Wl,...thing passes arguments to the linker, and the linker takes a -eargument to set the entry function

-Wl,...事情参数传递给链接器和链接器将一个-e参数设置项功能

回答by Sam Liao

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.

“.interp”部分将使您的程序能够调用外部共享库。退出调用将使您的入口函数退出程序而不是返回。

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

回答by Rudy Matela

If you are on a system that provides GNU Binutils(like Linux), you can use the objcopycommand to make an arbitrary function the new entry point.

如果您使用的系统提供GNU Binutils(如 Linux),您可以使用该objcopy命令将任意函数设为新的入口点。

Suppose a file called program.ccontaining the entryfunction:

假设一个名为的文件program.c包含该entry函数:

$ cat > program.c
#include <stdio.h>
int entry()
{
    return 0;
}
^D
  1. You first compile it using -cto generate a relocatable object file:

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

    $ objcopy --redefine-sym entry=main program.o
    
  3. Now use gcc to compile the new object file:

    $ gcc program.o -o program
    
  1. 您首先使用它来编译它-c以生成一个可重定位的目标文件:

    $ gcc -c program.c -o program.o
    
  2. 然后你重新定义entrymain

    $ objcopy --redefine-sym entry=main program.o
    
  3. 现在使用 gcc 编译新的目标文件:

    $ gcc program.o -o program
    

NOTE:If your program already has a function called main, before step 2, you can perform a separate objcopyinvocation:

注意:如果您的程序已经有一个名为 的函数main,则在第 2 步之前,您可以执行单独的objcopy调用:

objcopy --redefine-sym oldmain=main program.o