switching stacks

By mikehearn

Usually a program only has multiple stacks if it has multiple threads, but sometimes it can be useful to have multiple stacks per thread. This is rare, but is handy for implementing certain types of language constructs like continuations or cothreads. It’s also used inside Wine and my dissertation project (which I’ll talk about more when it’s finished).

To allocate a new stack and switch to it, something like the following code will work on Linux/x86:

static __attribute__((used)) void *new_stack(int stacksize)
{
    // first argument: don't care where the stack is
    // third argument: VM permissions - stacks are read/write but not executable
    // fourth argument: VM flags - see man page
    // last arguments: unused for anonymous mappings

    void *s = mmap(NULL,  stacksize, PROT_READ|PROT_WRITE,
                   MAP_PRIVATE | MAP_GROWSDOWN | MAP_ANONYMOUS, 0, 0);
    if (s == MAP_FAILED) fatal_perror("stack mmap");

    return s;
}

..........

asm("	push $0x200000\n"  // 2 megabyte stack
    "	call new_stack\n"  // allocate it
    "	mov %eax, %esp\n"  // set %esp to its base
    "	xor %ebp, %ebp\n"  // clear %ebp
    "	call initial_function\n");  // call first function

The attribute((used)) marker is to prevent GCC optimizing the function out. Now initial_function() will be running on the newly allocated stack. If you don’t need the old one anymore remember to deallocate it using munmap. Pretty straightforward, no? Things get more fun when you need to return from initial_function() and switch back.

audiojelly

AudioJelly is a legal, paid for MP3 store which sells d&b, beatbeat, trace and other electronic music genres. I just bought my first MP3 from there, it was straightforward and no hassle. And of course works on Linux. They have an excellent Flash based preview player that gives you long previews, and even has a playlist. I bought the Burufunk remix of Ashland – Clear (click the little headphone icon to hear).

2 Responses to “switching stacks”

  1. laura Says:

    burufunk is be one of the few truly loved artists in this decade. his music is from his heart

  2. Mike Says:

    Yeah, I need to check out more of his stuff

Leave a Reply

You must be logged in to post a comment.