C标准指出...
...从初始调用到
main
函数的返回等同于调用exit
函数,而主函数返回的值作为其参数。
从我所看到的,这通常是由C运行时支持代码(CRT0.C(实现的 - 通过这样做 - 调用exit
,并带有main
的返回值。
glibc:
result = main (argc, argv, __environ MAIN_AUXVEC_PARAM);
exit (result);
ulysses libc:
exit(main(argc, argv, envp));
但是,当我编写自己的exit
版本时,它会被称为:
#include <stdio.h>
#include <stdlib.h>
void exit( int rc )
{
puts( "ok" );
fflush( stdout );
}
int main()
{
return 0;
}
这不会产生我预期的"确定"输出。显然我在这里缺少什么?
上下文:我正在实施C标准库,只是ISO部分,即无CRT0.C。我希望现有的系统运行时可以调用我自己的exit
实现,因此"我的"清理(例如Flushing and Closing流,使用atexit
等注册的处理功能(将自动从链接到我的库的main
时自动运行。显然不是这样,我只是不明白为什么不明白。
如果我正确理解,则在尝试使用c运行时的某些部分(即称为主函数和退出(时,您正在尝试在C标准库中实现功能。<<<<<<<<<<<<<<<<<</p>
通常执行此操作的代码部分是_start
函数。这通常是用Linux Loader的Elf二进制组的入口点。
此_start
函数在编译器正在使用的C运行时定义,并且已经链接了呼叫的呼叫(地址已修补为呼叫(。它可能简单地将其列入_start
函数。
要使_start
函数调用您的exit
,您要做的就是重新定义_start
本身。然后,您必须确保不使用C运行时的_start
。
我会选择这样的东西 -
// Assuming your have included files that declare the puts and fflush functions and the stdout macro.
int main(int argc, char* argv[]); // This is here just so that there is a declaration before the call
void _start(void) {
char *argv[] = {"executable"}; // There is a way to get the real arguments, but I think you will have to write some assembly for that.
int return_value = main(1, argv);
exit(return_value);
// Control should NEVER reach here, because you cannot return from the _start function
}
void exit(int ret) {
puts("ok");
fflush(stdout); // Assuming your runtime defines these functions and stdout somewhere.
// To simulate an exit, we will just spin infinitely -
while(1);
}
int main(int argc, char* argv[]) {
puts("hello worldn");
return 0;
}
现在您可以编译并将文件链接为 -
gcc test.c -o executable -nostdlib
-nostdlib
告诉链接器不要与具有_start
实现的标准运行时链接。
现在您可以执行可执行文件,它将调用您的"退出"。正如您所期望的那样,然后将永远保持循环。您可以通过按Ctrl C或以其他方式发送Sigkill来杀死它。
附录
只是为了完整的缘故,我还试图写下其余功能的实现。
您首先可以在代码顶部添加以下声明和定义。
#define stdout (1)
int puts(char *s);
long unsigned int strlen(const char *s) {
int len = 0;
while (s[len])
len++;
return len;
}
int fflush(int s) {
}
void exit(int n);
strlen
定义为预期,fflush
是一个no-op,因为我们没有为我们的stdio函数实施缓冲。
现在在单独的文件中。
.text
.globl puts
puts:
movq %rdi, %r12
callq strlen
movq $1, %rdi
movq %r12, %rsi
movq %rax, %rdx
movq $1, %rax
syscall
retq
这是puts
的最简单实现,该实现称为strlen函数,然后是Write Syscall。
您现在可以编译并将所有内容链接为 -
gcc test.c put.s -o executable -nostdlib
当我运行生产的executable
时,我将获得以下输出 -
hello world
ok
然后这个过程挂起。我可以按CTRL c。