use syscall_arg_t type for syscall prototypes in pthread code
[musl] / src / thread / cancel_impl.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, syscall_arg_t, syscall_arg_t,
13                       syscall_arg_t, syscall_arg_t, syscall_arg_t, syscall_arg_t);
14
15 long (__syscall_cp)(syscall_arg_t nr, syscall_arg_t u, syscall_arg_t v, syscall_arg_t w,
16                     syscall_arg_t x, syscall_arg_t y, syscall_arg_t z)
17 {
18         pthread_t self;
19         long r;
20
21         if (!libc.main_thread || (self = __pthread_self())->canceldisable)
22                 return __syscall(nr, u, v, w, x, y, z);
23
24         r = __syscall_cp_asm(&self->cancel, nr, u, v, w, x, y, z);
25         if (r==-EINTR && nr!=SYS_close && self->cancel && !self->canceldisable)
26                 __cancel();
27         return r;
28 }
29
30 static void _sigaddset(sigset_t *set, int sig)
31 {
32         unsigned s = sig-1;
33         set->__bits[s/8/sizeof *set->__bits] |= 1UL<<(s&8*sizeof *set->__bits-1);
34 }
35
36 static void cancel_handler(int sig, siginfo_t *si, void *ctx)
37 {
38         pthread_t self = __pthread_self();
39         ucontext_t *uc = ctx;
40         const char *ip = ((char **)&uc->uc_mcontext)[CANCEL_REG_IP];
41         extern const char __cp_begin[1], __cp_end[1];
42
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_tgkill, self->pid, self->tid, SIGCANCEL);
54 }
55
56 void __testcancel()
57 {
58         pthread_t self = pthread_self();
59         if (self->cancel && !self->canceldisable)
60                 __cancel();
61 }
62
63 static void init_cancellation()
64 {
65         struct sigaction sa = {
66                 .sa_flags = SA_SIGINFO | SA_RESTART,
67                 .sa_sigaction = cancel_handler
68         };
69         sigfillset(&sa.sa_mask);
70         __libc_sigaction(SIGCANCEL, &sa, 0);
71 }
72
73 int pthread_cancel(pthread_t t)
74 {
75         static int init;
76         if (!init) {
77                 init_cancellation();
78                 init = 1;
79         }
80         a_store(&t->cancel, 1);
81         return pthread_kill(t, SIGCANCEL);
82 }