gpt4 book ai didi

linux - 是程序还是操作系统负责设置栈

转载 作者:IT王子 更新时间:2023-10-29 00:57:13 25 4
gpt4 key购买 nike

提出这个问题是因为作者正在构建一个编译器(src -> asm)并且正在编写生成汇编代码的代码。

当程序在基于 Linux(实际上是任何操作系统)的操作系统上执行时,首先发生的事情之一是设置堆栈并为 SP 寄存器分配堆栈开头的内存地址。

我很好奇执行上述操作的责任是程序还是操作系统本身。如果责任在于程序,那么程序是如何完成的(具体来说,在 Linux 基础环境中)?

在开始执行其主要功能之前,单个程序还必须执行哪些其他操作?

带有注释的 i386 NASM 汇编代码的示例表示赞赏。此外,任何可以帮助作者实现其目标的网络资源也将不胜感激。

最佳答案

你可以去搜索一下linux的ELF格式。以及适用于 Windows 的 PE-COFF。

这些是可执行文件的格式,这是操作系统知道的。在 Linux 下,您有负责加载程序的模块,并且在其他模块中使用可执行格式来正确加载程序。

编辑:来自 glibc 的线索给出了答案:

/*
[snip]
%esp The stack contains the arguments and environment:
0(%esp) argc
4(%esp) argv[0]
...
(4*argc)(%esp) NULL
(4*(argc+1))(%esp) envp[0]
...
NULL
[snip]
*/
[snip]
_start:
/* Clear the frame pointer. The ABI suggests this be done, to mark
the outermost frame obviously. */
xorl %ebp, %ebp

/* Extract the arguments as encoded on the stack and set up
the arguments for `main': argc, argv. envp will be determined
later in __libc_start_main. */
popl %esi /* Pop the argument count. */
movl %esp, %ecx /* argv starts just at the current stack top.*/

/* Before pushing the arguments align the stack to a 16-byte
(SSE needs 16-byte alignment) boundary to avoid penalties from
misaligned accesses. Thanks to Edward Seidl <seidl@janed.com>
for pointing this out. */
andl $0xfffffff0, %esp
pushl %eax /* Push garbage because we allocate
28 more bytes. */

/* Provide the highest stack address to the user code (for stacks
which grow downwards). */
pushl %esp

pushl %edx /* Push address of the shared library
termination function. */

[snip]

关于linux - 是程序还是操作系统负责设置栈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3265057/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com