8000 Fix unavailable MAP_ANONYMOUS · ruby/rbs@be16779 · GitHub
[go: up one dir, main page]

Skip to content

Commit be16779

Browse files
committed
Fix unavailable MAP_ANONYMOUS
Signed-off-by: Alexandre Terrasa <alexandre.terrasa@shopify.com>
1 parent 2e5d41d commit be16779

File tree

1 file changed

+23
-7
lines changed

1 file changed

+23
-7
lines changed

src/util/rbs_allocator.c

Lines changed: 23 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -22,16 +22,33 @@
2222
#include <sys/mman.h>
2323
#endif
2424

25-
#if defined(__APPLE__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__sun)
26-
#define MAP_ANONYMOUS MAP_ANON
27-
#endif
28-
29-
3025
struct rbs_allocator {
3126
uintptr_t heap_ptr;
3227
uintptr_t size;
3328
};
3429

30+
static void* portable_mmap_anon(size_t size) {
31+
void* ptr;
32+
33+
#ifdef _WIN32
34+
ptr = VirtualAlloc(NULL, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
35+
if (ptr == NULL) return NULL;
36+
#elif defined(MAP_ANONYMOUS)
37+
ptr = mmap(NULL, size, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
38+
#elif defined(MAP_ANON)
39+
ptr = mmap(NULL, size, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANON, -1, 0);
40+
#else
41+
/* Fallback to /dev/zero for systems without anonymous mapping */
42+
int fd = open("/dev/zero", O_RDWR);
43+
if (fd == -1) return MAP_FAILED;
44+
45+
ptr = mmap(NULL, size, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
46+
close(fd); /* Can close fd after mapping */
47+
#endif
48+
49+
return ptr;
50+
}
51+
3552
static size_t get_system_page_size(void) {
3653
#ifdef _WIN32
3754
SYSTEM_INFO si;
@@ -49,8 +66,7 @@ static void *map_memory(size_t size) {
4966
LPVOID result = VirtualAlloc(NULL, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
5067
rbs_assert(result != NULL, "VirtualAlloc failed");
5168
#else
52-
void *result = mmap(NULL, size, PROT_READ | PROT_WRITE,
53-
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
69+
void *result = portable_mmap_anon(size);
5470
rbs_assert(result != MAP_FAILED, "mmap failed");
5571
#endif
5672
return result;

0 commit comments

Comments
 (0)
0