GNU汇编疑问:-4(%rbp)为何未覆盖栈上的帧指针?
movl %edi, -0x4(%rbp) is safe in x86-64 stack frames Great question—this is a common point of confusion when first unpacking x86-64 stack frame mechanics! Let's break down exactly what's happening here, step by step.
First, let's recap the stack frame setup instructions you provided:
_sum: 0000000100000f60 pushq %rbp 0000000100000f61 movq %rsp, %rbp 0000000100000f64 movl %edi, -0x4(%rbp) 0000000100000f67 movl %esi, -0x8(%rbp)
Key Background: x86-64 Stack Growth
The x86-64 stack grows downward—meaning stack addresses decrease as you push more data onto the stack. When you execute pushq %rbp, two things happen:
- The stack pointer
%rspis decremented by 8 (sinceqdenotes an 8-byte operation). - The current value of
%rbpis written to the memory location now pointed to by%rsp.
What movq %rsp, %rbp Does
After pushing %rbp, we set %rbp equal to %rsp. This makes %rbp the base pointer for the current function's stack frame, pointing directly to the start of the saved %rbp value (which occupies 8 bytes of memory, from %rbp to %rbp + 7).
Why -0x4(%rbp) Doesn't Overwrite Saved %rbp
When we execute movl %edi, -0x4(%rbp), we're writing to the memory address calculated as %rbp - 4. Since %rbp points to the start of the saved %rbp value, subtracting 4 moves us to an address below (lower numerical value) the saved %rbp—this is unused stack space reserved for the function's local variables, and it doesn't overlap with the 8 bytes of the saved %rbp at all.
Let's use concrete addresses to make this tangible:
- Suppose before
pushq %rbp,%rspis0x1000. - After
pushq %rbp,%rspbecomes0x0FF8, and the original%rbpvalue is stored in addresses0x0FF8to0x0FFF. movq %rsp, %rbpsets%rbpto0x0FF8.movl %edi, -0x4(%rbp)writes to0x0FF8 - 4 = 0x0FF4(covering0x0FF4to0x0FF7), which is completely separate from the saved%rbp's space (0x0FF8to0x0FFF).
Final Notes
- The negative offsets from
%rbpare standard for accessing local variables in x86-64 stack frames—they're designed to avoid interfering with the saved%rbp(or the return address, which is stored higher up in the stack). - As you noted,
%ediand%esihold the first two integer arguments to thesumfunction; storing them in the stack frame is a safe way to preserve their values for use later in the function.
内容的提问来源于stack exchange,提问作者acomplex

