]> git.pond.sub.org Git - empserver/blob - src/lib/empthread/ntthread.c
(va_start) [_WIN32]: For va_start() requires stdarg.h.
[empserver] / src / lib / empthread / ntthread.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  *  ntthread.c: Interface from Empire threads to Windows NT threads
29  * 
30  *  Known contributors to this file:
31  *     Doug Hay, 1998
32  *     Steve McClure, 1998
33  *     Ron Koenderink, 2004-2007
34  */
35
36 /*
37  * EMPTHREADs for Windows NT.
38  *
39  * Actually, threads for any Win32 platform, like Win95, Win98, WinCE,
40  * and whatever other toy OSs are in our future from Microsoft.
41  *
42  * WIN32 has a full pre-emptive threading environment.  But Empire can
43  * not handle pre-emptive threading.  Thus, we will use the threads,
44  * but limit the preemption using a Mutex.
45  */
46
47 #include <config.h>
48
49 #include <errno.h>
50 #include <signal.h>
51 #include <stdio.h>
52 #include <stdarg.h>
53 #include <sys/types.h>
54 #include <time.h>
55 #include <winsock2.h>
56 #undef NS_ALL
57 #include <windows.h>
58 #include <process.h>
59 /* Note: unistd.h(posixio.c) is not thread-safe.
60  * It may be used *only* while holding hThreadMutex.
61  */
62 #include "unistd.h"
63 #include "misc.h"
64 #include "empthread.h"
65 #include "prototypes.h"
66
67 #define loc_MIN_THREAD_STACK  16384
68
69 /************************
70  * loc_Thread
71  */
72 struct loc_Thread {
73
74     /* The thread name, passed in at create time. */
75     char szName[17];
76
77     /* True if this is the main line, and not a real thread. */
78     BOOL bMainThread;
79
80     /* The user data passed in at create time. */
81     void *pvUserData;
82
83     /* True if this thread has been killed. */
84     BOOL bKilled;
85
86     /* The entry function for the thread. */
87     void (*pfnEntry) (void *);
88
89     /* The system thread ID. */
90     unsigned long ulThreadID;
91
92     /* An Mutex that the thread will wait/sleep on. */
93     HANDLE hThreadEvent;
94 };
95
96
97 /************************
98  * loc_RWLock
99  *
100  * Invariants
101  *      must hold at function call, return, sleep
102  *      and resume from sleep.
103  *
104  * any state:
105  *      nwrite >= 0
106  *      nread >= 0
107
108  * if unlocked:
109  *      can_read set
110  *      can_write set
111  *      nwrite == 0
112  *      nread == 0
113  *
114  * if read-locked without writers contending:
115  *      can_read set
116  *      can_write clear
117  *      nwrite == 0
118  *      nread > 0
119  *
120  * if read-locked with writers contending:
121  *      can_read clear
122  *      can_write clear
123  *      nwrite > 0    #writers blocked
124  *      nread > 0
125  *
126  * if write-locked:
127  *      can_read clear
128  *      can_write clear
129  *      nwrite > 0    #writers blocked + 1
130  *      nread == 0
131  *
132  * To ensure consistency, state normally changes only while the
133  * thread changing it holds hThreadMutex.
134  *
135  */
136 struct loc_RWLock {
137     char name[17];      /* The thread name, passed in at create time. */
138     HANDLE can_read;    /* Manual event -- allows read locks */
139     HANDLE can_write;   /* Auto-reset event -- allows write locks */
140     int nread;          /* number of active readers */
141     int nwrite;         /* total number of writers (active and waiting) */
142 };
143
144 /* This is the thread exclusion/non-premption mutex. */
145 /* The running thread has this MUTEX, and all others are */
146 /* either blocked on it, or waiting for some OS response. */
147 static HANDLE hThreadMutex;
148
149 /* This is the thread startup event. */
150 /* We use this to lockstep when we are starting up threads. */
151 static HANDLE hThreadStartEvent;
152
153 /* This is an event used to wakeup the main thread */
154 /* to start the shutdown sequence. */
155 static HANDLE hShutdownEvent;
156
157 /* The Thread Local Storage index.  We store the pThread pointer */
158 /* for each thread at this index. */
159 static DWORD dwTLSIndex;
160
161 /* The current running thread. */
162 static empth_t *pCurThread;
163
164 /* Ticks at start */
165 static unsigned long ulTickAtStart;
166
167 /* Pointer out to global context.  "player". */
168 /* From empth_init parameter. */
169 static void **ppvUserData;
170
171 /* Global flags.  From empth_init parameter. */
172 static int global_flags;
173
174
175 /************************
176  * loc_debug
177  *
178  * Print out the current thread's status??
179  */
180 static void
181 loc_debug(const char *pszFmt, ...)
182 {
183     va_list vaList;
184     unsigned long ulCurTick;
185     unsigned long ulRunTick;
186     unsigned long ulMs, ulSec, ulMin, ulHr;
187     empth_t *pThread = TlsGetValue(dwTLSIndex);
188     char buf[1024];
189
190     if ((global_flags & EMPTH_PRINT) != 0) {
191
192         /* Ticks are in milliseconds */
193         ulCurTick = GetTickCount();
194
195         ulRunTick = ulCurTick - ulTickAtStart;
196         ulMs = ulRunTick % 1000L;
197         ulSec = (ulRunTick / 1000L) % 60L;
198         ulMin = (ulRunTick / (60L * 1000L)) % 60L;
199         ulHr = (ulRunTick / (60L * 60L * 1000L));
200
201         va_start(vaList, pszFmt);
202         vsprintf(buf, pszFmt, vaList);
203         va_end(vaList);
204
205         if (pThread) {
206             printf("%ld:%02ld:%02ld.%03ld %17s: %s\n",
207                    ulHr, ulMin, ulSec, ulMs, pThread->szName, buf);
208         } else {
209             printf("%ld:%02ld:%02ld.%03ld %17s: %s\n",
210                    ulHr, ulMin, ulSec, ulMs, "UNKNOWN", buf);
211         }
212
213     }
214 }
215
216 /************************
217  * loc_FreeThreadInfo
218  */
219 static void
220 loc_FreeThreadInfo(empth_t *pThread)
221 {
222     if (pThread) {
223         if (pThread->hThreadEvent)
224             CloseHandle(pThread->hThreadEvent);
225         memset(pThread, 0, sizeof(*pThread));
226         free(pThread);
227     }
228 }
229
230 /************************
231  * loc_RunThisThread
232  *
233  * This thread wants to run.
234  * When this function returns, the globals are set to this thread
235  * info, and the thread owns the MUTEX.
236  */
237 static void
238 loc_RunThisThread(HANDLE hWaitObject)
239 {
240     HANDLE hWaitObjects[2];
241
242     empth_t *pThread = TlsGetValue(dwTLSIndex);
243
244     if (pThread->bKilled) {
245         if (!pThread->bMainThread) {
246             TlsSetValue(dwTLSIndex, NULL);
247             loc_FreeThreadInfo(pThread);
248             _endthread();
249         }
250     }
251
252     hWaitObjects[0] = hThreadMutex;
253     hWaitObjects[1] = hWaitObject;
254
255     WaitForMultipleObjects(hWaitObject ? 2 : 1, hWaitObjects,
256                            TRUE, INFINITE);
257
258     if (!pCurThread) {
259         /* Set the globals to this thread. */
260         *ppvUserData = pThread->pvUserData;
261
262         pCurThread = pThread;
263     } else {
264         /* Hmm, a problem, eh? */
265         logerror("RunThisThread, someone already running.");
266     }
267 }
268
269 /************************
270  * loc_BlockThisThread
271  *
272  * This thread was running.  It no longer wants to.
273  */
274 static void
275 loc_BlockThisThread(void)
276 {
277     empth_t *pThread = TlsGetValue(dwTLSIndex);
278
279     if (pCurThread == pThread) {
280         /* Reset the globals back to original */
281
282         pCurThread = NULL;
283         *ppvUserData = NULL;
284
285         /* Release the MUTEX */
286         ReleaseMutex(hThreadMutex);
287     } else {
288         /* Hmm, this thread was not the running one. */
289         logerror("BlockThisThread, not running.");
290     }
291 }
292
293 /************************
294  * loc_Exit_Handler
295  *
296  * Ctrl-C, Ctrl-Break, Window-Closure, User-Logging-Off or
297  * System-Shutdown will initiate a shutdown.
298  * This is done by calling empth_request_shutdown()
299  */
300 static BOOL
301 loc_Exit_Handler(DWORD fdwCtrlType)
302 {
303     switch (fdwCtrlType) { 
304         case CTRL_C_EVENT:
305         case CTRL_CLOSE_EVENT:
306         case CTRL_BREAK_EVENT: 
307         case CTRL_LOGOFF_EVENT: 
308         case CTRL_SHUTDOWN_EVENT: 
309             empth_request_shutdown();
310             return TRUE;
311         default:
312             return FALSE;
313     }
314 }
315
316 /************************
317  * empth_threadMain
318  *
319  * This is the main line of each thread.
320  * This is really a static local func....
321  * Note: As the POSIX compatibility layer is not thread safe
322  * this function can not open or create any files or sockets until
323  * loc_RunThisThread() is called
324  */
325 static void
326 empth_threadMain(void *pvData)
327 {
328     time_t now;
329
330     empth_t *pThread = pvData;
331
332     /* Out of here... */
333     if (!pvData)
334         return;
335
336     /* Store pThread on this thread. */
337     TlsSetValue(dwTLSIndex, pvData);
338
339     /* Get the ID of the thread. */
340     pThread->ulThreadID = GetCurrentThreadId();
341
342     /* Signal that the thread has started. */
343     SetEvent(hThreadStartEvent);
344
345     /* seed the rand() function */
346     time(&now);
347     srand(now ^ (unsigned)pThread);
348
349     /* Switch to this thread context */
350     loc_RunThisThread(NULL);
351
352     /* Run the thread. */
353     if (pThread->pfnEntry)
354         pThread->pfnEntry(pThread->pvUserData);
355
356     /* Kill the thread. */
357     empth_exit();
358 }
359
360 /************************
361  * empth_init
362  *
363  * Initialize the thread environment.
364  *
365  * This is called from the program main line.
366  */
367 int
368 empth_init(void **ctx_ptr, int flags)
369 {
370     empth_t *pThread = NULL;
371
372     ulTickAtStart = GetTickCount();
373     ppvUserData = ctx_ptr;
374     global_flags = flags;
375     dwTLSIndex = TlsAlloc();
376
377     /* Create the thread mutex. */
378     /* Initally unowned. */
379     hThreadMutex = CreateMutex(NULL, FALSE, NULL);
380     if (!hThreadMutex) {
381         logerror("Failed to create mutex %lu", GetLastError());
382         return 0;
383     }
384
385     /* Create the thread start event. */
386     /* Automatic state reset. */
387     hThreadStartEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
388     if (!hThreadStartEvent) {
389         logerror("Failed to create start event %lu", GetLastError());
390         return 0;
391     }
392
393     /* Create the shutdown event for the main thread. */
394     /* Manual reset */
395     hShutdownEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
396     if (!hShutdownEvent) {
397         logerror("Failed to create shutdown event %lu", GetLastError());
398         return 0;
399     }
400     SetConsoleCtrlHandler((PHANDLER_ROUTINE)loc_Exit_Handler, TRUE);
401
402     /* Create the global Thread context. */
403     pThread = malloc(sizeof(*pThread));
404     if (!pThread) {
405         logerror("not enough memory to create main thread.");
406         return 0;
407     }
408     memset(pThread, 0, sizeof(*pThread));
409
410     strncpy(pThread->szName, "Main", sizeof(pThread->szName) - 1);
411     pThread->ulThreadID = GetCurrentThreadId();
412     pThread->bMainThread = TRUE;
413
414     TlsSetValue(dwTLSIndex, pThread);
415
416     /* Make this the running thread. */
417     loc_RunThisThread(NULL);
418
419     logerror("NT pthreads initialized");
420     return 0;
421 }
422
423
424 /************************
425  * empth_create
426  *
427  * Create a new thread.
428  *
429  * entry - entry point function for thread.
430  * size  - stack size.
431  * flags - debug control.
432  *           LWP_STACKCHECK  - not needed
433  * name  - name of the thread, for debug.
434  * ud    - "user data".  The "ctx_ptr" gets this value
435  *         when the thread is active.
436  *         It is also passed to the entry function...
437  */
438 empth_t *
439 empth_create(void (*entry)(void *), int size, int flags,
440              char *name, void *ud)
441 {
442     empth_t *pThread = NULL;
443
444     loc_debug("creating new thread %s", name);
445
446     pThread = malloc(sizeof(*pThread));
447     if (!pThread) {
448         logerror("not enough memory to create thread %s", name);
449         return NULL;
450     }
451     memset(pThread, 0, sizeof(*pThread));
452
453     strncpy(pThread->szName, name, sizeof(pThread->szName) - 1);
454     pThread->pvUserData = ud;
455     pThread->pfnEntry = entry;
456     pThread->bMainThread = FALSE;
457
458     /* Create thread event, auto reset. */
459     pThread->hThreadEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
460
461     if (size < loc_MIN_THREAD_STACK)
462         size = loc_MIN_THREAD_STACK;
463
464     pThread->ulThreadID = _beginthread(empth_threadMain, size, pThread);
465     if (pThread->ulThreadID == 1L) {
466         logerror("can not create thread: %s: %s", name, strerror(errno));
467         goto bad;
468     }
469
470     loc_debug("new thread id is %ld", pThread->ulThreadID);
471     empth_yield();
472     return pThread;
473
474   bad:
475     if (pThread) {
476         loc_FreeThreadInfo(pThread);
477     }
478     return NULL;
479 }
480
481
482 /************************
483  * empth_self
484  */
485 empth_t *
486 empth_self(void)
487 {
488     empth_t *pThread = TlsGetValue(dwTLSIndex);
489
490     return pThread;
491 }
492
493 /************************
494  * empth_exit
495  */
496 void
497 empth_exit(void)
498 {
499     empth_t *pThread = TlsGetValue(dwTLSIndex);
500
501     loc_debug("empth_exit");
502     loc_BlockThisThread();
503
504     TlsSetValue(dwTLSIndex, NULL);
505     loc_FreeThreadInfo(pThread);
506     _endthread();
507 }
508
509 /************************
510  * empth_yield
511  *
512  * Yield processing to another thread.
513  */
514 void
515 empth_yield(void)
516 {
517     loc_BlockThisThread();
518     loc_RunThisThread(NULL);
519 }
520
521 /************************
522  * empth_terminate
523  *
524  * Kill off the thread.
525  */
526 void
527 empth_terminate(empth_t *pThread)
528 {
529     loc_debug("killing thread %s", pThread->szName);
530     pThread->bKilled = TRUE;
531
532     SetEvent(pThread->hThreadEvent);
533 }
534
535 /************************
536  * empth_select
537  *
538  * Do a select on the given file.
539  * Wait for IO on it.
540  *
541  * This would be one of the main functions used within gen\io.c
542  */
543 void
544 empth_select(int fd, int flags)
545 {
546     int handle;
547     WSAEVENT hEventObject[2];
548     empth_t *pThread = TlsGetValue(dwTLSIndex);
549
550     loc_debug("%s select on %d",
551               flags == EMPTH_FD_READ ? "read" : "write", fd);
552     loc_BlockThisThread();
553
554     hEventObject[0] = WSACreateEvent();
555     hEventObject[1] = pThread->hThreadEvent;
556
557     handle = posix_fd2socket(fd);
558     CANT_HAPPEN(handle < 0);
559
560     if (flags == EMPTH_FD_READ)
561         WSAEventSelect(handle, hEventObject[0], FD_READ | FD_ACCEPT | FD_CLOSE);
562     else if (flags == EMPTH_FD_WRITE)
563         WSAEventSelect(handle, hEventObject[0], FD_WRITE | FD_CLOSE);
564     else {
565         logerror("bad flag %d passed to empth_select", flags);
566         empth_exit();
567     }
568
569     WSAWaitForMultipleEvents(2, hEventObject, FALSE, WSA_INFINITE, FALSE);
570
571     WSAEventSelect(handle, hEventObject[0], 0);
572
573     WSACloseEvent(hEventObject[0]);
574
575     loc_RunThisThread(NULL);
576 }
577
578 /************************
579  * empth_wakeup
580  *
581  * Wake up the specified thread.
582  */
583 void
584 empth_wakeup(empth_t *pThread)
585 {
586     loc_debug("waking up thread %s", pThread->szName);
587
588     /* Let it run if it is blocked... */
589     SetEvent(pThread->hThreadEvent);
590 }
591
592 /************************
593  * empth_sleep
594  *
595  * Put the given thread to sleep...
596  */
597 int
598 empth_sleep(time_t until)
599 {
600     long lSec;
601     empth_t *pThread = TlsGetValue(dwTLSIndex);
602     int iReturn = 0;
603
604     if ((lSec = until - time(0)) > 0) {
605         loc_BlockThisThread();
606         loc_debug("going to sleep %ld sec", lSec);
607
608         if (WaitForSingleObject(pThread->hThreadEvent, lSec * 1000L) !=
609             WAIT_TIMEOUT)
610             iReturn = -1;
611
612         loc_debug("sleep done. Waiting to run.");
613         loc_RunThisThread(NULL);
614     }
615     return iReturn;
616 }
617
618 /************************
619  * empth_request_shutdown
620  *
621  * This wakes up empth_wait_for_signal() so shutdown can proceed.
622  * This is done by signalling hShutdownEvent.
623  */
624 void
625 empth_request_shutdown(void)
626 {
627     SetEvent(hShutdownEvent);
628 }
629
630 int
631 empth_wait_for_signal(void)
632 {
633     loc_BlockThisThread();
634     loc_RunThisThread(hShutdownEvent);
635     return SIGTERM;
636 }
637
638 empth_rwlock_t *
639 empth_rwlock_create(char *name)
640 {
641     empth_rwlock_t *rwlock;
642
643     rwlock = malloc(sizeof(*rwlock));
644     if (!rwlock)
645         return NULL;
646
647     memset(rwlock, 0, sizeof(*rwlock));
648     strncpy(rwlock->name, name, sizeof(rwlock->name) - 1);
649
650     if ((rwlock->can_read = CreateEvent(NULL, TRUE, TRUE, NULL)) == NULL) {
651         logerror("rwlock_create: failed to create reader event %s at %s:%d",
652             name, __FILE__, __LINE__);
653         free(rwlock);
654         return NULL;
655     }
656
657     if ((rwlock->can_write = CreateEvent(NULL, FALSE, TRUE, NULL)) == NULL) {
658         logerror("rwlock_create: failed to create writer event %s at %s:%d",
659             name, __FILE__, __LINE__);
660         CloseHandle(rwlock->can_read);
661         free(rwlock);
662         return NULL;
663     }
664     return rwlock;
665 }
666
667 void
668 empth_rwlock_destroy(empth_rwlock_t *rwlock)
669 {
670     if (CANT_HAPPEN(rwlock->nread || rwlock->nwrite))
671         return;
672     CloseHandle(rwlock->can_read);
673     CloseHandle(rwlock->can_write);
674     free(rwlock);
675 }
676
677 void
678 empth_rwlock_wrlock(empth_rwlock_t *rwlock)
679 {
680     /* block any new readers */
681     ResetEvent(rwlock->can_read);
682     rwlock->nwrite++;
683     loc_BlockThisThread();
684     loc_RunThisThread(rwlock->can_write);
685     CANT_HAPPEN(rwlock->nread != 0);
686 }
687
688 void
689 empth_rwlock_rdlock(empth_rwlock_t *rwlock)
690 {
691     loc_BlockThisThread();
692     loc_RunThisThread(rwlock->can_read);
693     ResetEvent(rwlock->can_write);
694     rwlock->nread++;
695 }
696
697 void
698 empth_rwlock_unlock(empth_rwlock_t *rwlock)
699 {
700     if (CANT_HAPPEN(!rwlock->nread && !rwlock->nwrite))
701         return;
702    if (rwlock->nread) { /* holding read lock */
703         rwlock->nread--;
704         if (rwlock->nread == 0)
705             SetEvent(rwlock->can_write);
706     } else {
707         rwlock->nwrite--;
708         SetEvent(rwlock->can_write);
709     }
710     if (rwlock->nwrite == 0)
711         SetEvent(rwlock->can_read);
712 }