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