Skip to content

Commit d4ab4a2

Browse files
committed
Allocate the memory for stack with the MAP_GROWSDOWN flag
1 parent 4bd6724 commit d4ab4a2

File tree

1 file changed

+5
-3
lines changed

1 file changed

+5
-3
lines changed

coroutine.c

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,13 @@
66

77
#include <poll.h>
88
#include <unistd.h>
9+
#include <sys/mman.h>
910

1011
#include "coroutine.h"
1112

1213
// TODO: make the STACK_CAPACITY customizable by the user
1314
//#define STACK_CAPACITY (4*1024)
14-
#define STACK_CAPACITY (20*1024*1024)
15+
#define STACK_CAPACITY (1024*getpagesize())
1516

1617
// Initial capacity of a dynamic array
1718
#ifndef DA_INIT_CAP
@@ -207,7 +208,7 @@ void coroutine_finish(void)
207208
{
208209
if (active.items[current] == 0) {
209210
for (size_t i = 1; i < contexts.count; ++i) {
210-
free(contexts.items[i].stack_base);
211+
munmap(contexts.items[i].stack_base, STACK_CAPACITY);
211212
}
212213
free(contexts.items);
213214
free(active.items);
@@ -257,7 +258,8 @@ void coroutine_go(void (*f)(void*), void *arg)
257258
// This may require employing mmap(2) and mprotect(2) on Linux.
258259
da_append(&contexts, ((Context){0}));
259260
id = contexts.count-1;
260-
contexts.items[id].stack_base = malloc(STACK_CAPACITY); // TODO: align the stack to 16 bytes or whatever
261+
contexts.items[id].stack_base = mmap(NULL, STACK_CAPACITY, PROT_WRITE|PROT_READ, MAP_PRIVATE|MAP_STACK|MAP_ANONYMOUS|MAP_GROWSDOWN, -1, 0);
262+
assert(contexts.items[id].stack_base != MAP_FAILED);
261263
}
262264

263265
void **rsp = (void**)((char*)contexts.items[id].stack_base + STACK_CAPACITY);

0 commit comments

Comments
 (0)