Intrinsicify SpanHelpers.IndexOf(char) (dotnet/coreclr#22505)
[mono-project.git] / support / signal.c
blob503c9c270a0515eccd70edad1c8c87a7d7d8adbc
1 /*
2 * <signal.h> wrapper functions.
4 * Authors:
5 * Jonathan Pryor (jonpryor@vt.edu)
6 * Jonathan Pryor (jpryor@novell.com)
7 * Tim Jenks (tim.jenks@realtimeworlds.com)
9 * Copyright (C) 2004-2005 Jonathan Pryor
10 * Copyright (C) 2008 Novell, Inc.
13 #include <signal.h>
15 #include "map.h"
16 #include "mph.h"
18 #ifndef HOST_WIN32
19 #include <sys/time.h>
20 #include <sys/types.h>
21 #if defined(HAVE_POLL_H)
22 #include <poll.h>
23 #elif defined(HAVE_SYS_POLL_H)
24 #include <sys/poll.h>
25 #endif
26 #include <unistd.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <pthread.h>
30 #include <mono/utils/atomic.h>
31 #include <mono/metadata/appdomain.h>
32 #endif
34 G_BEGIN_DECLS
36 typedef void (*mph_sighandler_t)(int);
37 typedef struct Mono_Unix_UnixSignal_SignalInfo signal_info;
39 #ifndef HOST_WIN32
40 static int count_handlers (int signum);
41 #endif
43 void*
44 Mono_Posix_Stdlib_SIG_DFL (void)
46 return SIG_DFL;
49 void*
50 Mono_Posix_Stdlib_SIG_ERR (void)
52 return SIG_ERR;
55 void*
56 Mono_Posix_Stdlib_SIG_IGN (void)
58 return SIG_IGN;
61 void
62 Mono_Posix_Stdlib_InvokeSignalHandler (int signum, void *handler)
64 mph_sighandler_t _h = (mph_sighandler_t) handler;
65 _h (signum);
68 int Mono_Posix_SIGRTMIN (void)
70 #ifdef SIGRTMIN
71 return SIGRTMIN;
72 #else /* def SIGRTMIN */
73 return -1;
74 #endif /* ndef SIGRTMIN */
77 int Mono_Posix_SIGRTMAX (void)
79 #ifdef SIGRTMAX
80 return SIGRTMAX;
81 #else /* def SIGRTMAX */
82 return -1;
83 #endif /* ndef SIGRTMAX */
86 int Mono_Posix_FromRealTimeSignum (int offset, int *r)
88 if (NULL == r) {
89 errno = EINVAL;
90 return -1;
92 *r = 0;
93 #if defined (SIGRTMIN) && defined (SIGRTMAX)
94 if ((offset < 0) || (SIGRTMIN > SIGRTMAX - offset)) {
95 errno = EINVAL;
96 return -1;
98 *r = SIGRTMIN+offset;
99 return 0;
100 #else /* defined (SIGRTMIN) && defined (SIGRTMAX) */
101 # ifdef ENOSYS
102 errno = ENOSYS;
103 # endif /* ENOSYS */
104 return -1;
105 #endif /* defined (SIGRTMIN) && defined (SIGRTMAX) */
108 #ifndef HOST_WIN32
110 // Atomicity rules: Fields of signal_info read or written by the signal handler
111 // (see UnixSignal.cs) should be read and written using atomic functions.
112 // (For simplicity, we're protecting some things we don't strictly need to.)
114 // Because we are in MonoPosixHelper, we are banned from linking mono.
115 // We can still use atomic.h because that's all inline functions--
116 // unless WAPI_NO_ATOMIC_ASM is defined, in which case atomic.h calls linked functions.
117 #ifndef WAPI_NO_ATOMIC_ASM
118 #define mph_int_get(p) mono_atomic_fetch_add_i32 ((p), 0)
119 #define mph_int_inc(p) mono_atomic_inc_i32 ((p))
120 #define mph_int_dec_test(p) (mono_atomic_dec_i32 ((p)) == 0)
121 #define mph_int_set(p,n) mono_atomic_xchg_i32 ((p), (n))
122 // Pointer, original, new
123 #define mph_int_test_and_set(p,o,n) (o == mono_atomic_cas_i32 ((p), (n), (o)))
124 #elif GLIB_CHECK_VERSION(2,4,0)
125 #define mph_int_get(p) g_atomic_int_get ((p))
126 #define mph_int_inc(p) do {g_atomic_int_inc ((p));} while (0)
127 #define mph_int_dec_test(p) g_atomic_int_dec_and_test ((p))
128 #define mph_int_set(p,n) g_atomic_int_set ((p),(n))
129 #define mph_int_test_and_set(p,o,n) g_atomic_int_compare_and_exchange ((p), (o), (n))
130 #else
131 #error "GLIB 2.4 required because building without ASM atomics"
132 #endif
134 #if HAVE_PSIGNAL
137 * HACK: similar to the mkdtemp one in glib; turns out gcc "helpfully"
138 * shadows system headers with "fixed" versions that omit functions...
139 * in any case, psignal is another victim of poor GNU decisions. Even
140 * then, we may have to do this anyways, as psignal, while present in
141 * libc, isn't in PASE headers - so do it anyways
143 #if defined(_AIX)
144 extern void psignal(int, const char *);
145 #endif
148 Mono_Posix_Syscall_psignal (int sig, const char* s)
150 errno = 0;
151 psignal (sig, s);
152 return errno == 0 ? 0 : -1;
154 #endif /* def HAVE_PSIGNAL */
156 #define NUM_SIGNALS 64
157 static signal_info signals[NUM_SIGNALS];
159 static int acquire_mutex (pthread_mutex_t *mutex)
161 int mr;
162 while ((mr = pthread_mutex_lock (mutex)) == EAGAIN) {
163 /* try to acquire again */
165 if ((mr != 0) && (mr != EDEADLK)) {
166 errno = mr;
167 return -1;
169 return 0;
172 static void release_mutex (pthread_mutex_t *mutex)
174 int mr;
175 while ((mr = pthread_mutex_unlock (mutex)) == EAGAIN) {
176 /* try to release mutex again */
180 static inline int
181 keep_trying (int r)
183 return r == -1 && errno == EINTR;
186 // This tiny ad-hoc read/write lock is needed because of the very specific
187 // synchronization needed between default_handler and teardown_pipes:
188 // - Many default_handlers can be running at once
189 // - The signals_mutex already ensures only one teardown_pipes runs at once
190 // - If teardown_pipes starts while a default_handler is ongoing, it must block
191 // - If default_handler starts while a teardown_pipes is ongoing, it must *not* block
192 // Locks are implemented as ints.
194 // The lock is split into a teardown bit and a handler count (sign bit unused).
195 // There is a teardown running or waiting to run if the teardown bit is set.
196 // There is a handler running if the handler count is nonzero.
197 #define PIPELOCK_TEARDOWN_BIT ( (int)0x40000000 )
198 #define PIPELOCK_COUNT_MASK (~((int)0xC0000000))
199 #define PIPELOCK_GET_COUNT(x) ((x) & PIPELOCK_COUNT_MASK)
200 #define PIPELOCK_INCR_COUNT(x, by) (((x) & PIPELOCK_TEARDOWN_BIT) | (PIPELOCK_GET_COUNT (PIPELOCK_GET_COUNT (x) + (by))))
202 static inline void
203 acquire_pipelock_teardown (int *lock)
205 int lockvalue_draining;
206 // First mark that a teardown is occurring, so handlers will stop entering the lock.
207 while (1) {
208 int lockvalue = mph_int_get (lock);
209 lockvalue_draining = lockvalue | PIPELOCK_TEARDOWN_BIT;
210 if (mph_int_test_and_set (lock, lockvalue, lockvalue_draining))
211 break;
213 // Now wait for all handlers to complete.
214 while (1) {
215 if (0 == PIPELOCK_GET_COUNT (lockvalue_draining))
216 break; // We now hold the lock.
217 // Handler is still running, spin until it completes.
218 sched_yield (); // We can call this because !defined(HOST_WIN32)
219 lockvalue_draining = mph_int_get (lock);
223 static inline void
224 release_pipelock_teardown (int *lock)
226 while (1) {
227 int lockvalue = mph_int_get (lock);
228 int lockvalue_new = lockvalue & ~PIPELOCK_TEARDOWN_BIT;
229 // Technically this can't fail, because we hold both the pipelock and the mutex, but
230 if (mph_int_test_and_set (lock, lockvalue, lockvalue_new))
231 return;
235 // Return 1 for success
236 static inline int
237 acquire_pipelock_handler (int *lock)
239 while (1) {
240 int lockvalue = mph_int_get (lock);
241 if (lockvalue & PIPELOCK_TEARDOWN_BIT) // Final lock is being torn down
242 return 0;
243 int lockvalue_new = PIPELOCK_INCR_COUNT (lockvalue, 1);
244 if (mph_int_test_and_set (lock, lockvalue, lockvalue_new))
245 return 1;
249 static inline void
250 release_pipelock_handler (int *lock)
252 while (1) {
253 int lockvalue = mph_int_get (lock);
254 int lockvalue_new = PIPELOCK_INCR_COUNT (lockvalue, -1);
255 if (mph_int_test_and_set (lock, lockvalue, lockvalue_new))
256 return;
260 // This handler is registered once for each UnixSignal object. A pipe is maintained
261 // for each one; Wait users read at one end of this pipe, and default_handler sends
262 // a write on the pipe for each signal received while the Wait is ongoing.
264 // Notice a fairly unlikely race condition exists here: Because we synchronize with
265 // pipe teardown, but not install/uninstall (in other words, we are only trying to
266 // protect against writing on a closed pipe) it is technically possible a full
267 // uninstall and then an install could complete after signum is checked but before
268 // the remaining instructions execute. In this unlikely case count could be
269 // incremented or a byte written on the wrong signal handler.
270 static void
271 default_handler (int signum)
273 int i;
274 for (i = 0; i < NUM_SIGNALS; ++i) {
275 int fd;
276 signal_info* h = &signals [i];
277 if (mph_int_get (&h->signum) != signum)
278 continue;
280 mph_int_inc (&h->count);
282 if (!acquire_pipelock_handler (&h->pipelock))
283 continue; // Teardown is occurring on this object, no one to send to.
285 fd = mph_int_get (&h->write_fd);
286 if (fd > 0) { // If any listener exists to write to
287 int j,pipecounter;
288 char c = signum; // (Value is meaningless)
289 pipecounter = mph_int_get (&h->pipecnt); // Write one byte per pipe listener
290 for (j = 0; j < pipecounter; ++j) {
291 int r;
292 do { r = write (fd, &c, 1); } while (keep_trying (r));
295 release_pipelock_handler (&h->pipelock);
299 static pthread_mutex_t signals_mutex = PTHREAD_MUTEX_INITIALIZER;
301 // A UnixSignal object is being constructed
302 void*
303 Mono_Unix_UnixSignal_install (int sig)
305 #if defined(HAVE_SIGNAL)
306 int i;
307 signal_info* h = NULL; // signals[] slot to install to
308 int have_handler = 0; // Candidates for signal_info handler fields
309 void* handler = NULL;
311 if (acquire_mutex (&signals_mutex) == -1)
312 return NULL;
314 #if defined (SIGRTMIN) && defined (SIGRTMAX)
315 /*The runtime uses some rt signals for itself so it's important to not override them.*/
316 if (sig >= SIGRTMIN && sig <= SIGRTMAX && count_handlers (sig) == 0) {
317 struct sigaction sinfo;
318 sigaction (sig, NULL, &sinfo);
319 if (sinfo.sa_handler != SIG_DFL || (void*)sinfo.sa_sigaction != (void*)SIG_DFL) {
320 pthread_mutex_unlock (&signals_mutex);
321 errno = EADDRINUSE;
322 return NULL; // This is an rt signal with an existing handler. Bail out.
325 #endif /*defined (SIGRTMIN) && defined (SIGRTMAX)*/
327 // Scan through signals list looking for (1) an unused spot (2) a usable value for handler
328 for (i = 0; i < NUM_SIGNALS; ++i) {
329 int just_installed = 0;
330 // We're still looking for a signal_info spot, and this one is available:
331 if (h == NULL && mph_int_get (&signals [i].signum) == 0) {
332 h = &signals [i];
333 h->handler = signal (sig, default_handler);
334 if (h->handler == SIG_ERR) {
335 h->handler = NULL;
336 h = NULL;
337 break;
339 else {
340 just_installed = 1;
343 // Check if this slot has a "usable" (not installed by this file) handler-to-restore-later:
344 // (On the first signal to be installed, signals [i] will be == h when this happens.)
345 if (!have_handler && (just_installed || mph_int_get (&signals [i].signum) == sig) &&
346 signals [i].handler != default_handler) {
347 have_handler = 1;
348 handler = signals [i].handler;
350 if (h && have_handler) // We have everything we need
351 break;
354 if (h) {
355 // If we reached here without have_handler, this means that default_handler
356 // was set as the signal handler before the first UnixSignal object was installed.
357 g_assert (have_handler);
359 // Overwrite the tenative handler we set a moment ago with a known-usable one
360 h->handler = handler;
361 h->have_handler = 1;
363 mph_int_set (&h->count, 0);
364 mph_int_set (&h->pipecnt, 0);
365 mph_int_set (&h->signum, sig);
368 release_mutex (&signals_mutex);
370 return h;
371 #else
372 g_error ("signal() is not supported by this platform");
373 return 0;
374 #endif
377 static int
378 count_handlers (int signum)
380 int i;
381 int count = 0;
382 for (i = 0; i < NUM_SIGNALS; ++i) {
383 if (mph_int_get (&signals [i].signum) == signum)
384 ++count;
386 return count;
389 // A UnixSignal object is being Disposed
391 Mono_Unix_UnixSignal_uninstall (void* info)
393 #if defined(HAVE_SIGNAL)
394 signal_info* h;
395 int r = -1;
397 if (acquire_mutex (&signals_mutex) == -1)
398 return -1;
400 h = info;
402 if (h == NULL || h < signals || h > &signals [NUM_SIGNALS])
403 errno = EINVAL;
404 else {
405 /* last UnixSignal -- we can unregister */
406 int signum = mph_int_get (&h->signum);
407 if (h->have_handler && count_handlers (signum) == 1) {
408 mph_sighandler_t p = signal (signum, h->handler);
409 if (p != SIG_ERR)
410 r = 0;
411 h->handler = NULL;
412 h->have_handler = 0;
414 mph_int_set (&h->signum, 0);
417 release_mutex (&signals_mutex);
419 return r;
420 #else
421 g_error ("signal() is not supported by this platform");
422 return 0;
423 #endif
426 // Set up a signal_info to begin waiting for signal
427 static int
428 setup_pipes (signal_info** signals, int count, struct pollfd *fd_structs, int *currfd)
430 int i;
431 int r = 0;
432 for (i = 0; i < count; ++i) {
433 signal_info* h;
434 int filedes[2];
436 h = signals [i];
438 if (mph_int_get (&h->pipecnt) == 0) { // First listener for this signal_info
439 if ((r = pipe (filedes)) != 0) {
440 break;
442 mph_int_set (&h->read_fd, filedes [0]);
443 mph_int_set (&h->write_fd, filedes [1]);
445 mph_int_inc (&h->pipecnt);
446 fd_structs[*currfd].fd = mph_int_get (&h->read_fd);
447 fd_structs[*currfd].events = POLLIN;
448 ++(*currfd); // count is verified less than NUM_SIGNALS by caller
450 return r;
453 // Cleanup a signal_info after waiting for signal
454 static void
455 teardown_pipes (signal_info** signals, int count)
457 int i;
458 for (i = 0; i < count; ++i) {
459 signal_info* h = signals [i];
461 if (mph_int_dec_test (&h->pipecnt)) { // Final listener for this signal_info
462 acquire_pipelock_teardown (&h->pipelock);
463 int read_fd = mph_int_get (&h->read_fd);
464 int write_fd = mph_int_get (&h->write_fd);
465 if (read_fd != 0)
466 close (read_fd);
467 if (write_fd != 0)
468 close (write_fd);
469 mph_int_set (&h->read_fd, 0);
470 mph_int_set (&h->write_fd, 0);
471 release_pipelock_teardown (&h->pipelock);
476 // Given pipes set up, wait for a byte to arrive on one of them
477 static int
478 wait_for_any (signal_info** signals, int count, int *currfd, struct pollfd* fd_structs, int timeout, Mono_Posix_RuntimeIsShuttingDown shutting_down)
480 int r, idx;
481 // Poll until one of this signal_info's pipes is ready to read.
482 // Once a second, stop to check if the VM is shutting down.
483 do {
484 struct timeval tv;
485 struct timeval *ptv = NULL;
486 if (timeout != -1) {
487 tv.tv_sec = timeout / 1000;
488 tv.tv_usec = (timeout % 1000)*1000;
489 ptv = &tv;
491 r = poll (fd_structs, count, timeout);
492 } while (keep_trying (r) && !shutting_down ());
494 idx = -1;
495 if (r == 0)
496 idx = timeout;
497 else if (r > 0) { // The pipe[s] are ready to read.
498 int i;
499 for (i = 0; i < count; ++i) {
500 signal_info* h = signals [i];
501 if (fd_structs[i].revents & POLLIN) {
502 int r;
503 char c;
504 do {
505 r = read (mph_int_get (&h->read_fd), &c, 1);
506 } while (keep_trying (r) && !shutting_down ());
507 if (idx == -1)
508 idx = i;
513 return idx;
517 * returns: -1 on error:
518 * timeout on timeout
519 * index into _signals array of signal that was generated on success
522 Mono_Unix_UnixSignal_WaitAny (void** _signals, int count, int timeout /* milliseconds */, Mono_Posix_RuntimeIsShuttingDown shutting_down)
524 int r;
525 int currfd = 0;
526 struct pollfd fd_structs[NUM_SIGNALS];
528 signal_info** signals = (signal_info**) _signals;
530 if (count > NUM_SIGNALS)
531 return -1;
533 if (acquire_mutex (&signals_mutex) == -1)
534 return -1;
536 r = setup_pipes (signals, count, &fd_structs[0], &currfd);
538 release_mutex (&signals_mutex);
540 if (r == 0) {
541 r = wait_for_any (signals, count, &currfd, &fd_structs[0], timeout, shutting_down);
544 if (acquire_mutex (&signals_mutex) == -1)
545 return -1;
547 teardown_pipes (signals, count);
549 release_mutex (&signals_mutex);
551 return r;
554 #endif /* ndef HOST_WIN32 */
557 G_END_DECLS
560 * vim: noexpandtab