【问题标题】:Dynamic expansion of the Linux stackLinux堆栈的动态扩展
【发布时间】:2019-07-01 00:50:00
【问题描述】:

我注意到 Linux 堆栈开始时很小,并随着递归/推送/vlas 导致的页面错误扩展至大小 getrlimit(RLIMIT_STACK,...),给予或接受(在我的系统上默认为 8MiB)。

但奇怪的是,如果我通过直接寻址字节导致页面错误,在限制范围内,Linux 只会定期出现段错误而不扩展页面映射(虽然没有段错误,如果我在获得例如 alloca 之后这样做,会导致堆栈扩展)。

示例程序:

#include <stdio.h>
#include <unistd.h>
#include <stdint.h>
#include <stdlib.h>
#define CMD "grep stack /proc/XXXXXXXXXXXXXXXX/maps"
#define CMDP "grep stack /proc/%ld/maps"
void vla(size_t Sz)
{
    char b[Sz];
    b[0]='y';
    b[1]='\0';
    puts(b);
}
#define OFFSET (sizeof(char)<<12)
int main(int C, char **V)
{
    char cmd[sizeof CMD]; sprintf(cmd,CMDP,(long)getpid());
    if(system(cmd)) return 1;
    for(int i=0; ; i++){
        printf("%d\n", i);
        char *ptr = (char*)(((uintptr_t)&ptr)-i*OFFSET);
        if(C>1) vla(i*OFFSET); //pass an argument to the executable to turn this on
        ptr[0] = 'x';
        ptr[1] = '\0';
        if(system(cmd)) return 1;
        puts(ptr);
    }
}

什么内核代码在做这个?它如何区分自然堆栈增长和我在地址空间中四处寻找?

【问题讨论】:

标签: c linux memory page-fault


【解决方案1】:

linux内核以栈指针的内容为界限(在合理的范围内)。访问堆栈下面堆栈指针减去 65536 和 32 个无符号长整数的大小会导致分段违规。因此,如果您访问堆栈中的内存,则必须确保堆栈指针以某种方式随着访问而减小,以使 linux 内核扩大该段。看到这个来自/arch/x86/mm/fault.c的sn-p:

if (sw_error_code & X86_PF_USER) {
    /*
     * Accessing the stack below %sp is always a bug.
     * The large cushion allows instructions like enter
     * and pusha to work. ("enter $65535, $31" pushes
     * 32 pointers and then decrements %sp by 65535.)
     */
    if (unlikely(address + 65536 + 32 * sizeof(unsigned long) < regs->sp)) {
        bad_area(regs, sw_error_code, address);
        return;
    }
}

栈指针寄存器的值是这里的关键!

【讨论】:

  • 谢谢。我怀疑这一点,但在内核中找不到代码。你的答案很好!
猜你喜欢
  • 1970-01-01
  • 2023-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-20
  • 1970-01-01
相关资源
最近更新 更多