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