split internal lock API out of libc.h, creating lock.h
[musl.git] / src / signal / sigaction.c
blobaf47195e001376c2e5e870f410b71ae5f230bb25
1 #include <signal.h>
2 #include <errno.h>
3 #include <string.h>
4 #include "syscall.h"
5 #include "pthread_impl.h"
6 #include "libc.h"
7 #include "lock.h"
8 #include "ksigaction.h"
10 volatile int dummy_lock[1] = { 0 };
12 extern hidden volatile int __abort_lock[1];
14 weak_alias(dummy_lock, __abort_lock);
16 static int unmask_done;
17 static unsigned long handler_set[_NSIG/(8*sizeof(long))];
19 void __get_handler_set(sigset_t *set)
21 memcpy(set, handler_set, sizeof handler_set);
24 int __libc_sigaction(int sig, const struct sigaction *restrict sa, struct sigaction *restrict old)
26 struct k_sigaction ksa, ksa_old;
27 unsigned long set[_NSIG/(8*sizeof(long))];
28 if (sa) {
29 if ((uintptr_t)sa->sa_handler > 1UL) {
30 a_or_l(handler_set+(sig-1)/(8*sizeof(long)),
31 1UL<<(sig-1)%(8*sizeof(long)));
33 /* If pthread_create has not yet been called,
34 * implementation-internal signals might not
35 * yet have been unblocked. They must be
36 * unblocked before any signal handler is
37 * installed, so that an application cannot
38 * receive an illegal sigset_t (with them
39 * blocked) as part of the ucontext_t passed
40 * to the signal handler. */
41 if (!libc.threaded && !unmask_done) {
42 __syscall(SYS_rt_sigprocmask, SIG_UNBLOCK,
43 SIGPT_SET, 0, _NSIG/8);
44 unmask_done = 1;
47 /* Changing the disposition of SIGABRT to anything but
48 * SIG_DFL requires a lock, so that it cannot be changed
49 * while abort is terminating the process after simply
50 * calling raise(SIGABRT) failed to do so. */
51 if (sa->sa_handler != SIG_DFL && sig == SIGABRT) {
52 __block_all_sigs(&set);
53 LOCK(__abort_lock);
55 ksa.handler = sa->sa_handler;
56 ksa.flags = sa->sa_flags | SA_RESTORER;
57 ksa.restorer = (sa->sa_flags & SA_SIGINFO) ? __restore_rt : __restore;
58 memcpy(&ksa.mask, &sa->sa_mask, _NSIG/8);
60 int r = __syscall(SYS_rt_sigaction, sig, sa?&ksa:0, old?&ksa_old:0, _NSIG/8);
61 if (sig == SIGABRT && sa && sa->sa_handler != SIG_DFL) {
62 UNLOCK(__abort_lock);
63 __restore_sigs(&set);
65 if (old && !r) {
66 old->sa_handler = ksa_old.handler;
67 old->sa_flags = ksa_old.flags;
68 memcpy(&old->sa_mask, &ksa_old.mask, _NSIG/8);
70 return __syscall_ret(r);
73 int __sigaction(int sig, const struct sigaction *restrict sa, struct sigaction *restrict old)
75 if (sig-32U < 3 || sig-1U >= _NSIG-1) {
76 errno = EINVAL;
77 return -1;
79 return __libc_sigaction(sig, sa, old);
82 weak_alias(__sigaction, sigaction);