forked from blanham/liballoc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
linux.c
64 lines (47 loc) · 1.05 KB
/
linux.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <sys/mman.h>
#include <unistd.h>
#if !defined(MAP_ANONYMOUS) && defined(MAP_ANON)
# define MAP_ANONYMOUS MAP_ANON
#endif
#if !defined(MAP_FAILED)
# define MAP_FAILED ((char*)-1)
#endif
#ifndef MAP_NORESERVE
# ifdef MAP_AUTORESRV
# define MAP_NORESERVE MAP_AUTORESRV
# else
# define MAP_NORESERVE 0
# endif
#endif
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
static int page_size = -1;
int liballoc_lock()
{
pthread_mutex_lock( &mutex );
return 0;
}
int liballoc_unlock()
{
pthread_mutex_unlock( &mutex );
return 0;
}
void* liballoc_alloc( int pages )
{
if ( page_size < 0 ) page_size = getpagesize();
unsigned int size = pages * page_size;
char *p2 = (char*)mmap(0, size, PROT_NONE, MAP_PRIVATE|MAP_NORESERVE|MAP_ANONYMOUS, -1, 0);
if ( p2 == MAP_FAILED) return NULL;
if(mprotect(p2, size, PROT_READ|PROT_WRITE) != 0)
{
munmap(p2, size);
return NULL;
}
return p2;
}
int liballoc_free( void* ptr, int pages )
{
return munmap( ptr, pages * page_size );
}