]> git.pond.sub.org Git - empserver/blob - src/lib/empthread/pthread.c
Guard against unusable fd in pthreads' empth_select()
[empserver] / src / lib / empthread / pthread.c
1 /*
2  *  Empire - A multi-player, client/server Internet based war game.
3  *  Copyright (C) 1986-2011, Dave Pare, Jeff Bailey, Thomas Ruschak,
4  *                Ken Stevens, Steve McClure, Markus Armbruster
5  *
6  *  Empire is free software: you can redistribute it and/or modify
7  *  it under the terms of the GNU General Public License as published by
8  *  the Free Software Foundation, either version 3 of the License, or
9  *  (at your option) any later version.
10  *
11  *  This program is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *  GNU General Public License for more details.
15  *
16  *  You should have received a copy of the GNU General Public License
17  *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  *
19  *  ---
20  *
21  *  See files README, COPYING and CREDITS in the root of the source
22  *  tree for related information and legal notices.  It is expected
23  *  that future projects/authors will amend these files as needed.
24  *
25  *  ---
26  *
27  *  pthread.c: Interface from Empire threads to POSIX threads
28  *
29  *  Known contributors to this file:
30  *     Sasha Mikheev
31  *     Steve McClure, 1998
32  *     Markus Armbruster, 2005-2011
33  *     Ron Koenderink, 2007-2009
34  */
35
36 /* Required for PTHREAD_STACK_MIN on some systems, e.g. Solaris: */
37 #define _XOPEN_SOURCE 500
38
39 #include <config.h>
40
41 #include <errno.h>
42 #include <limits.h>
43 #include <pthread.h>
44 #include <signal.h>
45 #include <stdarg.h>
46 #include <stdio.h>
47 #include <stdlib.h>
48 #include <string.h>
49 #include <sys/select.h>
50 #include <unistd.h>
51 #include "misc.h"
52 #include "empthread.h"
53 #include "file.h"
54 #include "prototypes.h"
55
56 struct empth_t {
57     char *name;                 /* thread name */
58     void *ud;                   /* user data */
59     int wakeup;
60     void (*ep)(void *);         /* entry point */
61     pthread_t id;               /* thread id */
62 };
63
64 struct empth_rwlock_t {
65     /* Can't use pthread_rwlock_t, because it needn't prefer writers */
66     char *name;
67     int nread;                  /* #active readers */
68     int nwrite;                 /* total #writers (active and waiting) */
69     pthread_cond_t can_read;
70     pthread_cond_t can_write;
71 };
72
73 /* Thread-specific data key */
74 static pthread_key_t ctx_key;
75
76 /* Flags that were passed to empth_init() */
77 static int empth_flags;
78
79 /* Pointer to thread context variable */
80 static void **udata;
81
82 /*
83  * Non-preemption mutex.
84  * Empire code outside this file is only executed while holding this
85  * mutex.  This makes sure Empire code is never preempted by Empire
86  * code.
87  */
88 static pthread_mutex_t mtx_ctxsw;
89
90 static void empth_status(char *format, ...)
91     ATTRIBUTE((format (printf, 1, 2)));
92 static void empth_alarm(int sig);
93
94 static void *
95 empth_start(void *arg)
96 {
97     empth_t *ctx = arg;
98
99     ctx->id = pthread_self();
100     pthread_setspecific(ctx_key, ctx);
101     pthread_mutex_lock(&mtx_ctxsw);
102     *udata = ctx->ud;
103     ctx->ep(ctx->ud);
104     empth_exit();
105     return NULL;
106 }
107
108 static void
109 empth_status(char *format, ...)
110 {
111     va_list ap;
112     static struct timeval startTime;
113     struct timeval tv;
114     char buf[1024];
115     int sec, msec;
116     empth_t *a;
117
118     va_start(ap, format);
119     if (empth_flags & EMPTH_PRINT) {
120         if (startTime.tv_sec == 0)
121             gettimeofday(&startTime, 0);
122         gettimeofday(&tv, 0);
123         sec = tv.tv_sec - startTime.tv_sec;
124         msec = (tv.tv_usec - startTime.tv_usec) / 1000;
125         if (msec < 0) {
126             sec++;
127             msec += 1000;
128         }
129         vsprintf(buf, format, ap);
130         a = empth_self();
131         printf("%d:%02d.%03d %17s: %s\n", sec / 60, sec % 60, msec / 10,
132                a->name, buf);
133
134     }
135     va_end(ap);
136 }
137
138
139 int
140 empth_init(void **ctx_ptr, int flags)
141 {
142     empth_t *ctx;
143     sigset_t set;
144     struct sigaction act;
145
146     empth_flags = flags;
147     udata = ctx_ptr;
148
149     empth_init_signals();
150     sigemptyset(&set);
151     sigaddset(&set, SIGHUP);
152     sigaddset(&set, SIGINT);
153     sigaddset(&set, SIGTERM);
154     pthread_sigmask(SIG_BLOCK, &set, NULL);
155     act.sa_flags = 0;
156     sigemptyset(&act.sa_mask);
157     act.sa_handler = empth_alarm;
158     sigaction(SIGALRM, &act, NULL);
159
160     pthread_key_create(&ctx_key, NULL);
161     pthread_mutex_init(&mtx_ctxsw, NULL);
162
163     ctx = malloc(sizeof(empth_t));
164     if (!ctx) {
165         logerror("pthread init failed: not enough memory");
166         exit(1);
167     }
168     ctx->name = "Main";
169     ctx->ep = 0;
170     ctx->ud = 0;
171     ctx->id = pthread_self();
172     ctx->wakeup = 0;
173     pthread_setspecific(ctx_key, ctx);
174     pthread_mutex_lock(&mtx_ctxsw);
175     logerror("pthreads initialized");
176     return 0;
177 }
178
179
180 empth_t *
181 empth_create(void (*entry)(void *), int size, int flags,
182              char *name, void *ud)
183 {
184     pthread_t t;
185     pthread_attr_t attr;
186     empth_t *ctx;
187     int eno;
188
189     empth_status("creating new thread %s", name);
190     ef_make_stale();
191
192     ctx = malloc(sizeof(empth_t));
193     if (!ctx) {
194         logerror("not enough memory to create thread %s", name);
195         return NULL;
196     }
197     ctx->name = strdup(name);
198     ctx->ud = ud;
199     ctx->wakeup = 0;
200     ctx->ep = entry;
201
202     eno = pthread_attr_init(&attr);
203     if (eno) {
204         logerror("can not create thread attribute %s: %s",
205                  name, strerror(eno));
206         goto bad;
207     }
208     if (size < PTHREAD_STACK_MIN)
209         size = PTHREAD_STACK_MIN;
210     pthread_attr_setstacksize(&attr, size);
211     pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
212
213     eno = pthread_create(&t, &attr, empth_start, ctx);
214     if (eno) {
215         logerror("can not create thread: %s: %s", name, strerror(eno));
216         goto bad;
217     }
218     empth_status("new thread id is %ld", (long)t);
219     empth_yield();
220     return ctx;
221
222   bad:
223     pthread_attr_destroy(&attr);
224     free(ctx);
225     return NULL;
226 }
227
228
229 static void
230 empth_restorectx(void)
231 {
232     empth_t *ctx_ptr;
233
234     ctx_ptr = pthread_getspecific(ctx_key);
235     *udata = ctx_ptr->ud;
236     ctx_ptr->wakeup = 0;
237     empth_status("context restored");
238 }
239
240 empth_t *
241 empth_self(void)
242 {
243     return pthread_getspecific(ctx_key);
244 }
245
246 char *
247 empth_name(empth_t *thread)
248 {
249     return thread->name;
250 }
251
252 void
253 empth_set_name(empth_t *thread, char *name)
254 {
255     if (thread->name)
256         free(thread->name);
257     thread->name = strdup(name);
258 }
259
260 void
261 empth_exit(void)
262 {
263     empth_t *ctx = pthread_getspecific(ctx_key);
264
265     empth_status("empth_exit");
266     ef_make_stale();
267     pthread_mutex_unlock(&mtx_ctxsw);
268     free(ctx->name);
269     free(ctx);
270     pthread_exit(0);
271 }
272
273 void
274 empth_yield(void)
275 {
276     ef_make_stale();
277     pthread_mutex_unlock(&mtx_ctxsw);
278     pthread_mutex_lock(&mtx_ctxsw);
279     empth_restorectx();
280 }
281
282 int
283 empth_select(int fd, int flags, struct timeval *timeout)
284 {
285     fd_set readmask;
286     fd_set writemask;
287     struct timeval tv;
288     int n;
289     empth_t *ctx;
290     int res = 0;
291
292     if (CANT_HAPPEN(fd < 0 || fd >= FD_SETSIZE)) {
293         errno = EBADF;
294         return -1;
295     }
296
297     ef_make_stale();
298     pthread_mutex_unlock(&mtx_ctxsw);
299     empth_status("select on %d for %d", fd, flags);
300
301 again:
302     FD_ZERO(&readmask);
303     FD_ZERO(&writemask);
304     if (flags & EMPTH_FD_READ)
305         FD_SET(fd, &readmask);
306     if (flags & EMPTH_FD_WRITE)
307         FD_SET(fd, &writemask);
308
309     if (timeout)
310         tv = *timeout;
311     n = select(fd + 1, &readmask, &writemask, NULL, timeout ? &tv : NULL);
312     if (n < 0) {
313         ctx = pthread_getspecific(ctx_key);
314         if (ctx->wakeup) {
315             empth_status("select woken up");
316             res = 0;
317         } else if (errno == EINTR) {
318             empth_status("select broken by signal");
319             goto again;
320         } else {
321             empth_status("select failed (%s)", strerror(errno));
322             res = -1;
323         }
324     } else if (n == 0) {
325         empth_status("select timed out");
326         res = 0;
327     } else if (flags == EMPTH_FD_READ && FD_ISSET(fd, &readmask)) {
328         empth_status("input ready");
329         res = 1;
330     } else if (flags == EMPTH_FD_WRITE && FD_ISSET(fd, &writemask)) {
331         empth_status("output ready");
332         res = 1;
333     }
334
335     pthread_mutex_lock(&mtx_ctxsw);
336     empth_restorectx();
337     return res;
338 }
339
340 static void
341 empth_alarm(int sig)
342 {
343     /*
344      * Nothing to do --- we handle this signal just to let
345      * empth_wakeup() interrupt system calls.
346      */
347 }
348
349 void
350 empth_wakeup(empth_t *a)
351 {
352     empth_status("waking up thread %s", a->name);
353     a->wakeup = 1;
354     pthread_kill(a->id, SIGALRM);
355 }
356
357 int
358 empth_sleep(time_t until)
359 {
360     empth_t *ctx = pthread_getspecific(ctx_key);
361     time_t now;
362     struct timeval tv;
363     int res;
364
365     ef_make_stale();
366     pthread_mutex_unlock(&mtx_ctxsw);
367     do {
368         now = time(NULL);
369         tv.tv_sec = until >= now ? until - now : 0;
370         tv.tv_usec = 0;
371         empth_status("going to sleep %ld sec", (long)tv.tv_sec);
372         res = select(0, NULL, NULL, NULL, &tv);
373     } while (res < 0 && !ctx->wakeup);
374     empth_status("sleep done. Waiting for lock");
375     pthread_mutex_lock(&mtx_ctxsw);
376     empth_restorectx();
377     return res;
378 }
379
380 int
381 empth_wait_for_signal(void)
382 {
383     sigset_t set;
384     int sig, err;
385
386     ef_make_stale();
387     sigemptyset(&set);
388     sigaddset(&set, SIGHUP);
389     sigaddset(&set, SIGINT);
390     sigaddset(&set, SIGTERM);
391     pthread_mutex_unlock(&mtx_ctxsw);
392     for (;;) {
393         empth_status("waiting for signals");
394         err = sigwait(&set, &sig);
395         if (CANT_HAPPEN(err)) {
396             sleep(60);
397             continue;
398         }
399         empth_status("got awaited signal %d", sig);
400         pthread_mutex_lock(&mtx_ctxsw);
401         empth_restorectx();
402         return sig;
403     }
404 }
405
406 empth_rwlock_t *
407 empth_rwlock_create(char *name)
408 {
409     empth_rwlock_t *rwlock;
410
411     rwlock = malloc(sizeof(*rwlock));
412     if (!rwlock)
413         return NULL;
414
415     if (pthread_cond_init(&rwlock->can_read, NULL) != 0
416         || pthread_cond_init(&rwlock->can_write, NULL) != 0) {
417         free(rwlock);
418         return NULL;
419     }
420
421     rwlock->name = strdup(name);
422     rwlock->nread = rwlock->nwrite = 0;
423     return rwlock;
424 }
425
426 void
427 empth_rwlock_destroy(empth_rwlock_t *rwlock)
428 {
429     pthread_cond_destroy(&rwlock->can_read);
430     pthread_cond_destroy(&rwlock->can_write);
431     free(rwlock->name);
432     free(rwlock);
433 }
434
435 void
436 empth_rwlock_wrlock(empth_rwlock_t *rwlock)
437 {
438     empth_status("wrlock %s %d %d",
439                  rwlock->name, rwlock->nread, rwlock->nwrite);
440     ef_make_stale();
441     rwlock->nwrite++;
442     while (rwlock->nread != 0 || rwlock->nwrite != 1) {
443         empth_status("waiting for wrlock %s", rwlock->name);
444         pthread_cond_wait(&rwlock->can_write, &mtx_ctxsw);
445         empth_status("got wrlock %s %d %d",
446                      rwlock->name, rwlock->nread, rwlock->nwrite);
447         empth_restorectx();
448     }
449 }
450
451 void
452 empth_rwlock_rdlock(empth_rwlock_t *rwlock)
453 {
454     empth_status("rdlock %s %d %d",
455                  rwlock->name, rwlock->nread, rwlock->nwrite);
456     ef_make_stale();
457     while (rwlock->nwrite) {
458         empth_status("waiting for rdlock %s", rwlock->name);
459         pthread_cond_wait(&rwlock->can_read, &mtx_ctxsw);
460         empth_status("got rdlock %s %d %d",
461                      rwlock->name, rwlock->nread, rwlock->nwrite);
462         empth_restorectx();
463     }
464     rwlock->nread++;
465 }
466
467 void
468 empth_rwlock_unlock(empth_rwlock_t *rwlock)
469 {
470     if (CANT_HAPPEN(!rwlock->nread && !rwlock->nwrite))
471         return;
472     if (rwlock->nread) {        /* holding read lock */
473         if (!--rwlock->nread)
474             pthread_cond_signal(&rwlock->can_write);
475     } else {
476         rwlock->nwrite--;
477         pthread_cond_signal(&rwlock->can_write);
478     }
479     if (rwlock->nwrite == 0)
480         pthread_cond_broadcast(&rwlock->can_read);
481 }