Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading the RSP register from Microsoft C++

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++?

like image 590
Jack Wester Avatar asked Jul 18 '11 13:07

Jack Wester


2 Answers

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.

like image 159
Raphaël Saint-Pierre Avatar answered Sep 20 '22 14:09

Raphaël Saint-Pierre


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();

like image 29
Olipro Avatar answered Sep 19 '22 14:09

Olipro