Reading RSP register from Microsoft C ++

Since inline assembler is not available in Microsoft C ++ when compiling for x64 architecture, I cannot figure out how to access the RSP register (stack pointer). I know that I can read it using RtlCaptureContext, but it will also perform many unwanted operations. It would also be several thousand times slower (for my purposes, unacceptable). If I write a separate ASM function, RSP will obviously change, so this is not an alternative either.

So, how to read the contents of the x64 RSP registry using Microsoft C ++?

+6
source share
5 answers

You can get this indirectly using _AddressOfReturnAddress() (see MSDN link ). Obviously, you donโ€™t know exactly where the current stack stack is stopped, but you can evaluate it using any stack variables you have and looking at the generated assembly.

Combined with the Olipro clause: using _AddressOfReturnAddress() in a standalone function, getting the stack address becomes very easy. Not to mention the fact that there is a high probability that a function written in C contains only a call for this internal to be embedded.

+5
source

Okay, so I had a violin with her and it worked; you cannot force the compiler to embed it, but fortunately you do not need it, just add it to the .s or .asm file and compile with `ml64 / c yourasm.s' and transfer the .obj to the linker.

 .CODE getRSP PROC mov rax, rsp add rax, 8 ret getRSP ENDP END 

then on the C side the things you need are extern "C" __int64 getRSP();

+5
source

Do you know about _AddressOfReturnAddress internal? This is not an RSP registry, but somewhat erratic in itself.

+2
source

There are only two ways I can think of this:

1) create an ASM file with instructions for moving rsp to rax and return, and then see if you can force the compiler to embed it.

2) if above it is no-go, declare the volatile pointer variable and use the built-in __nop() to provide yourself enough space to fix the necessary instructions in the post-assembly (or heck, just assign the value of your mutable pointer several times and replace it)

+1
source

__getCFS , __getPSP , maybe __getReg ?

You can also link to the MinGW-w64 object file, which makes assembler inline.

0
source

Source: https://habr.com/ru/post/892990/


All Articles