Since inline assembler is not available in Microsoft C++ when compiling for the x64 architecture, I can't figure out how to access the RSP register (stack pointer). I know I can read it using RtlCaptureContext, but this would also perform a lot of unwanted operations. Also it would be a few thousand times slower (for my purposes, not acceptable). If I write a separate ASM function, the RSP would obviously change, so that is not an alternative either.
So how does one read the contents for the x64 RSP register using Microsoft C++?
You can get it indirectly using the _AddressOfReturnAddress()
(see MSDN reference) intrinsic.
Obviously, you do not get to know for sure where the current stack frame stops, but you can guesstimate it with whatever stack variables you have and by looking at the generated assembly.
In combination with Olipro's suggestion: using _AddressOfReturnAddress()
in a standalone function, getting the stack address becomes seriously easy. Not to mention that there is a great probability for a function written in C containing only a call to this intrinsic to be inlined.
OK, so, I've had a fiddle with it and got it working; you can't get the compiler to inline it, but you fortunately don't need it to, just drop this into a .s or .asm file and compile with `ml64 /c yourasm.s" and hand the .obj to the linker.
.CODE
getRSP PROC
mov rax, rsp
add rax, 8
ret
getRSP ENDP
END
then on the C side of things all you need is extern "C" __int64 getRSP();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With