xref: /PHP-7.4/sapi/fpm/fpm/fpm_shm.c (revision 1ad08256)
1 	/* (c) 2007,2008 Andrei Nigmatulin, Jerome Loyet */
2 
3 #include <sys/mman.h>
4 #include <errno.h>
5 #include <string.h>
6 
7 #include "fpm_shm.h"
8 #include "zlog.h"
9 
10 
11 /* MAP_ANON is deprecated, but not in macosx */
12 #if defined(MAP_ANON) && !defined(MAP_ANONYMOUS)
13 #define MAP_ANONYMOUS MAP_ANON
14 #endif
15 
16 static size_t fpm_shm_size = 0;
17 
fpm_shm_alloc(size_t size)18 void *fpm_shm_alloc(size_t size) /* {{{ */
19 {
20 	void *mem;
21 
22 	mem = mmap(0, size, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_SHARED, -1, 0);
23 
24 #ifdef MAP_FAILED
25 	if (mem == MAP_FAILED) {
26 		zlog(ZLOG_SYSERROR, "unable to allocate %zu bytes in shared memory: %s", size, strerror(errno));
27 		return NULL;
28 	}
29 #endif
30 
31 	if (!mem) {
32 		zlog(ZLOG_SYSERROR, "unable to allocate %zu bytes in shared memory", size);
33 		return NULL;
34 	}
35 
36 	fpm_shm_size += size;
37 	return mem;
38 }
39 /* }}} */
40 
fpm_shm_free(void * mem,size_t size)41 int fpm_shm_free(void *mem, size_t size) /* {{{ */
42 {
43 	if (!mem) {
44 		zlog(ZLOG_ERROR, "mem is NULL");
45 		return 0;
46 	}
47 
48 	if (munmap(mem, size) == -1) {
49 		zlog(ZLOG_SYSERROR, "Unable to free shm");
50 		return 0;
51 	}
52 
53 	if (fpm_shm_size - size > 0) {
54 		fpm_shm_size -= size;
55 	} else {
56 		fpm_shm_size = 0;
57 	}
58 
59 	return 1;
60 }
61 /* }}} */
62 
fpm_shm_get_size_allocated()63 size_t fpm_shm_get_size_allocated() /* {{{*/
64 {
65 	return fpm_shm_size;
66 }
67 /* }}} */
68