xref: /PHP-8.0/ext/sysvsem/sysvsem.c (revision b63ea104)
1 /*
2    +----------------------------------------------------------------------+
3    | Copyright (c) The PHP Group                                          |
4    +----------------------------------------------------------------------+
5    | This source file is subject to version 3.01 of the PHP license,      |
6    | that is bundled with this package in the file LICENSE, and is        |
7    | available through the world-wide-web at the following url:           |
8    | http://www.php.net/license/3_01.txt                                  |
9    | If you did not receive a copy of the PHP license and are unable to   |
10    | obtain it through the world-wide-web, please send a note to          |
11    | license@php.net so we can mail you a copy immediately.               |
12    +----------------------------------------------------------------------+
13    | Authors: Tom May <tom@go2net.com>                                    |
14    |          Gavin Sherry <gavin@linuxworld.com.au>                      |
15    +----------------------------------------------------------------------+
16  */
17 
18 #ifdef HAVE_CONFIG_H
19 #include "config.h"
20 #endif
21 
22 #include "php.h"
23 
24 #ifdef HAVE_SYSVSEM
25 
26 #include <sys/types.h>
27 #include <sys/ipc.h>
28 #include <sys/sem.h>
29 #include <errno.h>
30 
31 #include "sysvsem_arginfo.h"
32 #include "php_sysvsem.h"
33 #include "ext/standard/info.h"
34 #include "Zend/zend_interfaces.h"
35 
36 #if !HAVE_SEMUN
37 
38 union semun {
39 	int val;                    /* value for SETVAL */
40 	struct semid_ds *buf;       /* buffer for IPC_STAT, IPC_SET */
41 	unsigned short int *array;  /* array for GETALL, SETALL */
42 	struct seminfo *__buf;      /* buffer for IPC_INFO */
43 };
44 
45 #undef HAVE_SEMUN
46 #define HAVE_SEMUN 1
47 
48 #endif
49 
50 /* {{{ sysvsem_module_entry */
51 zend_module_entry sysvsem_module_entry = {
52 	STANDARD_MODULE_HEADER,
53 	"sysvsem",
54 	ext_functions,
55 	PHP_MINIT(sysvsem),
56 	NULL,
57 	NULL,
58 	NULL,
59 	PHP_MINFO(sysvsem),
60 	PHP_SYSVSEM_VERSION,
61 	STANDARD_MODULE_PROPERTIES
62 };
63 /* }}} */
64 
65 #ifdef COMPILE_DL_SYSVSEM
66 ZEND_GET_MODULE(sysvsem)
67 #endif
68 
69 /* Semaphore functions using System V semaphores.  Each semaphore
70  * actually consists of three semaphores allocated as a unit under the
71  * same key.  Semaphore 0 (SYSVSEM_SEM) is the actual semaphore, it is
72  * initialized to max_acquire and decremented as processes acquire it.
73  * The value of semaphore 1 (SYSVSEM_USAGE) is a count of the number
74  * of processes using the semaphore.  After calling semget(), if a
75  * process finds that the usage count is 1, it will set the value of
76  * SYSVSEM_SEM to max_acquire.  This allows max_acquire to be set and
77  * track the PHP code without having a global init routine or external
78  * semaphore init code.  Except see the bug regarding a race condition
79  * php_sysvsem_get().  Semaphore 2 (SYSVSEM_SETVAL) serializes the
80  * calls to GETVAL SYSVSEM_USAGE and SETVAL SYSVSEM_SEM.  It can be
81  * acquired only when it is zero.
82  */
83 
84 #define SYSVSEM_SEM		0
85 #define SYSVSEM_USAGE	1
86 #define SYSVSEM_SETVAL	2
87 
88 /* SysvSemaphore class */
89 
90 zend_class_entry *sysvsem_ce;
91 static zend_object_handlers sysvsem_object_handlers;
92 
sysvsem_from_obj(zend_object * obj)93 static inline sysvsem_sem *sysvsem_from_obj(zend_object *obj) {
94 	return (sysvsem_sem *)((char *)(obj) - XtOffsetOf(sysvsem_sem, std));
95 }
96 
97 #define Z_SYSVSEM_P(zv) sysvsem_from_obj(Z_OBJ_P(zv))
98 
sysvsem_create_object(zend_class_entry * class_type)99 static zend_object *sysvsem_create_object(zend_class_entry *class_type) {
100 	sysvsem_sem *intern = zend_object_alloc(sizeof(sysvsem_sem), class_type);
101 
102 	zend_object_std_init(&intern->std, class_type);
103 	object_properties_init(&intern->std, class_type);
104 	intern->std.handlers = &sysvsem_object_handlers;
105 
106 	return &intern->std;
107 }
108 
sysvsem_get_constructor(zend_object * object)109 static zend_function *sysvsem_get_constructor(zend_object *object) {
110 	zend_throw_error(NULL, "Cannot directly construct SysvSemaphore, use sem_get() instead");
111 	return NULL;
112 }
113 
sysvsem_free_obj(zend_object * object)114 static void sysvsem_free_obj(zend_object *object)
115 {
116 	sysvsem_sem *sem_ptr = sysvsem_from_obj(object);
117 	struct sembuf sop[2];
118 	int opcount = 1;
119 
120 	/*
121 	 * if count == -1, semaphore has been removed
122 	 * Need better way to handle this
123 	 */
124 	if (sem_ptr->count == -1 || !sem_ptr->auto_release) {
125 		zend_object_std_dtor(&sem_ptr->std);
126 		return;
127 	}
128 	/* Decrement the usage count. */
129 
130 	sop[0].sem_num = SYSVSEM_USAGE;
131 	sop[0].sem_op  = -1;
132 	sop[0].sem_flg = SEM_UNDO;
133 
134 	/* Release the semaphore if it has been acquired but not released. */
135 
136 	if (sem_ptr->count) {
137 
138 		sop[1].sem_num = SYSVSEM_SEM;
139 		sop[1].sem_op  = sem_ptr->count;
140 		sop[1].sem_flg = SEM_UNDO;
141 
142 		opcount++;
143 	}
144 
145 	semop(sem_ptr->semid, sop, opcount);
146 
147 	zend_object_std_dtor(&sem_ptr->std);
148 }
149 /* }}} */
150 
151 /* {{{ PHP_MINIT_FUNCTION */
PHP_MINIT_FUNCTION(sysvsem)152 PHP_MINIT_FUNCTION(sysvsem)
153 {
154 	zend_class_entry ce;
155 	INIT_CLASS_ENTRY(ce, "SysvSemaphore", class_SysvSemaphore_methods);
156 	sysvsem_ce = zend_register_internal_class(&ce);
157 	sysvsem_ce->ce_flags |= ZEND_ACC_FINAL | ZEND_ACC_NO_DYNAMIC_PROPERTIES;
158 	sysvsem_ce->create_object = sysvsem_create_object;
159 	sysvsem_ce->serialize = zend_class_serialize_deny;
160 	sysvsem_ce->unserialize = zend_class_unserialize_deny;
161 
162 	memcpy(&sysvsem_object_handlers, &std_object_handlers, sizeof(zend_object_handlers));
163 	sysvsem_object_handlers.offset = XtOffsetOf(sysvsem_sem, std);
164 	sysvsem_object_handlers.free_obj = sysvsem_free_obj;
165 	sysvsem_object_handlers.get_constructor = sysvsem_get_constructor;
166 	sysvsem_object_handlers.clone_obj = NULL;
167 	sysvsem_object_handlers.compare = zend_objects_not_comparable;
168 
169 	return SUCCESS;
170 }
171 /* }}} */
172 
173 /* {{{ PHP_MINFO_FUNCTION */
PHP_MINFO_FUNCTION(sysvsem)174 PHP_MINFO_FUNCTION(sysvsem)
175 {
176 	php_info_print_table_start();
177 	php_info_print_table_row(2, "sysvsem support", "enabled");
178 	php_info_print_table_end();
179 }
180 /* }}} */
181 
182 #define SETVAL_WANTS_PTR
183 
184 #if defined(_AIX)
185 #undef SETVAL_WANTS_PTR
186 #endif
187 
188 /* {{{ Return an id for the semaphore with the given key, and allow max_acquire (default 1) processes to acquire it simultaneously */
PHP_FUNCTION(sem_get)189 PHP_FUNCTION(sem_get)
190 {
191 	zend_long key, max_acquire = 1, perm = 0666;
192 	zend_bool auto_release = 1;
193 	int semid;
194 	struct sembuf sop[3];
195 	int count;
196 	sysvsem_sem *sem_ptr;
197 
198 	if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS(), "l|llb", &key, &max_acquire, &perm, &auto_release)) {
199 		RETURN_THROWS();
200 	}
201 
202 	/* Get/create the semaphore.  Note that we rely on the semaphores
203 	 * being zeroed when they are created.  Despite the fact that
204 	 * the(?)  Linux semget() man page says they are not initialized,
205 	 * the kernel versions 2.0.x and 2.1.z do in fact zero them.
206 	 */
207 
208 	semid = semget(key, 3, perm|IPC_CREAT);
209 	if (semid == -1) {
210 		php_error_docref(NULL, E_WARNING, "Failed for key 0x" ZEND_XLONG_FMT ": %s", key, strerror(errno));
211 		RETURN_FALSE;
212 	}
213 
214 	/* Find out how many processes are using this semaphore.  Note
215 	 * that on Linux (at least) there is a race condition here because
216 	 * semaphore undo on process exit is not atomic, so we could
217 	 * acquire SYSVSEM_SETVAL before a crashed process has decremented
218 	 * SYSVSEM_USAGE in which case count will be greater than it
219 	 * should be and we won't set max_acquire.  Fortunately this
220 	 * doesn't actually matter in practice.
221 	 */
222 
223 	/* Wait for sem 1 to be zero . . . */
224 
225 	sop[0].sem_num = SYSVSEM_SETVAL;
226 	sop[0].sem_op  = 0;
227 	sop[0].sem_flg = 0;
228 
229 	/* . . . and increment it so it becomes non-zero . . . */
230 
231 	sop[1].sem_num = SYSVSEM_SETVAL;
232 	sop[1].sem_op  = 1;
233 	sop[1].sem_flg = SEM_UNDO;
234 
235 	/* . . . and increment the usage count. */
236 
237 	sop[2].sem_num = SYSVSEM_USAGE;
238 	sop[2].sem_op  = 1;
239 	sop[2].sem_flg = SEM_UNDO;
240 	while (semop(semid, sop, 3) == -1) {
241 		if (errno != EINTR) {
242 			php_error_docref(NULL, E_WARNING, "Failed acquiring SYSVSEM_SETVAL for key 0x" ZEND_XLONG_FMT ": %s", key, strerror(errno));
243 			break;
244 		}
245 	}
246 
247 	/* Get the usage count. */
248 	count = semctl(semid, SYSVSEM_USAGE, GETVAL, NULL);
249 	if (count == -1) {
250 		php_error_docref(NULL, E_WARNING, "Failed for key 0x" ZEND_XLONG_FMT ": %s", key, strerror(errno));
251 	}
252 
253 	/* If we are the only user, then take this opportunity to set the max. */
254 
255 	if (count == 1) {
256 #if HAVE_SEMUN
257 		/* This is correct for Linux which has union semun. */
258 		union semun semarg;
259 		semarg.val = max_acquire;
260 		if (semctl(semid, SYSVSEM_SEM, SETVAL, semarg) == -1) {
261 			php_error_docref(NULL, E_WARNING, "Failed for key 0x" ZEND_XLONG_FMT ": %s", key, strerror(errno));
262 		}
263 #elif defined(SETVAL_WANTS_PTR)
264 		/* This is correct for Solaris 2.6 which does not have union semun. */
265 		if (semctl(semid, SYSVSEM_SEM, SETVAL, &max_acquire) == -1) {
266 			php_error_docref(NULL, E_WARNING, "Failed for key 0x%lx: %s", key, strerror(errno));
267 		}
268 #else
269 		/* This works for i.e. AIX */
270 		if (semctl(semid, SYSVSEM_SEM, SETVAL, max_acquire) == -1) {
271 			php_error_docref(NULL, E_WARNING, "Failed for key 0x%lx: %s", key, strerror(errno));
272 		}
273 #endif
274 	}
275 
276 	/* Set semaphore 1 back to zero. */
277 
278 	sop[0].sem_num = SYSVSEM_SETVAL;
279 	sop[0].sem_op  = -1;
280 	sop[0].sem_flg = SEM_UNDO;
281 	while (semop(semid, sop, 1) == -1) {
282 		if (errno != EINTR) {
283 			php_error_docref(NULL, E_WARNING, "Failed releasing SYSVSEM_SETVAL for key 0x" ZEND_XLONG_FMT ": %s", key, strerror(errno));
284 			break;
285 		}
286 	}
287 
288 	object_init_ex(return_value, sysvsem_ce);
289 
290 	sem_ptr = Z_SYSVSEM_P(return_value);
291 	sem_ptr->key   = key;
292 	sem_ptr->semid = semid;
293 	sem_ptr->count = 0;
294 	sem_ptr->auto_release = (int) auto_release;
295 }
296 /* }}} */
297 
298 /* {{{ php_sysvsem_semop */
php_sysvsem_semop(INTERNAL_FUNCTION_PARAMETERS,int acquire)299 static void php_sysvsem_semop(INTERNAL_FUNCTION_PARAMETERS, int acquire)
300 {
301 	zval *arg_id;
302 	zend_bool nowait = 0;
303 	sysvsem_sem *sem_ptr;
304 	struct sembuf sop;
305 
306 	if (acquire) {
307 		if (zend_parse_parameters(ZEND_NUM_ARGS(), "O|b", &arg_id, sysvsem_ce, &nowait) == FAILURE) {
308 			RETURN_THROWS();
309 		}
310 	} else {
311 		if (zend_parse_parameters(ZEND_NUM_ARGS(), "O", &arg_id, sysvsem_ce) == FAILURE) {
312 			RETURN_THROWS();
313 		}
314 	}
315 
316 	sem_ptr = Z_SYSVSEM_P(arg_id);
317 
318 	if (!acquire && sem_ptr->count == 0) {
319 		php_error_docref(NULL, E_WARNING, "SysV semaphore for key 0x%x is not currently acquired", sem_ptr->key);
320 		RETURN_FALSE;
321 	}
322 
323 	sop.sem_num = SYSVSEM_SEM;
324 	sop.sem_op  = acquire ? -1 : 1;
325 	sop.sem_flg = SEM_UNDO | (nowait ? IPC_NOWAIT : 0);
326 
327 	while (semop(sem_ptr->semid, &sop, 1) == -1) {
328 		if (errno != EINTR) {
329 			if (errno != EAGAIN) {
330 				php_error_docref(NULL, E_WARNING, "Failed to %s key 0x%x: %s", acquire ? "acquire" : "release", sem_ptr->key, strerror(errno));
331 			}
332 			RETURN_FALSE;
333 		}
334 	}
335 
336 	sem_ptr->count -= acquire ? -1 : 1;
337 	RETURN_TRUE;
338 }
339 /* }}} */
340 
341 /* {{{ Acquires the semaphore with the given id, blocking if necessary */
PHP_FUNCTION(sem_acquire)342 PHP_FUNCTION(sem_acquire)
343 {
344 	php_sysvsem_semop(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1);
345 }
346 /* }}} */
347 
348 /* {{{ Releases the semaphore with the given id */
PHP_FUNCTION(sem_release)349 PHP_FUNCTION(sem_release)
350 {
351 	php_sysvsem_semop(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0);
352 }
353 /* }}} */
354 
355 /* {{{ Removes semaphore from Unix systems */
356 
357 /*
358  * contributed by Gavin Sherry gavin@linuxworld.com.au
359  * Fri Mar 16 00:50:13 EST 2001
360  */
361 
PHP_FUNCTION(sem_remove)362 PHP_FUNCTION(sem_remove)
363 {
364 	zval *arg_id;
365 	sysvsem_sem *sem_ptr;
366 #if HAVE_SEMUN
367 	union semun un;
368 	struct semid_ds buf;
369 #endif
370 
371 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "O", &arg_id, sysvsem_ce) == FAILURE) {
372 		RETURN_THROWS();
373 	}
374 
375 	sem_ptr = Z_SYSVSEM_P(arg_id);
376 
377 #if HAVE_SEMUN
378 	un.buf = &buf;
379 	if (semctl(sem_ptr->semid, 0, IPC_STAT, un) < 0) {
380 #else
381 	if (semctl(sem_ptr->semid, 0, IPC_STAT, NULL) < 0) {
382 #endif
383 		php_error_docref(NULL, E_WARNING, "SysV semaphore for key 0x%x does not (any longer) exist", sem_ptr->key);
384 		RETURN_FALSE;
385 	}
386 
387 #if HAVE_SEMUN
388 	if (semctl(sem_ptr->semid, 0, IPC_RMID, un) < 0) {
389 #else
390 	if (semctl(sem_ptr->semid, 0, IPC_RMID, NULL) < 0) {
391 #endif
392 		php_error_docref(NULL, E_WARNING, "Failed for SysV semaphore for key 0x%x: %s", sem_ptr->key, strerror(errno));
393 		RETURN_FALSE;
394 	}
395 
396 	/* let release_sysvsem_sem know we have removed
397 	 * the semaphore to avoid issues with releasing.
398 	 */
399 
400 	sem_ptr->count = -1;
401 	RETURN_TRUE;
402 }
403 
404 /* }}} */
405 
406 #endif /* HAVE_SYSVSEM */
407