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