abi

Why is the static chain pointer needed for nested functions?


I stumbled upon the static chain pointer while reading about the System V ABI and I found this explanation on its usage in nested functions.

I am curious, why do we need the static chain pointer at all? If the address of the nested function is not taken, why the need of a value pointing to the position of the stack of the parent? Will it not be immediately before the child's in every occasion?


Solution

  • Will it not be immediately before the child's in every occasion?

    In general it won't, because the child can call itself, or another function nested in the same parent (i.e. a sibling). And you can have multiple levels of nesting, where a "grandchild" function calls an "aunt" (i.e. a deeply-nested function calls a child of the outermost function that's not one it's nested inside). In none of these cases will the parent's stack be immediately before the child's.