os::current_stack_pointer seems a little strange

Andrew Haley aph-open at littlepinkcloud.com
Sat Jun 29 09:14:54 UTC 2024


On 6/29/24 07:40, Julian Waters wrote:

 > While looking through HotSpot I recently came across
 > os::current_stack_pointer, and the implementations seem a little odd.
 > On Windows x86, ARM64 and macOS Zero, it essentially returns the
 > address of the first local defined in itself, which should correspond
 > to the frame pointer of os::current_stack_pointer, which in turn
 > should equal the stack pointer of the caller, which is what we want to
 > get. Windows x64 instead delegates this task to runtime created
 > assembly from StubRoutines, Linux x86, PowerPC, ARM64, RISC-V, Zero as
 > well as AIX PowerPC all use __builtin_frame_address(0), Linux ARM32
 > loads the stack pointer using register address sp __asm__ ("sp");
 > which essentially loads the stack pointer into the sp local, and Linux
 > s390x and macOS x64 and ARM64 all use some form of handwritten
 > assembly to load the current stack pointer
 >
 > (Someone please correct me if I'm wrong about what
 > os::current_stack_pointer  is trying to get, as in, the current stack
 > pointer)

This:

// Returns an estimate of the current stack pointer. Result must be guaranteed
// to point into the calling threads stack, and be no lower than the current
// stack pointer.

We don't attempt to trace the C++ stack precisely, whatever that would
mean in practice. Of course a C++ implementation is entitled to move
the stack pointer whenever it chooses, which includes immediately
before and after any call to os::current_stack_pointer().

 From that point of view, the idea of trying to catch a precise value of
the current stack pointer makes sense, sort of, but it's only valid for
that instant. Trying to catch such a moving target is like trying to
catch smoke.

The right question for you to think about is "What is the result of
current_stack_pointer used for?" Then consider if those uses are
correct. And if you find any that aren't guaranteed to be correct,
then consider that to some extent we depend on "reasonable" behaviour
of C++ implementations, for some definition of reasonable...

-- 
Andrew Haley  (he/him)
Java Platform Lead Engineer
Red Hat UK Ltd. <https://www.redhat.com>
https://keybase.io/andrewhaley
EAC8 43EB D3EF DB98 CC77 2FAD A5CD 6035 332F A671



More information about the hotspot-dev mailing list