fix crash in pthread_cond_wait mutex-locked check
[musl] / src / thread / pthread_cond_timedwait.c
1 #include "pthread_impl.h"
2
3 struct cm {
4         pthread_cond_t *c;
5         pthread_mutex_t *m;
6 };
7
8 static void unwait(pthread_cond_t *c, pthread_mutex_t *m)
9 {
10         /* Removing a waiter is non-trivial if we could be using requeue
11          * based broadcast signals, due to mutex access issues, etc. */
12
13         if (c->_c_mutex == (void *)-1) {
14                 a_dec(&c->_c_waiters);
15                 return;
16         }
17
18         while (a_swap(&c->_c_lock, 1))
19                 __wait(&c->_c_lock, &c->_c_lockwait, 1, 1);
20
21         if (c->_c_waiters2) c->_c_waiters2--;
22         else a_dec(&m->_m_waiters);
23
24         a_store(&c->_c_lock, 0);
25         if (c->_c_lockwait) __wake(&c->_c_lock, 1, 1);
26 }
27
28 static void cleanup(void *p)
29 {
30         struct cm *cm = p;
31         unwait(cm->c, cm->m);
32         pthread_mutex_lock(cm->m);
33 }
34
35 int pthread_cond_timedwait(pthread_cond_t *c, pthread_mutex_t *m, const struct timespec *ts)
36 {
37         struct cm cm = { .c=c, .m=m };
38         int r, e=0, seq;
39
40         if (m->_m_type && (m->_m_lock&INT_MAX) != pthread_self()->tid)
41                 return EPERM;
42
43         if (ts && ts->tv_nsec >= 1000000000UL)
44                 return EINVAL;
45
46         pthread_testcancel();
47
48         a_inc(&c->_c_waiters);
49
50         if (c->_c_mutex != (void *)-1) {
51                 c->_c_mutex = m;
52                 while (a_swap(&c->_c_lock, 1))
53                         __wait(&c->_c_lock, &c->_c_lockwait, 1, 1);
54                 c->_c_waiters2++;
55                 a_store(&c->_c_lock, 0);
56                 if (c->_c_lockwait) __wake(&c->_c_lock, 1, 1);
57         }
58
59         seq = c->_c_seq;
60
61         pthread_mutex_unlock(m);
62
63         do e = __timedwait(&c->_c_seq, seq, c->_c_clock, ts, cleanup, &cm, 0);
64         while (c->_c_seq == seq && (!e || e==EINTR));
65         if (e == EINTR) e = 0;
66
67         unwait(c, m);
68
69         if ((r=pthread_mutex_lock(m))) return r;
70
71         return e;
72 }