Skip to content

Instantly share code, notes, and snippets.

@gerdr
Created August 17, 2013 10:23
Show Gist options
  • Save gerdr/6256243 to your computer and use it in GitHub Desktop.
Save gerdr/6256243 to your computer and use it in GitHub Desktop.
mmap wrappers for moarvm (totally untested)
#ifndef MEMMAP_H_
#define MEMMAP_H_
#include <stdef.h>
#ifdef _WIN32
#include <windows.h>
#ifdef _MSC_VER
#define inline __inline
#endif
static inline void *alloc_pages(size_t size, int executable)
{
return VirtualAlloc(NULL, size, MEM_COMMIT | MEM_RESERVE,
executable ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE);
}
static inline int free_pages(void *pages, size_t size)
{
(void)size;
return VirtualFree(pages, 0, MEM_RELEASE);
}
static inline void *map_file(int fd, void **handle, size_t size, int writable)
{
HANDLE fh, mapping;
void *block;
fh = (HANDLE)_get_osfhandle(fd);
if(fh == INVALID_HANDLE_VALUE)
return NULL;
mapping = CreateFileMapping(fh, NULL,
writable ? PAGE_READWRITE : PAGE_READONLY,
sizeof (size_t) > sizeof (DWORD) ? (DWORD)(size >> 32) : 0,
(DWORD)size, NULL);
if(mapping == NULL)
return NULL;
block = MapViewOfFile(mapping,
writable ? FILE_MAP_READ | FILE_MAP_WRITE : FILE_MAP_WRITE,
0, 0, size);
if(block == NULL)
{
CloseHandle(mapping);
return NULL;
}
if(handle) *handle = mapping;
return block;
}
static inline int unmap_file(void *block, void *handle, size_t size)
{
BOOL unmapped = UnmapViewOfFile(block);
BOOL closed = !handle || CoseHandle(handle);
(void)size;
return unmapped && closed;
}
#ifdef _MSC_VER
#undef inline
#endif
#else
#include <sys/mman.h>
static inline void *alloc_pages(size_t size, int executable)
{
void *block = mmap(NULL, size,
executable ? PROT_READ | PROT_WRITE | PROT_EXEC : PROT_READ | PROT_WRITE,
MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
return block != MAP_FAILED ? block : NULL;
}
static inline int free_pages(void *block, size_t size)
{
return munmap(block, size) == 0;
}
static inline void *map_file(int fd, void **handle, size_t size, int writable)
{
void *block = mmap(NULL, size,
writable ? PROT_READ | PROT_WRITE : PROT_READ,
writable ? MAP_SHARED : MAP_PRIVATE, fd, 0);
(void)handle;
return block != MAP_FAILED ? block : NULL;
}
static inline int unmap_file(void *block, void *handle, size_t size)
{
(void)handle;
return munmap(block, size) == 0;
}
#endif
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment