-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack_alloc.c
105 lines (86 loc) · 2.31 KB
/
stack_alloc.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
// Copyright © 2018-2023 ButenkoMS. All rights reserved.
// Licensed under the Apache License, Version 2.0.
#include "stack_alloc.h"
#include <stdlib.h>
#if defined COROUTINE_HAVE_WIN32API
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <memoryapi.h>
#include <sysinfoapi.h>
#else
#if defined COROUTINE_HAVE_MMAP
#include <sys/mman.h>
#endif
#if defined COROUTINE_HAVE_SYSCONF || defined COROUTINE_HAVE_GETPAGESIZE
#include <unistd.h>
#endif
#endif
size_t sa_real_stack_size(size_t size);
static inline size_t get_page_size(void) {
#if defined COROUTINE_STATIC_PAGE_SIZE
return COROUTINE_STATIC_PAGE_SIZE;
#elif defined COROUTINE_HAVE_WIN32API
SYSTEM_INFO si;
GetSystemInfo(&si);
return si.dwPageSize;
#elif defined COROUTINE_HAVE_SYSCONF
return sysconf(COROUTINE_SC_PAGE_SIZE);
#elif defined COROUTINE_HAVE_GETPAGESIZE
return getpagesize();
#else
#error Can not detext page size
#endif
}
static inline void *alloc_stack_mem(size_t size) {
#if defined COROUTINE_HAVE_WIN32API
return VirtualAlloc(NULL, size, MEM_COMMIT, PAGE_READWRITE);
#elif defined COROUTINE_HAVE_MMAP
return mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | COROUTINE_MAP_ANONYMOUS, -1, 0);
#elif defined COROUTINE_HAVE_ALIGNED_ALLOC
return aligned_alloc(sa_page_size(), size);
#elif defined COROUTINE_HAVE_POSIX_MEMALIGN
void *p = NULL;
posix_memalign(&p, sa_page_size(), size);
return p;
#else
#pragma GCC warning "stack can not be aligned to the page size"
return calloc(1, size);
#endif
}
static inline void free_stack_mem(void *stack, size_t size) {
#if defined COROUTINE_HAVE_WIN32API
(void)size;
VirtualFree(stack, 0, MEM_RELEASE);
#elif defined COROUTINE_HAVE_MMAP
munmap(stack, size);
#else
(void)size;
free(stack);
#endif
}
void *alloc_stack(size_t minsize, size_t *realsize) {
size_t sz = sa_real_stack_size(minsize);
*realsize = sz;
return alloc_stack_mem(sz);
}
void free_stack(void *stack, size_t size) {
free_stack_mem(stack, size);
}
size_t sa_page_size(void) {
static size_t page_size = 0;
if(!page_size) {
page_size = get_page_size();
}
return page_size;
}
size_t sa_real_stack_size(size_t size) {
size_t page_size = sa_page_size();
if(size == 0) {
size = 64 * 1024;
}
size_t num_pages = (size - 1) / page_size + 1;
if(num_pages < 2) {
num_pages = 2;
}
return num_pages * page_size;
}