Will the stack of a C program ever shrink?

前端 未结 3 1948
说谎
说谎 2021-01-19 14:04

I\'ve noticed that every running C program has a private mapping called [stack] that is initially quite small (128k on my machine), but will grow to accomodate any automatic

3条回答
  •  借酒劲吻你
    2021-01-19 14:26

    In Linux/MMU (in !MMU you cannot grow the stack), the stack is grown in the page fault handler. For x86, whether to grow the stack is decided by the following code from arch/x86/mm/fault.c:do_page_fault():

            if (error_code & 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, error_code, address);
                        return;
                }
        }
        if (unlikely(expand_stack(vma, address))) {
                bad_area(regs, error_code, address);
                return;
        }
    

    expand_stack() checks the usual RLIMITS (RLIMIT_AS, RLIMIT_STACK, RLIMIT_MEMLOCK), whether LSMs will allow to grow the stack, whether there's too much overcommit, etc..., and finally grows the stack.

提交回复
热议问题