Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* MZM - memory mapped disk baked toy allocator.
- *
- * Copyright 2010 Salvatore Sanfilippo, BSD licensed. */
- #include <sys/mman.h>
- #include <sys/stat.h>
- #include <fcntl.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #define MEMORYZM_INITIAL_SIZE (4096*1024*8)
- #define MZM_BASE_ADDR 0x10000000
- static unsigned long cursize, curoff;
- /* Returns NULL if there was no pre-existing state.
- * Otherwise the address of the first allocation is returned. */
- void *zmzInit(void) {
- int fd = open("memory.zm",O_CREAT|O_RDWR,0644);
- struct stat buf;
- /* The first allocation is at base address plus a first long value
- * used to store the current offset, plus a second long value that
- * is the header of every allocation. */
- void *retval = (void*)(MZM_BASE_ADDR+(sizeof(long)*2));
- if (fd == -1) {
- perror("opening memory.zm");
- exit(1);
- }
- if (fstat(fd, &buf) == -1) {
- perror("fstat(2) against memory.zm");
- exit(1);
- }
- /* Mmap the file starting from our base address */
- cursize = buf.st_size;
- /* If there was not pre-existing state initalize it, otherwise
- * just read the old offset. */
- printf("cursize: %lu\n",cursize);
- if (cursize == 0) {
- long *x;
- retval = NULL;
- if (ftruncate(fd,MEMORYZM_INITIAL_SIZE) == -1) {
- perror("ftruncate(2) against memory.zm");
- exit(1);
- }
- cursize = MEMORYZM_INITIAL_SIZE;
- printf("Mmap-ping...\n");
- if (mmap((void*)MZM_BASE_ADDR,cursize,PROT_READ|PROT_WRITE,
- MAP_FILE|MAP_FIXED|MAP_SHARED,fd,0) == MAP_FAILED) {
- perror("mmap(2) in MZM");
- exit(1);
- }
- printf("OK\n"); fflush(stdout);
- curoff = (unsigned long) (MZM_BASE_ADDR+sizeof(long));
- x = (long*) MZM_BASE_ADDR;
- *x = curoff;
- } else {
- long *x;
- if (mmap((void*)MZM_BASE_ADDR,cursize,PROT_READ|PROT_WRITE,
- MAP_FILE|MAP_FIXED|MAP_SHARED,fd,0) == MAP_FAILED) {
- perror("mmap(2) in MZM");
- exit(1);
- }
- x = (long*) MZM_BASE_ADDR;
- curoff = *x;
- }
- return retval;
- }
- void *zmalloc(size_t size) {
- unsigned long *x = (unsigned long*) curoff;
- unsigned long *curoffp = (unsigned long*) MZM_BASE_ADDR;
- curoff += sizeof(unsigned long)+size;
- *curoffp = curoff;
- *x = (unsigned long) size;
- x++;
- return x;
- }
- #include <string.h>
- int main(void) {
- void *firstalloc = zmzInit();
- char *p;
- if (firstalloc == NULL) {
- printf("First allocation\n");
- p = zmalloc(7);
- memcpy(p,"foobar\0",7);
- } else {
- printf("Second run\n");
- p = firstalloc;
- }
- printf("String is: %s\n", p);
- return 0;
- }
Add Comment
Please, Sign In to add comment