I'm trying to understand how stack works in Linux. I read AMD64 ABI sections about stack and process initialization and it is not clear how the stack should be mapped. Here is the relevant quote (3.4.1):
Stack State
This section describes the machine state that
exec(BA_OS) creates for new processes.
and
It is unspecified whether the data and stack segments are initially mapped with execute permissions or not. Applications which need to execute code on the stack or data …
我浏览了一段时间,试图例如在执行操作时了解如何将内存分配给堆栈:
push rax
Run Code Online (Sandbox Code Playgroud)
或者移动堆栈指针为子例程的局部变量分配空间:
sub rsp, X ;Move stack pointer down by X bytes
Run Code Online (Sandbox Code Playgroud)
据我了解,堆栈段在虚拟内存空间中是匿名的,即不是文件支持的。
我还了解的是,内核不会真正将匿名虚拟内存段映射到物理内存,直到程序对该内存段进行实际操作(即写入数据)为止。因此,尝试在写入该段之前先读取该段可能会导致错误。
在第一个示例中,如果需要,内核将在物理内存中分配一个帧页。在第二个示例中,我假设内核不会在程序实际将数据写入堆栈堆栈段中的地址之前将任何物理内存分配给堆栈段。
我在正确的轨道上吗?
In the x86-64 System V ABI it is specified that the space behind the $rsp - 128 is the so-called red zone which is not touched by any signal handlers. On my machine
$ ulimit -s
8192
Run Code Online (Sandbox Code Playgroud)
I expected there is only 2 pages in the stack. So I wrote the following program to test till which size red zone can expand:
PAGE_SIZE equ 0x1000
SYS_exit equ 0x3C
section .text
global _start
_start:
lea rcx, [rsp - 0x1f * PAGE_SIZE] …Run Code Online (Sandbox Code Playgroud) 我正在使用堆栈进行一些实验,以下内容让我陷入困境。
可以看出Linux在大小上有初始[stack]映射132KiB。ulimit -s unlimited如果我们进行相应的调整,我们可以进一步扩展堆栈rsp。所以我设置ulimit -s unlimited并运行了以下程序:
PAGE_SIZE equ 0x1000
;mmap staff
PROT_READ equ 0x01
PROT_WRITE equ 0x02
MAP_ANONYMOUS equ 0x20
MAP_PRIVATE equ 0x02
MAP_FIXED equ 0x10
;syscall numbers
SYS_mmap equ 0x09
SYS_exit equ 0x3c
section .text
global _start
_start:
; page alignment
and rsp, -0x1000
; call mmap 0x101 pages below the rsp with fixed mapping
mov rax, SYS_mmap
lea rdi, [rsp - 0x101 * PAGE_SIZE]
mov rsi, PAGE_SIZE
mov …Run Code Online (Sandbox Code Playgroud)