How to get address of base stack pointer

后端 未结 6 1910
逝去的感伤
逝去的感伤 2020-12-14 03:18

I am in the process of porting an application from x86 to x64. I am using Visual Studio 2009; most of the code is C++ and some portions are plain C. The __asm keyword is not

6条回答
  •  孤城傲影
    2020-12-14 03:44

    The really right thing to do would be to rewrite whatever this function does so that it does not require access to the actual frame pointer. That is definitely bad behavior.

    But, to do what you are looking for you should be able to do:

    int CallStackSize() {
        __int64 Frame = 0; /* MUST be the very first thing in the function */
        PDWORD pFrame;
    
        Frame++; /* make sure that Frame doesn't get optimized out */
    
        pFrame = (PDWORD)(&Frame);
        /*... do stuff with pFrame here*/
    }
    

    The reason this works is that in C usually the first thing a function does is save off the location of the base pointer (ebp) before allocating local variables. By creating a local variable (Frame) and then getting the address of if, we're really getting the address of the start of this function's stack frame.

    Note: Some optimizations could cause the "Frame" variable to be removed. Probably not, but be careful.

    Second Note: Your original code and also this code manipulates the data pointed to by "pFrame" when "pFrame" itself is on the stack. It is possible to overwrite pFrame here by accident and then you would have a bad pointer, and could get some weird behavior. Be especially mindful of this when moving from x86 to x64, because pFrame is now 8 bytes instead of 4, so if your old "do stuff with pFrame" code was accounting for the size of Frame and pFrame before messing with memory, you'll need to account for the new, larger size.

提交回复
热议问题