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.
This commit is contained in:
Eric Biggers 2019-08-30 00:14:43 -05:00
parent 2a2e24dc8b
commit f1e56f54b2

View File

@ -25,6 +25,16 @@
* OTHER DEALINGS IN THE SOFTWARE. * 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 "test_util.h"
#include <fcntl.h> #include <fcntl.h>
@ -37,6 +47,10 @@
# include <sys/time.h> # include <sys/time.h>
#endif #endif
#ifndef MAP_ANONYMOUS
# define MAP_ANONYMOUS MAP_ANON
#endif
/* Abort with an error message */ /* Abort with an error message */
_noreturn void _noreturn void
assertion_failed(const char *expr, const char *file, int line) 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; u8 *start, *end;
#ifdef _WIN32 #ifdef _WIN32
DWORD oldProtect; DWORD oldProtect;
#else
int fd;
#endif #endif
*start_ret = NULL; *start_ret = NULL;
@ -95,20 +107,11 @@ alloc_guarded_buffer(size_t size, u8 **start_ret, u8 **end_ret)
return -1; return -1;
} }
#else #else
/* /* Allocate buffer and guard pages. */
* Allocate buffer and guard pages. base_addr = mmap(NULL, (nr_pages + 2) * pagesize, PROT_READ|PROT_WRITE,
* For portability, use /dev/zero instead of MAP_ANONYMOUS. MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
*/
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);
if (base_addr == (u8 *)MAP_FAILED) { 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; return -1;
} }
start = base_addr + pagesize; start = base_addr + pagesize;