split out low-level memory mapping wrappers

This commit is contained in:
Daniel Micay 2018-08-29 00:53:12 -04:00
parent 8b42e8c3d6
commit 58d929c0f0
4 changed files with 47 additions and 29 deletions

View File

@ -2,12 +2,13 @@ CPPFLAGS := -D_GNU_SOURCE
CFLAGS := -std=c11 -Wall -Wextra -O2 -flto -fPIC -fvisibility=hidden -pedantic
LDFLAGS := -Wl,--as-needed,-z,defs,-z,relro,-z,now
LDLIBS := -lpthread
OBJECTS := chacha.o malloc.o random.o util.o
OBJECTS := chacha.o malloc.o memory.o random.o util.o
hardened_malloc.so: $(OBJECTS)
$(CC) $(CFLAGS) $(LDFLAGS) -shared $^ $(LDLIBS) -o $@
malloc.o: malloc.c malloc.h random.h util.h
malloc.o: malloc.c malloc.h memory.h random.h util.h
memory.o: memory.c memory.h util.h
random.o: random.c random.h chacha.h util.h
util.o: util.c util.h
chacha.o: chacha.c chacha.h

View File

@ -15,6 +15,7 @@
#include "libdivide.h"
#include "malloc.h"
#include "memory.h"
#include "random.h"
#include "util.h"
@ -28,33 +29,6 @@ static_assert(sizeof(void *) == 8, "64-bit only");
#define MIN_ALIGN 16
#define ALIGNMENT_CEILING(s, alignment) (((s) + (alignment - 1)) & ((~(alignment)) + 1))
static void *memory_map(size_t size) {
void *p = mmap(NULL, size, PROT_NONE, MAP_ANONYMOUS|MAP_PRIVATE, -1, 0);
if (unlikely(p == MAP_FAILED)) {
if (errno != ENOMEM) {
fatal_error("non-ENOMEM mmap failure");
}
return NULL;
}
return p;
}
static int memory_unmap(void *ptr, size_t size) {
int ret = munmap(ptr, size);
if (unlikely(ret) && errno != ENOMEM) {
fatal_error("non-ENOMEM munmap failure");
}
return ret;
}
static int memory_protect(void *ptr, size_t size, int prot) {
int ret = mprotect(ptr, size, prot);
if (unlikely(ret) && errno != ENOMEM) {
fatal_error("non-ENOMEM mprotect failure");
}
return ret;
}
static void *allocate_pages(size_t usable_size, size_t guard_size, bool unprotect) {
usable_size = PAGE_CEILING(usable_size);

33
memory.c Normal file
View File

@ -0,0 +1,33 @@
#include <errno.h>
#include <sys/mman.h>
#include "memory.h"
#include "util.h"
void *memory_map(size_t size) {
void *p = mmap(NULL, size, PROT_NONE, MAP_ANONYMOUS|MAP_PRIVATE, -1, 0);
if (unlikely(p == MAP_FAILED)) {
if (errno != ENOMEM) {
fatal_error("non-ENOMEM mmap failure");
}
return NULL;
}
return p;
}
int memory_unmap(void *ptr, size_t size) {
int ret = munmap(ptr, size);
if (unlikely(ret) && errno != ENOMEM) {
fatal_error("non-ENOMEM munmap failure");
}
return ret;
}
int memory_protect(void *ptr, size_t size, int prot) {
int ret = mprotect(ptr, size, prot);
if (unlikely(ret) && errno != ENOMEM) {
fatal_error("non-ENOMEM mprotect failure");
}
return ret;
}

10
memory.h Normal file
View File

@ -0,0 +1,10 @@
#ifndef MEMORY_H
#define MEMORY_H
#include <stddef.h>
void *memory_map(size_t size);
int memory_unmap(void *ptr, size_t size);
int memory_protect(void *ptr, size_t size, int prot);
#endif