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