From f1e56f54b25e178e813ab44b6e449c55675841bb Mon Sep 17 00:00:00 2001 From: Eric Biggers Date: Fri, 30 Aug 2019 00:14:43 -0500 Subject: [PATCH] test_util: use MAP_ANONYMOUS instead of /dev/zero Apparently, mmap'ing /dev/zero fails on macOS. So contrary to the intent, it's not actually portable. Switch to MAP_ANONYMOUS instead, with a fallback to MAP_ANON if it's not defined. --- programs/test_util.c | 33 ++++++++++++++++++--------------- 1 file changed, 18 insertions(+), 15 deletions(-) diff --git a/programs/test_util.c b/programs/test_util.c index 8bd88e6..2ff8b83 100644 --- a/programs/test_util.c +++ b/programs/test_util.c @@ -25,6 +25,16 @@ * OTHER DEALINGS IN THE SOFTWARE. */ +#ifndef _WIN32 +/* for MAP_ANONYMOUS or MAP_ANON, which unfortunately aren't part of POSIX... */ +# undef _POSIX_C_SOURCE +# ifdef __APPLE__ +# define _DARWIN_C_SOURCE +# elif defined(__linux__) +# define _GNU_SOURCE +# endif +#endif + #include "test_util.h" #include @@ -37,6 +47,10 @@ # include #endif +#ifndef MAP_ANONYMOUS +# define MAP_ANONYMOUS MAP_ANON +#endif + /* Abort with an error message */ _noreturn void assertion_failed(const char *expr, const char *file, int line) @@ -68,8 +82,6 @@ alloc_guarded_buffer(size_t size, u8 **start_ret, u8 **end_ret) u8 *start, *end; #ifdef _WIN32 DWORD oldProtect; -#else - int fd; #endif *start_ret = NULL; @@ -95,20 +107,11 @@ alloc_guarded_buffer(size_t size, u8 **start_ret, u8 **end_ret) return -1; } #else - /* - * Allocate buffer and guard pages. - * For portability, use /dev/zero instead of MAP_ANONYMOUS. - */ - fd = open("/dev/zero", O_RDONLY); - if (fd < 0) { - msg_errno("Unable to open /dev/zero"); - return -1; - } - base_addr = mmap(NULL, (nr_pages + 2) * pagesize, - PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0); - close(fd); + /* Allocate buffer and guard pages. */ + base_addr = mmap(NULL, (nr_pages + 2) * pagesize, PROT_READ|PROT_WRITE, + MAP_PRIVATE|MAP_ANONYMOUS, -1, 0); if (base_addr == (u8 *)MAP_FAILED) { - msg_errno("Unable to allocate memory (unable to mmap /dev/zero)"); + msg_errno("Unable to allocate memory (anonymous mmap)"); return -1; } start = base_addr + pagesize;