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