fix breakage in cancellation due to signal functions overhaul
[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         uintptr_t old_sp, old_ip;
18         long r;
19
20         if (!libc.threaded || (self = __pthread_self())->canceldisable)
21                 return __syscall(nr, u, v, w, x, y, z);
22
23         old_sp = self->cp_sp;
24         old_ip = self->cp_ip;
25         self->cp_sp = 0;
26         self->cp_ip = 0;
27         r = __syscall_cp_asm(&self->cp_sp, nr, u, v, w, x, y, z);
28         self->cp_ip = old_ip;
29         self->cp_sp = old_sp;
30         if (r == -EINTR && self->cancel && !self->canceldisable) __cancel();
31         return r;
32 }
33
34 static void _sigaddset(sigset_t *set, int sig)
35 {
36         unsigned s = sig-1;
37         set->__bits[s/8/sizeof *set->__bits] |= 1UL<<(s&8*sizeof *set->__bits-1);
38 }
39
40 static void cancel_handler(int sig, siginfo_t *si, void *ctx)
41 {
42         pthread_t self = __pthread_self();
43         ucontext_t *uc = ctx;
44         uintptr_t sp = ((uintptr_t *)&uc->uc_mcontext)[CANCEL_REG_SP];
45         uintptr_t ip = ((uintptr_t *)&uc->uc_mcontext)[CANCEL_REG_IP];
46
47         if (!self->cancel || self->canceldisable) return;
48
49         _sigaddset(&uc->uc_sigmask, SIGCANCEL);
50
51         if (self->cancelasync || sp == self->cp_sp && ip <= self->cp_ip) {
52                 self->canceldisable = 1;
53                 pthread_sigmask(SIG_SETMASK, &uc->uc_sigmask, 0);
54                 __cancel();
55         }
56
57         if (self->cp_sp)
58                 __syscall(SYS_tgkill, self->pid, self->tid, SIGCANCEL);
59 }
60
61 static void testcancel()
62 {
63         pthread_t self = __pthread_self();
64         if (self->cancel && !self->canceldisable)
65                 __cancel();
66 }
67
68 static void init_cancellation()
69 {
70         struct sigaction sa = {
71                 .sa_flags = SA_SIGINFO | SA_RESTART,
72                 .sa_sigaction = cancel_handler
73         };
74         sigfillset(&sa.sa_mask);
75         __libc_sigaction(SIGCANCEL, &sa, 0);
76         libc.testcancel = testcancel;
77 }
78
79 int pthread_cancel(pthread_t t)
80 {
81         static int init;
82         if (!init) {
83                 init_cancellation();
84                 init = 1;
85         }
86         a_store(&t->cancel, 1);
87         return pthread_kill(t, SIGCANCEL);
88 }