|
From: | Jeff Schwab |
Subject: | Re: changing stacks |
Date: | Thu, 14 Feb 2008 22:13:52 -0800 |
User-agent: | Thunderbird 2.0.0.9 (X11/20071031) |
Ganesh wrote:
Hi, I need to switch the stack before a function call in C++. Can I just change the stack pointer just before the function invocation. Is that all that is required to change stacks? Like, void func { change_stack_pointer foo (exp1, exp2...) restore_stack_pointer }
Why are you doing that? Forgive the question, but I've never seen anything like that in C++, and I'm curious. Have you got one thread trying to call a function in the context of another? If so, I have to wonder why you don't just have the correct thread call the function in the first place.
The function call has expressions that access the local variable in the original stack. I am concerned that if a compiler (say g++) emits a code that accesses the local variable of func using address relative to SP, then the above approach will fail (because the SP is changed).
That is a very reasonable concern. Care was taken in the design of the C and C++ programming languages to make sure that you would never need to do anything like this, outside of very low-level scheduling code.
How shall I gurantee in g++ (and if possible in other compilers) that access to local variables is not relative to SP? Or is it always the case that the access is not relative to SP?
It depends on the architecture, but local variable addresses on x86 are typically relative to the base pointer EBP, not the stack pointer ESP. The -fomit-frame-pointer flag allows GCC to use offsets directly from the stack pointer.
On x86, with C-style calling conventions, the register EBP is copied from ESP inside the function call. This means that if you modify the stack-pointer before the function is called, EBP is copied to late to make a difference. It will be copying a potentially invalid stack-pointer.
I know that there are other ways to change stack (makecontext, sigaltstack etc). But, I want an extremely light weight mechanism.
[Prev in Thread] | Current Thread | [Next in Thread] |