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