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