Marcus Hampel
Marcus Hampel

Reputation: 63

Linux how to get lowest possible stack address

I want to embed a Google V8 (v6.8) in a C++ program. Since this program uses a lot of stack, I want to configure the V8 to use the entire available stack. To do this, I need the smallest permitted stack address that the V8 can use.

uint32_t *base;
// TODO: set `base` to lowest stack address
...
v8::Isolate::CreateParams createParams;
createParams.array_buffer_allocator =
    v8::ArrayBuffer::Allocator::NewDefaultAllocator();
createParams.constraints.set_stack_limit(base);

defaultIsolate = Isolate::New(createParams);
...

Now I have to determine the value for base under Linux. To do this, I tried reading /proc/self/maps. However, the segment read for the stack is always only 132k in size:

7fff03e18000-7fff03e39000 rw-p 00000000 00:00 0                          [stack]

This seems to be independent of which stack limit is set. I also tried reading the limit using getrlimit() and reducing the highest address by the limit. But that then leads to a crash.

Can anyone tell me how else I can find out the lowest stack address under Linux?

Upvotes: 0

Views: 92

Answers (1)

Homer512
Homer512

Reputation: 13463

The address range that you read from /proc/self/maps is misleading because the memory mapping for the stack of the main thread grows dynamically. The stacks for other threads do not grow, as far as I understand it.

Here is a Linux-specific way to retrieve the full range of the stack:

#define _GNU_SOURCE
/* required for _np functions */
#include <pthread.h>

int main(void)
{
    pthread_attr_t attr;
    void* stackaddr;
    size_t stacksize;
    if(pthread_getattr_np(pthread_self(), &attr))
        return 1;
    if(pthread_attr_getstack(&attr, &stackaddr, &stacksize))
        return 1;
    pthread_attr_destroy(&attr);
}

The stackaddr is the lowest possible stack address. Because the stack grows towards lower addresses, this should be the end address for your stack limit parameter. I have verified that you can write to that address and that this will grow the stack size mapping to 8 MiB or whatever your process limit is.

Upvotes: 3

Related Questions