Skip to content

Commit e8c7e85

Browse files
Morriarst0012
authored andcommitted
Fix unavailable MAP_ANONYMOUS
Signed-off-by: Alexandre Terrasa <[email protected]>
1 parent a40fae3 commit e8c7e85

File tree

1 file changed

+23
-5
lines changed

1 file changed

+23
-5
lines changed

src/util/rbs_allocator.c

Lines changed: 23 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -22,15 +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-
2925
struct rbs_allocator {
3026
uintptr_t heap_ptr;
3127
uintptr_t size;
3228
};
3329

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+
3452
static size_t get_system_page_size(void) {
3553
#ifdef _WIN32
3654
SYSTEM_INFO si;
@@ -48,7 +66,7 @@ static void *map_memory(size_t size) {
4866
LPVOID result = VirtualAlloc(NULL, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
4967
rbs_assert(result != NULL, "VirtualAlloc failed");
5068
#else
51-
void *result = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
69+
void *result = portable_mmap_anon(size);
5270
rbs_assert(result != MAP_FAILED, "mmap failed");
5371
#endif
5472
return result;

0 commit comments

Comments
 (0)