Last active
July 20, 2022 07:45
-
-
Save aolo2/e4cd36cf9420401fef7f559ae2b930fa to your computer and use it in GitHub Desktop.
Stable growable array based on virtual memory (linux)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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