From 08706fcc6d7bac3dfe27e2f99542db41e71829f2 Mon Sep 17 00:00:00 2001 From: Avi Kivity Date: Sun, 5 Oct 2014 18:04:18 +0300 Subject: [PATCH] posix: wrap mmap() for anonymous maps Automatically munmap() when the result is destroyed. --- core/posix.cc | 11 +++++++++++ core/posix.hh | 9 +++++++++ 2 files changed, 20 insertions(+) diff --git a/core/posix.cc b/core/posix.cc index cfed8120b2..a5f1d574e7 100644 --- a/core/posix.cc +++ b/core/posix.cc @@ -3,6 +3,17 @@ */ #include "posix.hh" +#include + +void mmap_deleter::operator()(void* ptr) const { + ::munmap(ptr, _size); +} + +mmap_area mmap_anonymous(void* addr, size_t length, int prot, int flags) { + auto ret = ::mmap(addr, length, prot, flags | MAP_ANONYMOUS, -1, 0); + throw_system_error_on(ret == MAP_FAILED); + return mmap_area(reinterpret_cast(ret), mmap_deleter{length}); +} void* posix_thread::start_routine(void* arg) { auto pfunc = reinterpret_cast*>(arg); diff --git a/core/posix.hh b/core/posix.hh index 1e4f372a6d..60e7fbb85a 100644 --- a/core/posix.hh +++ b/core/posix.hh @@ -185,6 +185,15 @@ private: file_desc(int fd) : _fd(fd) {} }; +struct mmap_deleter { + size_t _size; + void operator()(void* ptr) const; +}; + +using mmap_area = std::unique_ptr; + +mmap_area mmap_anonymous(void* addr, size_t length, int prot, int flags); + class posix_thread { // must allocate, since this class is moveable std::unique_ptr> _func;