C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Monitor recursion by checking the frame pointer

From: Thiago Macieira <thiago_at_[hidden]>
Date: Mon, 17 Apr 2023 09:17:28 -0500
On Monday, 17 April 2023 06:09:25 CDT Frederick Virchanza Gotham via Std-
Proposals wrote:
> Then I realised that this
> could be ascertained from the stack pointer (i.e. the RSP register on
> x86_64, or the x31sp register on aarch64).

No, it can't.

The stack pointer register on x86 is architectural, so the return address is
always stored there, but that's not the case for almost any other architecture
(I don't know any; the closest is ARM Thumb mode). For those, the return
address is stored in a particular register by convention. Moreover, for those,
the stack pointer register itself is also a convention.

But fair enough, the ABI has to specify how the stack is handled and how the
function call sequence happens, so the stack pointer and return addresses are
somewhere.

However, you said "frame pointer" but listed RSP for x86. That's the wrong
register. The frame pointer on x86 is RBP and it doesn't need to be kept. In
optimised code, if the compiler can avoid needing RBP for the frame pointer
and free it instead for a variable, that improves performance, due to the
shortage of available general-purpose registers. So you cannot count on there
being a frame pointer on x86.

And in other architectures, even less so. The return address that a function
received in that ABI-specified register needs to be stored *somewhere* for the
recursive call sequence to happen, but where it is stored is unspecified. So
there's no way to unwind the stack and determine which functions are running
without extra help. That's debugging information and you cannot count on it
being present.

Note that unwinding the stack in order to throw exceptions uses a different set
of information tables and they will not necessarily give you the information
you want.

Conclusion: while your proposal for some functions may have some interest, it
can't do what you wanted it for.

-- 
Thiago Macieira - thiago (AT) macieira.info - thiago (AT) kde.org
   Software Architect - Intel DCAI Cloud Engineering

Received on 2023-04-17 14:17:31