1 /* GLIB - Library of useful routines for C programming
2 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
3 *
4 * gthread.c: solaris thread system implementation
5 * Copyright 1998-2001 Sebastian Wilhelmi; University of Karlsruhe
6 * Copyright 2001 Hans Breuer
7 *
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
12 *
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
17 *
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
20 */
21
22 /*
23 * Modified by the GLib Team and others 1997-2000. See the AUTHORS
24 * file for a list of people on the GLib Team. See the ChangeLog
25 * files for a list of changes. These files are distributed with
26 * GLib at ftp://ftp.gtk.org/pub/gtk/.
27 */
28
29 /* The GMutex and GCond implementations in this file are some of the
30 * lowest-level code in GLib. All other parts of GLib (messages,
31 * memory, slices, etc) assume that they can freely use these facilities
32 * without risking recursion.
33 *
34 * As such, these functions are NOT permitted to call any other part of
35 * GLib.
36 *
37 * The thread manipulation functions (create, exit, join, etc.) have
38 * more freedom -- they can do as they please.
39 */
40
41 #include "config.h"
42
43 #include "glib.h"
44 #include "glib-init.h"
45 #include "gthread.h"
46 #include "gthreadprivate.h"
47 #include "gslice.h"
48
49 #include <windows.h>
50
51 #include <process.h>
52 #include <stdlib.h>
53 #include <stdio.h>
54
55 static void
g_thread_abort(gint status,const gchar * function)56 g_thread_abort (gint status,
57 const gchar *function)
58 {
59 fprintf (stderr, "GLib (gthread-win32.c): Unexpected error from C library during '%s': %s. Aborting.\n",
60 strerror (status), function);
61 g_abort ();
62 }
63
64 /* Starting with Vista and Windows 2008, we have access to the
65 * CONDITION_VARIABLE and SRWLock primitives on Windows, which are
66 * pretty reasonable approximations of the primitives specified in
67 * POSIX 2001 (pthread_cond_t and pthread_mutex_t respectively).
68 *
69 * Both of these types are structs containing a single pointer. That
70 * pointer is used as an atomic bitfield to support user-space mutexes
71 * that only get the kernel involved in cases of contention (similar
72 * to how futex()-based mutexes work on Linux). The biggest advantage
73 * of these new types is that they can be statically initialised to
74 * zero. That means that they are completely ABI compatible with our
75 * GMutex and GCond APIs.
76 */
77
78 /* {{{1 GMutex */
79 void
g_mutex_init(GMutex * mutex)80 g_mutex_init (GMutex *mutex)
81 {
82 InitializeSRWLock ((gpointer) mutex);
83 }
84
85 void
g_mutex_clear(GMutex * mutex)86 g_mutex_clear (GMutex *mutex)
87 {
88 }
89
90 void
g_mutex_lock(GMutex * mutex)91 g_mutex_lock (GMutex *mutex)
92 {
93 AcquireSRWLockExclusive ((gpointer) mutex);
94 }
95
96 gboolean
g_mutex_trylock(GMutex * mutex)97 g_mutex_trylock (GMutex *mutex)
98 {
99 return TryAcquireSRWLockExclusive ((gpointer) mutex);
100 }
101
102 void
g_mutex_unlock(GMutex * mutex)103 g_mutex_unlock (GMutex *mutex)
104 {
105 ReleaseSRWLockExclusive ((gpointer) mutex);
106 }
107
108 /* {{{1 GRecMutex */
109
110 static CRITICAL_SECTION *
g_rec_mutex_impl_new(void)111 g_rec_mutex_impl_new (void)
112 {
113 CRITICAL_SECTION *cs;
114
115 cs = g_slice_new (CRITICAL_SECTION);
116 InitializeCriticalSection (cs);
117
118 return cs;
119 }
120
121 static void
g_rec_mutex_impl_free(CRITICAL_SECTION * cs)122 g_rec_mutex_impl_free (CRITICAL_SECTION *cs)
123 {
124 DeleteCriticalSection (cs);
125 g_slice_free (CRITICAL_SECTION, cs);
126 }
127
128 static CRITICAL_SECTION *
g_rec_mutex_get_impl(GRecMutex * mutex)129 g_rec_mutex_get_impl (GRecMutex *mutex)
130 {
131 CRITICAL_SECTION *impl = mutex->p;
132
133 if G_UNLIKELY (mutex->p == NULL)
134 {
135 impl = g_rec_mutex_impl_new ();
136 if (InterlockedCompareExchangePointer (&mutex->p, impl, NULL) != NULL)
137 g_rec_mutex_impl_free (impl);
138 impl = mutex->p;
139 }
140
141 return impl;
142 }
143
144 void
g_rec_mutex_init(GRecMutex * mutex)145 g_rec_mutex_init (GRecMutex *mutex)
146 {
147 mutex->p = g_rec_mutex_impl_new ();
148 }
149
150 void
g_rec_mutex_clear(GRecMutex * mutex)151 g_rec_mutex_clear (GRecMutex *mutex)
152 {
153 g_rec_mutex_impl_free (mutex->p);
154 }
155
156 void
g_rec_mutex_lock(GRecMutex * mutex)157 g_rec_mutex_lock (GRecMutex *mutex)
158 {
159 EnterCriticalSection (g_rec_mutex_get_impl (mutex));
160 }
161
162 void
g_rec_mutex_unlock(GRecMutex * mutex)163 g_rec_mutex_unlock (GRecMutex *mutex)
164 {
165 LeaveCriticalSection (mutex->p);
166 }
167
168 gboolean
g_rec_mutex_trylock(GRecMutex * mutex)169 g_rec_mutex_trylock (GRecMutex *mutex)
170 {
171 return TryEnterCriticalSection (g_rec_mutex_get_impl (mutex));
172 }
173
174 /* {{{1 GRWLock */
175
176 void
g_rw_lock_init(GRWLock * lock)177 g_rw_lock_init (GRWLock *lock)
178 {
179 InitializeSRWLock ((gpointer) lock);
180 }
181
182 void
g_rw_lock_clear(GRWLock * lock)183 g_rw_lock_clear (GRWLock *lock)
184 {
185 }
186
187 void
g_rw_lock_writer_lock(GRWLock * lock)188 g_rw_lock_writer_lock (GRWLock *lock)
189 {
190 AcquireSRWLockExclusive ((gpointer) lock);
191 }
192
193 gboolean
g_rw_lock_writer_trylock(GRWLock * lock)194 g_rw_lock_writer_trylock (GRWLock *lock)
195 {
196 return TryAcquireSRWLockExclusive ((gpointer) lock);
197 }
198
199 void
g_rw_lock_writer_unlock(GRWLock * lock)200 g_rw_lock_writer_unlock (GRWLock *lock)
201 {
202 ReleaseSRWLockExclusive ((gpointer) lock);
203 }
204
205 void
g_rw_lock_reader_lock(GRWLock * lock)206 g_rw_lock_reader_lock (GRWLock *lock)
207 {
208 AcquireSRWLockShared ((gpointer) lock);
209 }
210
211 gboolean
g_rw_lock_reader_trylock(GRWLock * lock)212 g_rw_lock_reader_trylock (GRWLock *lock)
213 {
214 return TryAcquireSRWLockShared ((gpointer) lock);
215 }
216
217 void
g_rw_lock_reader_unlock(GRWLock * lock)218 g_rw_lock_reader_unlock (GRWLock *lock)
219 {
220 ReleaseSRWLockShared ((gpointer) lock);
221 }
222
223 /* {{{1 GCond */
224 void
g_cond_init(GCond * cond)225 g_cond_init (GCond *cond)
226 {
227 InitializeConditionVariable ((gpointer) cond);
228 }
229
230 void
g_cond_clear(GCond * cond)231 g_cond_clear (GCond *cond)
232 {
233 }
234
235 void
g_cond_signal(GCond * cond)236 g_cond_signal (GCond *cond)
237 {
238 WakeConditionVariable ((gpointer) cond);
239 }
240
241 void
g_cond_broadcast(GCond * cond)242 g_cond_broadcast (GCond *cond)
243 {
244 WakeAllConditionVariable ((gpointer) cond);
245 }
246
247 void
g_cond_wait(GCond * cond,GMutex * entered_mutex)248 g_cond_wait (GCond *cond,
249 GMutex *entered_mutex)
250 {
251 SleepConditionVariableSRW ((gpointer) cond, (gpointer) entered_mutex, INFINITE, 0);
252 }
253
254 gboolean
g_cond_wait_until(GCond * cond,GMutex * entered_mutex,gint64 end_time)255 g_cond_wait_until (GCond *cond,
256 GMutex *entered_mutex,
257 gint64 end_time)
258 {
259 gint64 span, start_time;
260 DWORD span_millis;
261 gboolean signalled;
262
263 start_time = g_get_monotonic_time ();
264 do
265 {
266 span = end_time - start_time;
267
268 if G_UNLIKELY (span < 0)
269 span_millis = 0;
270 else if G_UNLIKELY (span > G_GINT64_CONSTANT (1000) * (DWORD) INFINITE)
271 span_millis = INFINITE;
272 else
273 /* Round up so we don't time out too early */
274 span_millis = (span + 1000 - 1) / 1000;
275
276 /* We never want to wait infinitely */
277 if (span_millis >= INFINITE)
278 span_millis = INFINITE - 1;
279
280 signalled = SleepConditionVariableSRW ((gpointer) cond, (gpointer) entered_mutex, span_millis, 0);
281 if (signalled)
282 break;
283
284 /* In case we didn't wait long enough after a timeout, wait again for the
285 * remaining time */
286 start_time = g_get_monotonic_time ();
287 }
288 while (start_time < end_time);
289
290 return signalled;
291 }
292
293 /* {{{1 GPrivate */
294
295 typedef struct _GPrivateDestructor GPrivateDestructor;
296
297 struct _GPrivateDestructor
298 {
299 DWORD index;
300 GDestroyNotify notify;
301 GPrivateDestructor *next;
302 };
303
304 static GPrivateDestructor *g_private_destructors; /* (atomic) prepend-only */
305 static CRITICAL_SECTION g_private_lock;
306
307 static DWORD
g_private_get_impl(GPrivate * key)308 g_private_get_impl (GPrivate *key)
309 {
310 DWORD impl = (DWORD) key->p;
311
312 if G_UNLIKELY (impl == 0)
313 {
314 EnterCriticalSection (&g_private_lock);
315 impl = (DWORD) key->p;
316 if (impl == 0)
317 {
318 GPrivateDestructor *destructor;
319
320 impl = TlsAlloc ();
321
322 if (impl == TLS_OUT_OF_INDEXES)
323 g_thread_abort (0, "TlsAlloc");
324
325 if (key->notify != NULL)
326 {
327 destructor = malloc (sizeof (GPrivateDestructor));
328 if G_UNLIKELY (destructor == NULL)
329 g_thread_abort (errno, "malloc");
330 destructor->index = impl;
331 destructor->notify = key->notify;
332 destructor->next = g_atomic_pointer_get (&g_private_destructors);
333
334 /* We need to do an atomic store due to the unlocked
335 * access to the destructor list from the thread exit
336 * function.
337 *
338 * It can double as a sanity check...
339 */
340 if (!g_atomic_pointer_compare_and_exchange (&g_private_destructors,
341 destructor->next,
342 destructor))
343 g_thread_abort (0, "g_private_get_impl(1)");
344 }
345
346 /* Ditto, due to the unlocked access on the fast path */
347 if (!g_atomic_pointer_compare_and_exchange (&key->p, NULL, impl))
348 g_thread_abort (0, "g_private_get_impl(2)");
349 }
350 LeaveCriticalSection (&g_private_lock);
351 }
352
353 return impl;
354 }
355
356 gpointer
g_private_get(GPrivate * key)357 g_private_get (GPrivate *key)
358 {
359 return TlsGetValue (g_private_get_impl (key));
360 }
361
362 void
g_private_set(GPrivate * key,gpointer value)363 g_private_set (GPrivate *key,
364 gpointer value)
365 {
366 TlsSetValue (g_private_get_impl (key), value);
367 }
368
369 void
g_private_replace(GPrivate * key,gpointer value)370 g_private_replace (GPrivate *key,
371 gpointer value)
372 {
373 DWORD impl = g_private_get_impl (key);
374 gpointer old;
375
376 old = TlsGetValue (impl);
377 TlsSetValue (impl, value);
378 if (old && key->notify)
379 key->notify (old);
380 }
381
382 /* {{{1 GThread */
383
384 #define win32_check_for_error(what) G_STMT_START{ \
385 if (!(what)) \
386 g_error ("file %s: line %d (%s): error %s during %s", \
387 __FILE__, __LINE__, G_STRFUNC, \
388 g_win32_error_message (GetLastError ()), #what); \
389 }G_STMT_END
390
391 #define G_MUTEX_SIZE (sizeof (gpointer))
392
393 typedef BOOL (__stdcall *GTryEnterCriticalSectionFunc) (CRITICAL_SECTION *);
394
395 typedef struct
396 {
397 GRealThread thread;
398
399 GThreadFunc proxy;
400 HANDLE handle;
401 } GThreadWin32;
402
403 void
g_system_thread_free(GRealThread * thread)404 g_system_thread_free (GRealThread *thread)
405 {
406 GThreadWin32 *wt = (GThreadWin32 *) thread;
407
408 win32_check_for_error (CloseHandle (wt->handle));
409 g_slice_free (GThreadWin32, wt);
410 }
411
412 void
g_system_thread_exit(void)413 g_system_thread_exit (void)
414 {
415 _endthreadex (0);
416 }
417
418 static guint __stdcall
g_thread_win32_proxy(gpointer data)419 g_thread_win32_proxy (gpointer data)
420 {
421 GThreadWin32 *self = data;
422
423 self->proxy (self);
424
425 g_system_thread_exit ();
426
427 g_assert_not_reached ();
428
429 return 0;
430 }
431
432 gboolean
g_system_thread_get_scheduler_settings(GThreadSchedulerSettings * scheduler_settings)433 g_system_thread_get_scheduler_settings (GThreadSchedulerSettings *scheduler_settings)
434 {
435 HANDLE current_thread = GetCurrentThread ();
436 scheduler_settings->thread_prio = GetThreadPriority (current_thread);
437
438 return TRUE;
439 }
440
441 GRealThread *
g_system_thread_new(GThreadFunc proxy,gulong stack_size,const GThreadSchedulerSettings * scheduler_settings,const char * name,GThreadFunc func,gpointer data,GError ** error)442 g_system_thread_new (GThreadFunc proxy,
443 gulong stack_size,
444 const GThreadSchedulerSettings *scheduler_settings,
445 const char *name,
446 GThreadFunc func,
447 gpointer data,
448 GError **error)
449 {
450 GThreadWin32 *thread;
451 GRealThread *base_thread;
452 guint ignore;
453 const gchar *message = NULL;
454 int thread_prio;
455
456 thread = g_slice_new0 (GThreadWin32);
457 thread->proxy = proxy;
458 thread->handle = (HANDLE) NULL;
459 base_thread = (GRealThread*)thread;
460 base_thread->ref_count = 2;
461 base_thread->ours = TRUE;
462 base_thread->thread.joinable = TRUE;
463 base_thread->thread.func = func;
464 base_thread->thread.data = data;
465 base_thread->name = g_strdup (name);
466
467 thread->handle = (HANDLE) _beginthreadex (NULL, stack_size, g_thread_win32_proxy, thread,
468 CREATE_SUSPENDED, &ignore);
469
470 if (thread->handle == NULL)
471 {
472 message = "Error creating thread";
473 goto error;
474 }
475
476 /* For thread priority inheritance we need to manually set the thread
477 * priority of the new thread to the priority of the current thread. We
478 * also have to start the thread suspended and resume it after actually
479 * setting the priority here.
480 *
481 * On Windows, by default all new threads are created with NORMAL thread
482 * priority.
483 */
484
485 if (scheduler_settings)
486 {
487 thread_prio = scheduler_settings->thread_prio;
488 }
489 else
490 {
491 HANDLE current_thread = GetCurrentThread ();
492 thread_prio = GetThreadPriority (current_thread);
493 }
494
495 if (thread_prio == THREAD_PRIORITY_ERROR_RETURN)
496 {
497 message = "Error getting current thread priority";
498 goto error;
499 }
500
501 if (SetThreadPriority (thread->handle, thread_prio) == 0)
502 {
503 message = "Error setting new thread priority";
504 goto error;
505 }
506
507 if (ResumeThread (thread->handle) == -1)
508 {
509 message = "Error resuming new thread";
510 goto error;
511 }
512
513 return (GRealThread *) thread;
514
515 error:
516 {
517 gchar *win_error = g_win32_error_message (GetLastError ());
518 g_set_error (error, G_THREAD_ERROR, G_THREAD_ERROR_AGAIN,
519 "%s: %s", message, win_error);
520 g_free (win_error);
521 if (thread->handle)
522 CloseHandle (thread->handle);
523 g_slice_free (GThreadWin32, thread);
524 return NULL;
525 }
526 }
527
528 void
g_thread_yield(void)529 g_thread_yield (void)
530 {
531 Sleep(0);
532 }
533
534 void
g_system_thread_wait(GRealThread * thread)535 g_system_thread_wait (GRealThread *thread)
536 {
537 GThreadWin32 *wt = (GThreadWin32 *) thread;
538
539 win32_check_for_error (WAIT_FAILED != WaitForSingleObject (wt->handle, INFINITE));
540 }
541
542 #define EXCEPTION_SET_THREAD_NAME ((DWORD) 0x406D1388)
543
544 #ifndef _MSC_VER
545 static void *SetThreadName_VEH_handle = NULL;
546
547 static LONG __stdcall
SetThreadName_VEH(PEXCEPTION_POINTERS ExceptionInfo)548 SetThreadName_VEH (PEXCEPTION_POINTERS ExceptionInfo)
549 {
550 if (ExceptionInfo->ExceptionRecord != NULL &&
551 ExceptionInfo->ExceptionRecord->ExceptionCode == EXCEPTION_SET_THREAD_NAME)
552 return EXCEPTION_CONTINUE_EXECUTION;
553
554 return EXCEPTION_CONTINUE_SEARCH;
555 }
556 #endif
557
558 typedef struct _THREADNAME_INFO
559 {
560 DWORD dwType; /* must be 0x1000 */
561 LPCSTR szName; /* pointer to name (in user addr space) */
562 DWORD dwThreadID; /* thread ID (-1=caller thread) */
563 DWORD dwFlags; /* reserved for future use, must be zero */
564 } THREADNAME_INFO;
565
566 static void
SetThreadName(DWORD dwThreadID,LPCSTR szThreadName)567 SetThreadName (DWORD dwThreadID,
568 LPCSTR szThreadName)
569 {
570 THREADNAME_INFO info;
571 DWORD infosize;
572
573 info.dwType = 0x1000;
574 info.szName = szThreadName;
575 info.dwThreadID = dwThreadID;
576 info.dwFlags = 0;
577
578 infosize = sizeof (info) / sizeof (DWORD);
579
580 #ifdef _MSC_VER
581 __try
582 {
583 RaiseException (EXCEPTION_SET_THREAD_NAME, 0, infosize,
584 (const ULONG_PTR *) &info);
585 }
586 __except (EXCEPTION_EXECUTE_HANDLER)
587 {
588 }
589 #else
590 /* Without a debugger we *must* have an exception handler,
591 * otherwise raising an exception will crash the process.
592 */
593 if ((!IsDebuggerPresent ()) && (SetThreadName_VEH_handle == NULL))
594 return;
595
596 RaiseException (EXCEPTION_SET_THREAD_NAME, 0, infosize, (DWORD *) &info);
597 #endif
598 }
599
600 typedef HRESULT (WINAPI *pSetThreadDescription) (HANDLE hThread,
601 PCWSTR lpThreadDescription);
602 static pSetThreadDescription SetThreadDescriptionFunc = NULL;
603 HMODULE kernel32_module = NULL;
604
605 static gboolean
g_thread_win32_load_library(void)606 g_thread_win32_load_library (void)
607 {
608 /* FIXME: Add support for UWP app */
609 #if !defined(G_WINAPI_ONLY_APP)
610 static volatile gsize _init_once = 0;
611 if (g_once_init_enter (&_init_once))
612 {
613 kernel32_module = LoadLibraryW (L"kernel32.dll");
614 if (kernel32_module)
615 {
616 SetThreadDescriptionFunc =
617 (pSetThreadDescription) GetProcAddress (kernel32_module,
618 "SetThreadDescription");
619 if (!SetThreadDescriptionFunc)
620 FreeLibrary (kernel32_module);
621 }
622 g_once_init_leave (&_init_once, 1);
623 }
624 #endif
625
626 return !!SetThreadDescriptionFunc;
627 }
628
629 static gboolean
g_thread_win32_set_thread_desc(const gchar * name)630 g_thread_win32_set_thread_desc (const gchar *name)
631 {
632 HRESULT hr;
633 wchar_t *namew;
634
635 if (!g_thread_win32_load_library () || !name)
636 return FALSE;
637
638 namew = g_utf8_to_utf16 (name, -1, NULL, NULL, NULL);
639 if (!namew)
640 return FALSE;
641
642 hr = SetThreadDescriptionFunc (GetCurrentThread (), namew);
643
644 g_free (namew);
645 return SUCCEEDED (hr);
646 }
647
648 void
g_system_thread_set_name(const gchar * name)649 g_system_thread_set_name (const gchar *name)
650 {
651 /* Prefer SetThreadDescription over exception based way if available,
652 * since thread description set by SetThreadDescription will be preserved
653 * in dump file */
654 if (!g_thread_win32_set_thread_desc (name))
655 SetThreadName ((DWORD) -1, name);
656 }
657
658 /* {{{1 Epilogue */
659
660 void
g_thread_win32_init(void)661 g_thread_win32_init (void)
662 {
663 InitializeCriticalSection (&g_private_lock);
664
665 #ifndef _MSC_VER
666 SetThreadName_VEH_handle = AddVectoredExceptionHandler (1, &SetThreadName_VEH);
667 if (SetThreadName_VEH_handle == NULL)
668 {
669 /* This is bad, but what can we do? */
670 }
671 #endif
672 }
673
674 void
g_thread_win32_thread_detach(void)675 g_thread_win32_thread_detach (void)
676 {
677 gboolean dtors_called;
678
679 do
680 {
681 GPrivateDestructor *dtor;
682
683 /* We go by the POSIX book on this one.
684 *
685 * If we call a destructor then there is a chance that some new
686 * TLS variables got set by code called in that destructor.
687 *
688 * Loop until nothing is left.
689 */
690 dtors_called = FALSE;
691
692 for (dtor = g_atomic_pointer_get (&g_private_destructors); dtor; dtor = dtor->next)
693 {
694 gpointer value;
695
696 value = TlsGetValue (dtor->index);
697 if (value != NULL && dtor->notify != NULL)
698 {
699 /* POSIX says to clear this before the call */
700 TlsSetValue (dtor->index, NULL);
701 dtor->notify (value);
702 dtors_called = TRUE;
703 }
704 }
705 }
706 while (dtors_called);
707 }
708
709 void
g_thread_win32_process_detach(void)710 g_thread_win32_process_detach (void)
711 {
712 #ifndef _MSC_VER
713 if (SetThreadName_VEH_handle != NULL)
714 {
715 RemoveVectoredExceptionHandler (SetThreadName_VEH_handle);
716 SetThreadName_VEH_handle = NULL;
717 }
718 #endif
719 }
720
721 /* vim:set foldmethod=marker: */
722