GAS: Explanation of .cfi_def_cfa_offset

As the DWARF spec says in section 6.4:

[...] The call frame is identified by an address on the stack. We refer to this address as the Canonical Frame Address or CFA. Typically, the CFA is defined to be the value of the stack pointer at the call site in the previous frame (which may be different from its value on entry to the current frame).

main() is called from somewhere else (in the libc C runtime support code), and, at the time the call instruction is executed, %rsp will point to the top of the stack (which is the lowest address - the stack grows downwards), whatever that may be (exactly what it is doesn't matter here):

:                :                              ^
|    whatever    | <--- %rsp                    | increasing addresses
+----------------+                              |

The value of %rsp at this point is the "value of the stack pointer at the call site", i.e. the CFA as defined by the spec.

As the call instruction is executed, it will push a 64-bit (8 byte) return address onto the stack:

:                :
|    whatever    | <--- CFA
+----------------+
| return address | <--- %rsp == CFA - 8
+----------------+

Now we are running the code at main, which executes subq $8, %rsp to reserve another 8 bytes of stack for itself:

:                :
|    whatever    | <--- CFA
+----------------+
| return address |
+----------------+
| reserved space | <--- %rsp == CFA - 16
+----------------+

The change of stack pointer is declared in the debugging information using the .cfi_def_cfa_offset directive, and you can see that the CFA is now at an offset of 16 bytes from the current stack pointer.

At the end of the function, the addq $8, %rsp instruction changes the stack pointer again, so another .cfi_def_cfa_offset directive is inserted to indicate that the CFA is now at an offset of only 8 bytes from the stack pointer.

(The number "22" in the labels is just an arbitrary value. The compiler will generate unique label names based on some implementation detail, such as its internal numbering of basic blocks.)


I would like an explanation for the values used with the .cfi_def_cfa_offset directives in assembly generated by GCC.

Matthew provided a good explanation. Here's the definition from Section 7.10 CFI Directives in the GAS manual:

.cfi_def_cfa_offset modifies a rule for computing CFA. Register remains the same, but offset is new. Note that it is the absolute offset that will be added to a defined register to compute CFA address.

And .cfi_adjust_cfa_offset:

Same as .cfi_def_cfa_offset but offset is a relative value that is added/substracted from the previous offset.