[w32handle] Initialize them earlier
[mono-project.git] / support / signal.c
blob993e2e216618b3c0aa0a9773707f48eef836873d
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) InterlockedExchangeAdd ((p), 0)
119 #define mph_int_inc(p) InterlockedIncrement ((p))
120 #define mph_int_dec_test(p) (InterlockedDecrement ((p)) == 0)
121 #define mph_int_set(p,n) InterlockedExchange ((p), (n))
122 // Pointer, original, new
123 #define mph_int_test_and_set(p,o,n) (o == InterlockedCompareExchange ((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
136 Mono_Posix_Syscall_psignal (int sig, const char* s)
138 errno = 0;
139 psignal (sig, s);
140 return errno == 0 ? 0 : -1;
142 #endif /* def HAVE_PSIGNAL */
144 #define NUM_SIGNALS 64
145 static signal_info signals[NUM_SIGNALS];
147 static int acquire_mutex (pthread_mutex_t *mutex)
149 int mr;
150 while ((mr = pthread_mutex_lock (mutex)) == EAGAIN) {
151 /* try to acquire again */
153 if ((mr != 0) && (mr != EDEADLK)) {
154 errno = mr;
155 return -1;
157 return 0;
160 static void release_mutex (pthread_mutex_t *mutex)
162 int mr;
163 while ((mr = pthread_mutex_unlock (mutex)) == EAGAIN) {
164 /* try to release mutex again */
168 static inline int
169 keep_trying (int r)
171 return r == -1 && errno == EINTR;
174 // This tiny ad-hoc read/write lock is needed because of the very specific
175 // synchronization needed between default_handler and teardown_pipes:
176 // - Many default_handlers can be running at once
177 // - The signals_mutex already ensures only one teardown_pipes runs at once
178 // - If teardown_pipes starts while a default_handler is ongoing, it must block
179 // - If default_handler starts while a teardown_pipes is ongoing, it must *not* block
180 // Locks are implemented as ints.
182 // The lock is split into a teardown bit and a handler count (sign bit unused).
183 // There is a teardown running or waiting to run if the teardown bit is set.
184 // There is a handler running if the handler count is nonzero.
185 #define PIPELOCK_TEARDOWN_BIT ( (int)0x40000000 )
186 #define PIPELOCK_COUNT_MASK (~((int)0xC0000000))
187 #define PIPELOCK_GET_COUNT(x) ((x) & PIPELOCK_COUNT_MASK)
188 #define PIPELOCK_INCR_COUNT(x, by) (((x) & PIPELOCK_TEARDOWN_BIT) | (PIPELOCK_GET_COUNT (PIPELOCK_GET_COUNT (x) + (by))))
190 static inline void
191 acquire_pipelock_teardown (int *lock)
193 int lockvalue_draining;
194 // First mark that a teardown is occurring, so handlers will stop entering the lock.
195 while (1) {
196 int lockvalue = mph_int_get (lock);
197 lockvalue_draining = lockvalue | PIPELOCK_TEARDOWN_BIT;
198 if (mph_int_test_and_set (lock, lockvalue, lockvalue_draining))
199 break;
201 // Now wait for all handlers to complete.
202 while (1) {
203 if (0 == PIPELOCK_GET_COUNT (lockvalue_draining))
204 break; // We now hold the lock.
205 // Handler is still running, spin until it completes.
206 sched_yield (); // We can call this because !defined(HOST_WIN32)
207 lockvalue_draining = mph_int_get (lock);
211 static inline void
212 release_pipelock_teardown (int *lock)
214 while (1) {
215 int lockvalue = mph_int_get (lock);
216 int lockvalue_new = lockvalue & ~PIPELOCK_TEARDOWN_BIT;
217 // Technically this can't fail, because we hold both the pipelock and the mutex, but
218 if (mph_int_test_and_set (lock, lockvalue, lockvalue_new))
219 return;
223 // Return 1 for success
224 static inline int
225 acquire_pipelock_handler (int *lock)
227 while (1) {
228 int lockvalue = mph_int_get (lock);
229 if (lockvalue & PIPELOCK_TEARDOWN_BIT) // Final lock is being torn down
230 return 0;
231 int lockvalue_new = PIPELOCK_INCR_COUNT (lockvalue, 1);
232 if (mph_int_test_and_set (lock, lockvalue, lockvalue_new))
233 return 1;
237 static inline void
238 release_pipelock_handler (int *lock)
240 while (1) {
241 int lockvalue = mph_int_get (lock);
242 int lockvalue_new = PIPELOCK_INCR_COUNT (lockvalue, -1);
243 if (mph_int_test_and_set (lock, lockvalue, lockvalue_new))
244 return;
248 // This handler is registered once for each UnixSignal object. A pipe is maintained
249 // for each one; Wait users read at one end of this pipe, and default_handler sends
250 // a write on the pipe for each signal received while the Wait is ongoing.
252 // Notice a fairly unlikely race condition exists here: Because we synchronize with
253 // pipe teardown, but not install/uninstall (in other words, we are only trying to
254 // protect against writing on a closed pipe) it is technically possible a full
255 // uninstall and then an install could complete after signum is checked but before
256 // the remaining instructions execute. In this unlikely case count could be
257 // incremented or a byte written on the wrong signal handler.
258 static void
259 default_handler (int signum)
261 int i;
262 for (i = 0; i < NUM_SIGNALS; ++i) {
263 int fd;
264 signal_info* h = &signals [i];
265 if (mph_int_get (&h->signum) != signum)
266 continue;
268 mph_int_inc (&h->count);
270 if (!acquire_pipelock_handler (&h->pipelock))
271 continue; // Teardown is occurring on this object, no one to send to.
273 fd = mph_int_get (&h->write_fd);
274 if (fd > 0) { // If any listener exists to write to
275 int j,pipecounter;
276 char c = signum; // (Value is meaningless)
277 pipecounter = mph_int_get (&h->pipecnt); // Write one byte per pipe listener
278 for (j = 0; j < pipecounter; ++j) {
279 int r;
280 do { r = write (fd, &c, 1); } while (keep_trying (r));
283 release_pipelock_handler (&h->pipelock);
287 static pthread_mutex_t signals_mutex = PTHREAD_MUTEX_INITIALIZER;
289 // A UnixSignal object is being constructed
290 void*
291 Mono_Unix_UnixSignal_install (int sig)
293 #if defined(HAVE_SIGNAL)
294 int i;
295 signal_info* h = NULL; // signals[] slot to install to
296 int have_handler = 0; // Candidates for signal_info handler fields
297 void* handler = NULL;
299 if (acquire_mutex (&signals_mutex) == -1)
300 return NULL;
302 #if defined (SIGRTMIN) && defined (SIGRTMAX)
303 /*The runtime uses some rt signals for itself so it's important to not override them.*/
304 if (sig >= SIGRTMIN && sig <= SIGRTMAX && count_handlers (sig) == 0) {
305 struct sigaction sinfo;
306 sigaction (sig, NULL, &sinfo);
307 if (sinfo.sa_handler != SIG_DFL || (void*)sinfo.sa_sigaction != (void*)SIG_DFL) {
308 pthread_mutex_unlock (&signals_mutex);
309 errno = EADDRINUSE;
310 return NULL; // This is an rt signal with an existing handler. Bail out.
313 #endif /*defined (SIGRTMIN) && defined (SIGRTMAX)*/
315 // Scan through signals list looking for (1) an unused spot (2) a usable value for handler
316 for (i = 0; i < NUM_SIGNALS; ++i) {
317 int just_installed = 0;
318 // We're still looking for a signal_info spot, and this one is available:
319 if (h == NULL && mph_int_get (&signals [i].signum) == 0) {
320 h = &signals [i];
321 h->handler = signal (sig, default_handler);
322 if (h->handler == SIG_ERR) {
323 h->handler = NULL;
324 h = NULL;
325 break;
327 else {
328 just_installed = 1;
331 // Check if this slot has a "usable" (not installed by this file) handler-to-restore-later:
332 // (On the first signal to be installed, signals [i] will be == h when this happens.)
333 if (!have_handler && (just_installed || mph_int_get (&signals [i].signum) == sig) &&
334 signals [i].handler != default_handler) {
335 have_handler = 1;
336 handler = signals [i].handler;
338 if (h && have_handler) // We have everything we need
339 break;
342 if (h) {
343 // If we reached here without have_handler, this means that default_handler
344 // was set as the signal handler before the first UnixSignal object was installed.
345 g_assert (have_handler);
347 // Overwrite the tenative handler we set a moment ago with a known-usable one
348 h->handler = handler;
349 h->have_handler = 1;
351 mph_int_set (&h->count, 0);
352 mph_int_set (&h->pipecnt, 0);
353 mph_int_set (&h->signum, sig);
356 release_mutex (&signals_mutex);
358 return h;
359 #else
360 g_error ("signal() is not supported by this platform");
361 return 0;
362 #endif
365 static int
366 count_handlers (int signum)
368 int i;
369 int count = 0;
370 for (i = 0; i < NUM_SIGNALS; ++i) {
371 if (mph_int_get (&signals [i].signum) == signum)
372 ++count;
374 return count;
377 // A UnixSignal object is being Disposed
379 Mono_Unix_UnixSignal_uninstall (void* info)
381 #if defined(HAVE_SIGNAL)
382 signal_info* h;
383 int r = -1;
385 if (acquire_mutex (&signals_mutex) == -1)
386 return -1;
388 h = info;
390 if (h == NULL || h < signals || h > &signals [NUM_SIGNALS])
391 errno = EINVAL;
392 else {
393 /* last UnixSignal -- we can unregister */
394 int signum = mph_int_get (&h->signum);
395 if (h->have_handler && count_handlers (signum) == 1) {
396 mph_sighandler_t p = signal (signum, h->handler);
397 if (p != SIG_ERR)
398 r = 0;
399 h->handler = NULL;
400 h->have_handler = 0;
402 mph_int_set (&h->signum, 0);
405 release_mutex (&signals_mutex);
407 return r;
408 #else
409 g_error ("signal() is not supported by this platform");
410 return 0;
411 #endif
414 // Set up a signal_info to begin waiting for signal
415 static int
416 setup_pipes (signal_info** signals, int count, struct pollfd *fd_structs, int *currfd)
418 int i;
419 int r = 0;
420 for (i = 0; i < count; ++i) {
421 signal_info* h;
422 int filedes[2];
424 h = signals [i];
426 if (mph_int_get (&h->pipecnt) == 0) { // First listener for this signal_info
427 if ((r = pipe (filedes)) != 0) {
428 break;
430 mph_int_set (&h->read_fd, filedes [0]);
431 mph_int_set (&h->write_fd, filedes [1]);
433 mph_int_inc (&h->pipecnt);
434 fd_structs[*currfd].fd = mph_int_get (&h->read_fd);
435 fd_structs[*currfd].events = POLLIN;
436 ++(*currfd); // count is verified less than NUM_SIGNALS by caller
438 return r;
441 // Cleanup a signal_info after waiting for signal
442 static void
443 teardown_pipes (signal_info** signals, int count)
445 int i;
446 for (i = 0; i < count; ++i) {
447 signal_info* h = signals [i];
449 if (mph_int_dec_test (&h->pipecnt)) { // Final listener for this signal_info
450 acquire_pipelock_teardown (&h->pipelock);
451 int read_fd = mph_int_get (&h->read_fd);
452 int write_fd = mph_int_get (&h->write_fd);
453 if (read_fd != 0)
454 close (read_fd);
455 if (write_fd != 0)
456 close (write_fd);
457 mph_int_set (&h->read_fd, 0);
458 mph_int_set (&h->write_fd, 0);
459 release_pipelock_teardown (&h->pipelock);
464 // Given pipes set up, wait for a byte to arrive on one of them
465 static int
466 wait_for_any (signal_info** signals, int count, int *currfd, struct pollfd* fd_structs, int timeout, Mono_Posix_RuntimeIsShuttingDown shutting_down)
468 int r, idx;
469 // Poll until one of this signal_info's pipes is ready to read.
470 // Once a second, stop to check if the VM is shutting down.
471 do {
472 struct timeval tv;
473 struct timeval *ptv = NULL;
474 if (timeout != -1) {
475 tv.tv_sec = timeout / 1000;
476 tv.tv_usec = (timeout % 1000)*1000;
477 ptv = &tv;
479 r = poll (fd_structs, count, timeout);
480 } while (keep_trying (r) && !shutting_down ());
482 idx = -1;
483 if (r == 0)
484 idx = timeout;
485 else if (r > 0) { // The pipe[s] are ready to read.
486 int i;
487 for (i = 0; i < count; ++i) {
488 signal_info* h = signals [i];
489 if (fd_structs[i].revents & POLLIN) {
490 int r;
491 char c;
492 do {
493 r = read (mph_int_get (&h->read_fd), &c, 1);
494 } while (keep_trying (r) && !shutting_down ());
495 if (idx == -1)
496 idx = i;
501 return idx;
505 * returns: -1 on error:
506 * timeout on timeout
507 * index into _signals array of signal that was generated on success
510 Mono_Unix_UnixSignal_WaitAny (void** _signals, int count, int timeout /* milliseconds */, Mono_Posix_RuntimeIsShuttingDown shutting_down)
512 int r;
513 int currfd = 0;
514 struct pollfd fd_structs[NUM_SIGNALS];
516 signal_info** signals = (signal_info**) _signals;
518 if (count > NUM_SIGNALS)
519 return -1;
521 if (acquire_mutex (&signals_mutex) == -1)
522 return -1;
524 r = setup_pipes (signals, count, &fd_structs[0], &currfd);
526 release_mutex (&signals_mutex);
528 if (r == 0) {
529 r = wait_for_any (signals, count, &currfd, &fd_structs[0], timeout, shutting_down);
532 if (acquire_mutex (&signals_mutex) == -1)
533 return -1;
535 teardown_pipes (signals, count);
537 release_mutex (&signals_mutex);
539 return r;
542 #endif /* ndef HOST_WIN32 */
545 G_END_DECLS
548 * vim: noexpandtab