fix issue with longjmp out of signal handlers and cancellation
[musl] / src / thread / cancel_impl.c
1 #include "pthread_impl.h"
2
3 void __cancel()
4 {
5         pthread_t self = __pthread_self();
6         self->cp_sp = 0;
7         self->canceldisable = 1;
8         self->cancelasync = 0;
9         pthread_exit(PTHREAD_CANCELED);
10 }
11
12 long __syscall_cp_asm(volatile void *, long, long, long, long, long, long, long);
13
14 long (__syscall_cp)(long nr, long u, long v, long w, long x, long y, long z)
15 {
16         pthread_t self;
17         long r;
18
19         if (!libc.main_thread || (self = __pthread_self())->canceldisable)
20                 return __syscall(nr, u, v, w, x, y, z);
21
22         r = __syscall_cp_asm(&self->cancel, nr, u, v, w, x, y, z);
23         if (r==-EINTR && nr!=SYS_close && self->cancel && !self->canceldisable)
24                 __cancel();
25         return r;
26 }
27
28 static void _sigaddset(sigset_t *set, int sig)
29 {
30         unsigned s = sig-1;
31         set->__bits[s/8/sizeof *set->__bits] |= 1UL<<(s&8*sizeof *set->__bits-1);
32 }
33
34 static void cancel_handler(int sig, siginfo_t *si, void *ctx)
35 {
36         pthread_t self = __pthread_self();
37         ucontext_t *uc = ctx;
38         const char *ip = ((char **)&uc->uc_mcontext)[CANCEL_REG_IP];
39         extern const char __cp_begin[1], __cp_end[1];
40
41         if (!self->cancel || self->canceldisable) return;
42
43         _sigaddset(&uc->uc_sigmask, SIGCANCEL);
44
45         if (self->cancelasync || ip >= __cp_begin && ip < __cp_end) {
46                 self->canceldisable = 1;
47                 pthread_sigmask(SIG_SETMASK, &uc->uc_sigmask, 0);
48                 __cancel();
49         }
50
51         if (self->cp_sp)
52                 __syscall(SYS_tgkill, self->pid, self->tid, SIGCANCEL);
53 }
54
55 void __testcancel()
56 {
57         pthread_t self = pthread_self();
58         if (self->cancel && !self->canceldisable)
59                 __cancel();
60 }
61
62 static void init_cancellation()
63 {
64         struct sigaction sa = {
65                 .sa_flags = SA_SIGINFO | SA_RESTART,
66                 .sa_sigaction = cancel_handler
67         };
68         sigfillset(&sa.sa_mask);
69         __libc_sigaction(SIGCANCEL, &sa, 0);
70 }
71
72 int pthread_cancel(pthread_t t)
73 {
74         static int init;
75         if (!init) {
76                 init_cancellation();
77                 init = 1;
78         }
79         a_store(&t->cancel, 1);
80         return pthread_kill(t, SIGCANCEL);
81 }