Signals: Ensure libdw session is freed
[ghc.git] / rts / posix / Signals.c
1 /* -----------------------------------------------------------------------------
2 *
3 * (c) The GHC Team, 1998-2005
4 *
5 * Signal processing / handling.
6 *
7 * ---------------------------------------------------------------------------*/
8
9 #include "PosixSource.h"
10 #include "Rts.h"
11
12 #include "Schedule.h"
13 #include "RtsSignals.h"
14 #include "Signals.h"
15 #include "RtsUtils.h"
16 #include "Prelude.h"
17 #include "Stable.h"
18 #include "Libdw.h"
19
20 #ifdef alpha_HOST_ARCH
21 # if defined(linux_HOST_OS)
22 # include <asm/fpu.h>
23 # else
24 # include <machine/fpu.h>
25 # endif
26 #endif
27
28 #ifdef HAVE_UNISTD_H
29 # include <unistd.h>
30 #endif
31
32 #ifdef HAVE_SIGNAL_H
33 # include <signal.h>
34 #endif
35
36 #ifdef HAVE_ERRNO_H
37 # include <errno.h>
38 #endif
39
40 #ifdef HAVE_EVENTFD_H
41 # include <sys/eventfd.h>
42 #endif
43
44 #ifdef HAVE_TERMIOS_H
45 #include <termios.h>
46 #endif
47
48 #include <stdlib.h>
49 #include <string.h>
50
51 /* This curious flag is provided for the benefit of the Haskell binding
52 * to POSIX.1 to control whether or not to include SA_NOCLDSTOP when
53 * installing a SIGCHLD handler.
54 */
55 HsInt nocldstop = 0;
56
57 /* -----------------------------------------------------------------------------
58 * The table of signal handlers
59 * -------------------------------------------------------------------------- */
60
61 #if defined(RTS_USER_SIGNALS)
62
63 /* SUP: The type of handlers is a little bit, well, doubtful... */
64 StgInt *signal_handlers = NULL; /* Dynamically grown array of signal handlers */
65 static StgInt nHandlers = 0; /* Size of handlers array */
66
67 static nat n_haskell_handlers = 0;
68
69 static sigset_t userSignals;
70 static sigset_t savedSignals;
71
72 #ifdef THREADED_RTS
73 static Mutex sig_mutex; // protects signal_handlers, nHandlers
74 #endif
75
76 /* -----------------------------------------------------------------------------
77 * Initialisation / deinitialisation
78 * -------------------------------------------------------------------------- */
79
80 void
81 initUserSignals(void)
82 {
83 sigemptyset(&userSignals);
84 #ifdef THREADED_RTS
85 initMutex(&sig_mutex);
86 #endif
87 }
88
89 void
90 freeSignalHandlers(void) {
91 if (signal_handlers != NULL) {
92 stgFree(signal_handlers);
93 signal_handlers = NULL;
94 nHandlers = 0;
95 n_haskell_handlers = 0;
96 }
97 #ifdef THREADED_RTS
98 closeMutex(&sig_mutex);
99 #endif
100 }
101
102 /* -----------------------------------------------------------------------------
103 * Allocate/resize the table of signal handlers.
104 * -------------------------------------------------------------------------- */
105
106 static void
107 more_handlers(int sig)
108 {
109 StgInt i;
110
111 if (sig < nHandlers)
112 return;
113
114 if (signal_handlers == NULL)
115 signal_handlers = (StgInt *)stgMallocBytes((sig + 1) * sizeof(StgInt),
116 "more_handlers");
117 else
118 signal_handlers = (StgInt *)stgReallocBytes(signal_handlers,
119 (sig + 1) * sizeof(StgInt),
120 "more_handlers");
121
122 for(i = nHandlers; i <= sig; i++)
123 // Fill in the new slots with default actions
124 signal_handlers[i] = STG_SIG_DFL;
125
126 nHandlers = sig + 1;
127 }
128
129 // Here's the pipe into which we will send our signals
130 static volatile int io_manager_wakeup_fd = -1;
131 static int timer_manager_control_wr_fd = -1;
132
133 #define IO_MANAGER_WAKEUP 0xff
134 #define IO_MANAGER_DIE 0xfe
135 #define IO_MANAGER_SYNC 0xfd
136
137 void setTimerManagerControlFd(int fd) {
138 timer_manager_control_wr_fd = fd;
139 }
140
141 void
142 setIOManagerWakeupFd (int fd)
143 {
144 // only called when THREADED_RTS, but unconditionally
145 // compiled here because GHC.Event.Control depends on it.
146 io_manager_wakeup_fd = fd;
147 }
148
149 /* -----------------------------------------------------------------------------
150 * Wake up at least one IO or timer manager HS thread.
151 * -------------------------------------------------------------------------- */
152 void
153 ioManagerWakeup (void)
154 {
155 int r;
156 // Wake up the IO Manager thread by sending a byte down its pipe
157 if (io_manager_wakeup_fd >= 0) {
158 #if defined(HAVE_EVENTFD)
159 StgWord64 n = (StgWord64)IO_MANAGER_WAKEUP;
160 r = write(io_manager_wakeup_fd, (char *) &n, 8);
161 #else
162 StgWord8 byte = (StgWord8)IO_MANAGER_WAKEUP;
163 r = write(io_manager_wakeup_fd, &byte, 1);
164 #endif
165 /* N.B. If the TimerManager is shutting down as we run this
166 * then there is a possiblity that our first read of
167 * io_manager_wakeup_fd is non-negative, but before we get to the
168 * write the file is closed. If this occurs, io_manager_wakeup_fd
169 * will be written into with -1 (GHC.Event.Control does this prior
170 * to closing), so checking this allows us to distinguish this case.
171 * To ensure we observe the correct ordering, we declare the
172 * io_manager_wakeup_fd as volatile.
173 * Since this is not an error condition, we do not print the error
174 * message in this case.
175 */
176 if (r == -1 && io_manager_wakeup_fd >= 0) {
177 sysErrorBelch("ioManagerWakeup: write");
178 }
179 }
180 }
181
182 #if defined(THREADED_RTS)
183 void
184 ioManagerDie (void)
185 {
186 StgWord8 byte = (StgWord8)IO_MANAGER_DIE;
187 nat i;
188 int fd;
189 int r;
190
191 if (0 <= timer_manager_control_wr_fd) {
192 r = write(timer_manager_control_wr_fd, &byte, 1);
193 if (r == -1) { sysErrorBelch("ioManagerDie: write"); }
194 timer_manager_control_wr_fd = -1;
195 }
196
197 for (i=0; i < n_capabilities; i++) {
198 fd = capabilities[i]->io_manager_control_wr_fd;
199 if (0 <= fd) {
200 r = write(fd, &byte, 1);
201 if (r == -1) { sysErrorBelch("ioManagerDie: write"); }
202 capabilities[i]->io_manager_control_wr_fd = -1;
203 }
204 }
205 }
206
207 void
208 ioManagerStartCap (Capability **cap)
209 {
210 rts_evalIO(cap,&base_GHCziConcziIO_ensureIOManagerIsRunning_closure,NULL);
211 }
212
213 void
214 ioManagerStart (void)
215 {
216 // Make sure the IO manager thread is running
217 Capability *cap;
218 if (timer_manager_control_wr_fd < 0 || io_manager_wakeup_fd < 0) {
219 cap = rts_lock();
220 ioManagerStartCap(&cap);
221 rts_unlock(cap);
222 }
223 }
224 #endif
225
226 #if !defined(THREADED_RTS)
227
228 #define N_PENDING_HANDLERS 16
229
230 siginfo_t pending_handler_buf[N_PENDING_HANDLERS];
231 siginfo_t *next_pending_handler = pending_handler_buf;
232
233 #endif /* THREADED_RTS */
234
235 /* -----------------------------------------------------------------------------
236 * Low-level signal handler
237 *
238 * Places the requested handler on a stack of pending handlers to be
239 * started up at the next context switch.
240 * -------------------------------------------------------------------------- */
241
242 static void
243 generic_handler(int sig USED_IF_THREADS,
244 siginfo_t *info,
245 void *p STG_UNUSED)
246 {
247 #if defined(THREADED_RTS)
248
249 StgWord8 buf[sizeof(siginfo_t) + 1];
250 int r;
251
252 buf[0] = sig;
253 if (info == NULL) {
254 // info may be NULL on Solaris (see #3790)
255 memset(buf+1, 0, sizeof(siginfo_t));
256 } else {
257 memcpy(buf+1, info, sizeof(siginfo_t));
258 }
259
260 if (0 <= timer_manager_control_wr_fd)
261 {
262 r = write(timer_manager_control_wr_fd, buf, sizeof(siginfo_t)+1);
263 if (r == -1 && errno == EAGAIN) {
264 errorBelch("lost signal due to full pipe: %d\n", sig);
265 }
266 }
267
268 // If the IO manager hasn't told us what the FD of the write end
269 // of its pipe is, there's not much we can do here, so just ignore
270 // the signal..
271
272 #else /* not THREADED_RTS */
273
274 /* Can't call allocate from here. Probably can't call malloc
275 either. However, we have to schedule a new thread somehow.
276
277 It's probably ok to request a context switch and allow the
278 scheduler to start the handler thread, but how do we
279 communicate this to the scheduler?
280
281 We need some kind of locking, but with low overhead (i.e. no
282 blocking signals every time around the scheduler).
283
284 Signal Handlers are atomic (i.e. they can't be interrupted), and
285 we can make use of this. We just need to make sure the
286 critical section of the scheduler can't be interrupted - the
287 only way to do this is to block signals. However, we can lower
288 the overhead by only blocking signals when there are any
289 handlers to run, i.e. the set of pending handlers is
290 non-empty.
291 */
292
293 /* We use a stack to store the pending signals. We can't
294 dynamically grow this since we can't allocate any memory from
295 within a signal handler.
296
297 Hence unfortunately we have to bomb out if the buffer
298 overflows. It might be acceptable to carry on in certain
299 circumstances, depending on the signal.
300 */
301
302 memcpy(next_pending_handler, info, sizeof(siginfo_t));
303
304 next_pending_handler++;
305
306 // stack full?
307 if (next_pending_handler == &pending_handler_buf[N_PENDING_HANDLERS]) {
308 errorBelch("too many pending signals");
309 stg_exit(EXIT_FAILURE);
310 }
311
312 interruptCapability(&MainCapability);
313
314 #endif /* THREADED_RTS */
315 }
316
317 /* -----------------------------------------------------------------------------
318 * Blocking/Unblocking of the user signals
319 * -------------------------------------------------------------------------- */
320
321 void
322 blockUserSignals(void)
323 {
324 sigprocmask(SIG_BLOCK, &userSignals, &savedSignals);
325 }
326
327 void
328 unblockUserSignals(void)
329 {
330 sigprocmask(SIG_SETMASK, &savedSignals, NULL);
331 }
332
333 rtsBool
334 anyUserHandlers(void)
335 {
336 return n_haskell_handlers != 0;
337 }
338
339 #if !defined(THREADED_RTS)
340 void
341 awaitUserSignals(void)
342 {
343 while (!signals_pending() && sched_state == SCHED_RUNNING) {
344 pause();
345 }
346 }
347 #endif
348
349 /* -----------------------------------------------------------------------------
350 * Install a Haskell signal handler.
351 *
352 * We should really do this in Haskell in GHC.Conc, and share the
353 * signal_handlers array with the one there.
354 *
355 * -------------------------------------------------------------------------- */
356
357 int
358 stg_sig_install(int sig, int spi, void *mask)
359 {
360 sigset_t signals, osignals;
361 struct sigaction action;
362 StgInt previous_spi;
363
364 ACQUIRE_LOCK(&sig_mutex);
365
366 // Block the signal until we figure out what to do
367 // Count on this to fail if the signal number is invalid
368 if (sig < 0 ||
369 sigemptyset(&signals) ||
370 sigaddset(&signals, sig) ||
371 sigprocmask(SIG_BLOCK, &signals, &osignals)) {
372 RELEASE_LOCK(&sig_mutex);
373 return STG_SIG_ERR;
374 }
375
376 more_handlers(sig);
377
378 previous_spi = signal_handlers[sig];
379
380 action.sa_flags = 0;
381
382 switch(spi) {
383 case STG_SIG_IGN:
384 action.sa_handler = SIG_IGN;
385 break;
386
387 case STG_SIG_DFL:
388 action.sa_handler = SIG_DFL;
389 break;
390
391 case STG_SIG_RST:
392 action.sa_flags |= SA_RESETHAND;
393 /* fall through */
394 case STG_SIG_HAN:
395 action.sa_sigaction = generic_handler;
396 action.sa_flags |= SA_SIGINFO;
397 break;
398
399 default:
400 barf("stg_sig_install: bad spi");
401 }
402
403 if (mask != NULL)
404 action.sa_mask = *(sigset_t *)mask;
405 else
406 sigemptyset(&action.sa_mask);
407
408 action.sa_flags |= sig == SIGCHLD && nocldstop ? SA_NOCLDSTOP : 0;
409
410 if (sigaction(sig, &action, NULL))
411 {
412 errorBelch("sigaction");
413 RELEASE_LOCK(&sig_mutex);
414 return STG_SIG_ERR;
415 }
416
417 signal_handlers[sig] = spi;
418
419 switch(spi) {
420 case STG_SIG_RST:
421 case STG_SIG_HAN:
422 sigaddset(&userSignals, sig);
423 if (previous_spi != STG_SIG_HAN && previous_spi != STG_SIG_RST) {
424 n_haskell_handlers++;
425 }
426 break;
427
428 default:
429 sigdelset(&userSignals, sig);
430 if (previous_spi == STG_SIG_HAN || previous_spi == STG_SIG_RST) {
431 n_haskell_handlers--;
432 }
433 break;
434 }
435
436 if (sigprocmask(SIG_SETMASK, &osignals, NULL))
437 {
438 errorBelch("sigprocmask");
439 RELEASE_LOCK(&sig_mutex);
440 return STG_SIG_ERR;
441 }
442
443 RELEASE_LOCK(&sig_mutex);
444 return previous_spi;
445 }
446
447 /* -----------------------------------------------------------------------------
448 * Creating new threads for signal handlers.
449 * -------------------------------------------------------------------------- */
450
451 #if !defined(THREADED_RTS)
452 void
453 startSignalHandlers(Capability *cap)
454 {
455 siginfo_t *info;
456 int sig;
457
458 blockUserSignals();
459
460 while (next_pending_handler != pending_handler_buf) {
461
462 next_pending_handler--;
463
464 sig = next_pending_handler->si_signo;
465 if (signal_handlers[sig] == STG_SIG_DFL) {
466 continue; // handler has been changed.
467 }
468
469 info = stgMallocBytes(sizeof(siginfo_t), "startSignalHandlers");
470 // freed by runHandler
471 memcpy(info, next_pending_handler, sizeof(siginfo_t));
472
473 scheduleThread(cap,
474 createIOThread(cap,
475 RtsFlags.GcFlags.initialStkSize,
476 rts_apply(cap,
477 rts_apply(cap,
478 &base_GHCziConcziSignal_runHandlersPtr_closure,
479 rts_mkPtr(cap, info)),
480 rts_mkInt(cap, info->si_signo))));
481 }
482
483 unblockUserSignals();
484 }
485 #endif
486
487 /* ----------------------------------------------------------------------------
488 * Mark signal handlers during GC.
489 * -------------------------------------------------------------------------- */
490
491 void
492 markSignalHandlers (evac_fn evac STG_UNUSED, void *user STG_UNUSED)
493 {
494 // nothing to do
495 }
496
497 #else /* !RTS_USER_SIGNALS */
498 StgInt
499 stg_sig_install(StgInt sig STG_UNUSED,
500 StgInt spi STG_UNUSED,
501 void* mask STG_UNUSED)
502 {
503 //barf("User signals not supported");
504 return STG_SIG_DFL;
505 }
506
507 #endif
508
509 #if defined(RTS_USER_SIGNALS)
510 /* -----------------------------------------------------------------------------
511 * SIGINT handler.
512 *
513 * We like to shutdown nicely after receiving a SIGINT, write out the
514 * stats, write profiling info, close open files and flush buffers etc.
515 * -------------------------------------------------------------------------- */
516 static void
517 shutdown_handler(int sig STG_UNUSED)
518 {
519 // If we're already trying to interrupt the RTS, terminate with
520 // extreme prejudice. So the first ^C tries to exit the program
521 // cleanly, and the second one just kills it.
522 if (sched_state >= SCHED_INTERRUPTING) {
523 stg_exit(EXIT_INTERRUPTED);
524 } else {
525 interruptStgRts();
526 }
527 }
528
529 /* -----------------------------------------------------------------------------
530 * SIGUSR2 handler.
531 *
532 * We try to give the user an indication of what we are currently doing
533 * in response to SIGUSR2.
534 * -------------------------------------------------------------------------- */
535 static void
536 backtrace_handler(int sig STG_UNUSED)
537 {
538 #ifdef USE_LIBDW
539 LibDwSession *session = libdw_init();
540 Backtrace *bt = libdw_get_backtrace(session);
541 libdw_print_backtrace(session, stderr, bt);
542 backtrace_free(bt);
543 libdw_free(session);
544 #else
545 fprintf(stderr, "This build does not support backtraces.\n");
546 #endif
547 }
548
549 /* -----------------------------------------------------------------------------
550 * An empty signal handler, currently used for SIGPIPE
551 * -------------------------------------------------------------------------- */
552 static void
553 empty_handler (int sig STG_UNUSED)
554 {
555 // nothing
556 }
557
558 /* -----------------------------------------------------------------------------
559 SIGTSTP handling
560
561 When a process is suspeended with ^Z and resumed again, the shell
562 makes no attempt to save and restore the terminal settings. So on
563 resume, any terminal setting modificaions we made (e.g. turning off
564 ICANON due to hSetBuffering NoBuffering) may well be lost. Hence,
565 we arrange to save and restore the terminal settings ourselves.
566
567 The trick we use is:
568 - catch SIGTSTP
569 - in the handler, kill(getpid(),SIGSTOP)
570 - when this returns, restore the TTY settings
571 This means we don't have to catch SIGCONT too.
572
573 Note we don't re-throw SIGTSTP, we throw SIGSTOP instead. This is
574 for a few reasons:
575
576 - re-throwing SIGTSTP would require temporarily restoring the
577 default sigaction.
578
579 - it doesn't work on certain buggy pthread implementations
580 (e.g. OpenBSD).
581
582 - throwing SIGTSTP seems slightly dodgy anyway.
583
584 -------------------------------------------------------------------------- */
585
586 static void sigtstp_handler(int sig);
587 static void set_sigtstp_action (rtsBool handle);
588
589 static void
590 sigtstp_handler (int sig STG_UNUSED)
591 {
592 int fd;
593 struct termios ts[3];
594
595 // save the current TTY state for TTYs we modified
596 for (fd = 0; fd <= 2; fd++) {
597 if (__hscore_get_saved_termios(fd) != NULL) {
598 tcgetattr(fd,&ts[fd]);
599 }
600 }
601
602 // really stop the process now
603 kill(getpid(), SIGSTOP);
604
605 // on return, restore the TTY state
606 for (fd = 0; fd <= 2; fd++) {
607 if (__hscore_get_saved_termios(fd) != NULL) {
608 tcsetattr(0,TCSANOW,&ts[fd]);
609 }
610 }
611 }
612
613 static void
614 set_sigtstp_action (rtsBool handle)
615 {
616 struct sigaction sa;
617 if (handle) {
618 sa.sa_handler = sigtstp_handler;
619 } else {
620 sa.sa_handler = SIG_DFL;
621 }
622 sa.sa_flags = 0;
623 sigemptyset(&sa.sa_mask);
624 if (sigaction(SIGTSTP, &sa, NULL) != 0) {
625 sysErrorBelch("warning: failed to install SIGTSTP handler");
626 }
627 }
628
629 /* -----------------------------------------------------------------------------
630 * Install default signal handlers.
631 *
632 * The RTS installs a default signal handler for catching
633 * SIGINT, so that we can perform an orderly shutdown.
634 *
635 * Haskell code may install their own SIGINT handler, which is
636 * fine, provided they're so kind as to put back the old one
637 * when they de-install.
638 *
639 * In addition to handling SIGINT, the RTS also handles SIGFPE
640 * by ignoring it. Apparently IEEE requires floating-point
641 * exceptions to be ignored by default, but alpha-dec-osf3
642 * doesn't seem to do so.
643 * -------------------------------------------------------------------------- */
644 void
645 initDefaultHandlers(void)
646 {
647 struct sigaction action,oact;
648
649 // install the SIGINT handler
650 action.sa_handler = shutdown_handler;
651 sigemptyset(&action.sa_mask);
652 action.sa_flags = 0;
653 if (sigaction(SIGINT, &action, &oact) != 0) {
654 sysErrorBelch("warning: failed to install SIGINT handler");
655 }
656
657 #if defined(HAVE_SIGINTERRUPT)
658 siginterrupt(SIGINT, 1); // isn't this the default? --SDM
659 #endif
660
661 // install the SIGFPE handler
662
663 // In addition to handling SIGINT, also handle SIGFPE by ignoring it.
664 // Apparently IEEE requires floating-point exceptions to be ignored by
665 // default, but alpha-dec-osf3 doesn't seem to do so.
666
667 // Commented out by SDM 2/7/2002: this causes an infinite loop on
668 // some architectures when an integer division by zero occurs: we
669 // don't recover from the floating point exception, and the
670 // program just generates another one immediately.
671 #if 0
672 action.sa_handler = SIG_IGN;
673 sigemptyset(&action.sa_mask);
674 action.sa_flags = 0;
675 if (sigaction(SIGFPE, &action, &oact) != 0) {
676 sysErrorBelch("warning: failed to install SIGFPE handler");
677 }
678 #endif
679
680 #ifdef alpha_HOST_ARCH
681 ieee_set_fp_control(0);
682 #endif
683
684 // ignore SIGPIPE; see #1619
685 // actually, we use an empty signal handler rather than SIG_IGN,
686 // so that SIGPIPE gets reset to its default behaviour on exec.
687 action.sa_handler = empty_handler;
688 sigemptyset(&action.sa_mask);
689 action.sa_flags = 0;
690 if (sigaction(SIGPIPE, &action, &oact) != 0) {
691 sysErrorBelch("warning: failed to install SIGPIPE handler");
692 }
693
694 // Print a backtrace on SIGUSR2
695 action.sa_handler = backtrace_handler;
696 sigemptyset(&action.sa_mask);
697 action.sa_flags = 0;
698 if (sigaction(SIGUSR2, &action, &oact) != 0) {
699 sysErrorBelch("warning: failed to install SIGUSR2 handler");
700 }
701
702 set_sigtstp_action(rtsTrue);
703 }
704
705 void
706 resetDefaultHandlers(void)
707 {
708 struct sigaction action;
709
710 action.sa_handler = SIG_DFL;
711 sigemptyset(&action.sa_mask);
712 action.sa_flags = 0;
713
714 // restore SIGINT
715 if (sigaction(SIGINT, &action, NULL) != 0) {
716 sysErrorBelch("warning: failed to uninstall SIGINT handler");
717 }
718 // restore SIGPIPE
719 if (sigaction(SIGPIPE, &action, NULL) != 0) {
720 sysErrorBelch("warning: failed to uninstall SIGPIPE handler");
721 }
722
723 set_sigtstp_action(rtsFalse);
724 }
725
726 #endif /* RTS_USER_SIGNALS */