fix invalid pointer in synccall (multithread setuid, etc.)
[musl] / src / thread / synccall.c
1 #include "pthread_impl.h"
2 #include <semaphore.h>
3 #include <string.h>
4
5 static struct chain {
6         struct chain *next;
7         sem_t sem, sem2;
8 } *head, *cur;
9
10 static void (*callback)(void *), *context;
11 static int chainlen;
12 static sem_t chainlock, chaindone;
13
14 static void handler(int sig, siginfo_t *si, void *ctx)
15 {
16         struct chain ch;
17         pthread_t self = __pthread_self();
18         int old_errno = errno;
19
20         if (chainlen == libc.threads_minus_1) return;
21
22         sigqueue(self->pid, SIGSYNCCALL, (union sigval){0});
23
24         sem_init(&ch.sem, 0, 0);
25         sem_init(&ch.sem2, 0, 0);
26
27         while (sem_wait(&chainlock));
28         ch.next = head;
29         head = &ch;
30         if (++chainlen == libc.threads_minus_1) sem_post(&chaindone);
31         sem_post(&chainlock);
32
33         while (sem_wait(&ch.sem));
34         callback(context);
35         sem_post(&ch.sem2);
36         while (sem_wait(&ch.sem));
37
38         errno = old_errno;
39 }
40
41 void __synccall(void (*func)(void *), void *ctx)
42 {
43         pthread_t self;
44         struct sigaction sa;
45         struct chain *next;
46         uint64_t oldmask;
47
48         if (!libc.threads_minus_1) {
49                 func(ctx);
50                 return;
51         }
52
53         __inhibit_ptc();
54
55         __syscall(SYS_rt_sigprocmask, SIG_BLOCK, SIGALL_SET,
56                 &oldmask, _NSIG/8);
57
58         sem_init(&chaindone, 0, 0);
59         sem_init(&chainlock, 0, 1);
60         chainlen = 0;
61         head = 0;
62         callback = func;
63         context = ctx;
64
65         sa.sa_flags = SA_SIGINFO | SA_RESTART;
66         sa.sa_sigaction = handler;
67         sigfillset(&sa.sa_mask);
68         __libc_sigaction(SIGSYNCCALL, &sa, 0);
69
70         self = __pthread_self();
71         sigqueue(self->pid, SIGSYNCCALL, (union sigval){0});
72         while (sem_wait(&chaindone));
73
74         for (cur=head; cur; cur=cur->next) {
75                 sem_post(&cur->sem);
76                 while (sem_wait(&cur->sem2));
77         }
78         func(ctx);
79
80         for (cur=head; cur; cur=next) {
81                 next = cur->next;
82                 sem_post(&cur->sem);
83         }
84
85         sa.sa_flags = 0;
86         sa.sa_handler = SIG_IGN;
87         __libc_sigaction(SIGSYNCCALL, &sa, 0);
88
89         __syscall(SYS_rt_sigprocmask, SIG_SETMASK,
90                 &oldmask, 0, _NSIG/8);
91
92         __release_ptc();
93 }