Call a C function using the stack pointer (gcc)

I am looking for a way to call a C function on another stack, that is, save the current stack pointer, set the stack pointer to another location, call the function and restore the old stack pointer when it returns.

The goal of this is a lightweight streaming system for a programming language. Streams will run on very small stacks, check to see if a larger stack is needed and dynamically resize it. This allows you to allocate thousands of threads without wasting a lot of memory. When calling C code, it is unsafe to use a tiny stack, because C code does not know about checking and resizing, so I want to use a large pthread stack, which is used only to call C (shared between light threads on the same pthread).

Now I could write pieces of assembly code that would work fine, but I was wondering if there is a better way to do this, such as a gcc extension or a library that already implements it. If not, then I think I will have a head similar to ABI and assembly instructions ;-) I just ask about it out of laziness and do not want to reinvent the wheel.

+8
c gcc stack pointers
source share
1 answer

Assuming you are using POSIX streams on a POSIX system, you can achieve this with signals. Set up an alternative signal processing stack ( sigaltstack ) and assign one special signal in real time so that its processor works in the alternative signal stack. Then raise signal to switch to the stack and the signal handler reads the data for which function to call and which argument to pass from the local data of the stream.

Please note that this approach is quite expensive (several system calls to change stacks), but should be 100% portable for POSIX systems. Since it is slow, you may want to create special call-on-alt-stack functions created in the assembly and use my general solution as a backup for the arch where you did not write the assembly version.

+2
source share

All Articles