Skip to content

Instantly share code, notes, and snippets.

@aolo2
Last active July 20, 2022 07:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aolo2/e4cd36cf9420401fef7f559ae2b930fa to your computer and use it in GitHub Desktop.
Save aolo2/e4cd36cf9420401fef7f559ae2b930fa to your computer and use it in GitHub Desktop.
Stable growable array based on virtual memory (linux)
#include <stdint.h>
#include <stdio.h>
#include <sys/mman.h>
struct bc_vm {
uint8_t *base;
uint64_t size;
uint64_t commited;
};
static struct bc_vm
mapping_reserve(uint64_t size)
{
struct bc_vm result = { 0 };
uint8_t *region = mmap(NULL, size, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); /* PROT_NONE + MAP_ANONYMOUS = do not commit */
if (region == MAP_FAILED) {
perror("mmap (reserve)");
return(result);
}
result.base = region;
result.size = size;
result.commited = 0;
return(result);
}
static int
mapping_commit(struct bc_vm *vm, uint64_t offset, uint64_t size)
{
if (offset + size > vm->size) {
return(1);
}
if (mprotect(vm->base + offset, size, PROT_READ | PROT_WRITE)) {
perror("mprotect (commit)");
return(1);
}
return(0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment