Sat Aug 1 13:41:07 CEST 2009

Tasks on heap

So.. Instead of copying the C stack, how can a C subroutine's stack be
allocated on the heap before it is executed, avoiding unnecessary
copying?  The following macro could act as a portable way to switch

#define SET_STACK(sp) \
    char _reserve_start[0]; \
    alloca(((void*)_reserve_start) - (sp))

Maybe it's just more convenient to keep it as it is: no need to
estimate stack sizes and no need for extra wrapping for initial entry
and final exit.

Problem: when I disable optimization, it no longer works.  Looks like
I assume I'm depending on some parameters being stored in registers
when switching/copying stack.

After the memcpy() the variable containing a reference to the context
gets overwritten.

task *ctx; 0x7fffffffd3e8
_sp        0x7fffffffd338
size       472

The `ctx' variable is not allocated on top of the reserved stack
space..  the alloca() doesn't do what I think it does.

Trying again with

#define SET_STACK(sp) \
    char _reserve_start[0]; \
    char _reserve[((void*)_reserve_start) - (sp)]


ctx->base      0x7fffffffd510
&ctx           0x7fffffffd3e8
_reserve_start 0x7fffffffd3a0
_sp            0x7fffffffd338
_reserve       0x7fffffffd2f0

which makes no sense at all..  Conclusion: It looks like C variables
can be re-arranged in memory.  Apparently nothing is specified[1].

Trying again but using the assumption that a large array will be
allocated on the stack.

    /* Reserve stack space (overestimate) */
    volatile void *reserve[ctx->size / sizeof(void *)];

base          0x7fffffffd510
sp            0x7fffffffd338
reserve       0x7fffffffd180

Ok. I fixed it now by:

    - allocating a large array to make sure function call/return works
      during/after memcpy.

    - making sure the ctx variable is not allocated on the stack

So, maybe it is possible to predict alloca?  Run it once, see where
the pointer ends up, then run it again to move the stack permanently.

[1] http://stackoverflow.com/questions/1102049/order-of-local-variable-allocation-on-the-stack