Imported Upstream version 2.72.3
[platform/upstream/glib.git] / glib / gthread-win32.c
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
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
80 g_mutex_init (GMutex *mutex)
81 {
82   InitializeSRWLock ((gpointer) mutex);
83 }
84
85 void
86 g_mutex_clear (GMutex *mutex)
87 {
88 }
89
90 void
91 g_mutex_lock (GMutex *mutex)
92 {
93   AcquireSRWLockExclusive ((gpointer) mutex);
94 }
95
96 gboolean
97 g_mutex_trylock (GMutex *mutex)
98 {
99   return TryAcquireSRWLockExclusive ((gpointer) mutex);
100 }
101
102 void
103 g_mutex_unlock (GMutex *mutex)
104 {
105   ReleaseSRWLockExclusive ((gpointer) mutex);
106 }
107
108 /* {{{1 GRecMutex */
109
110 static CRITICAL_SECTION *
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
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 *
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
145 g_rec_mutex_init (GRecMutex *mutex)
146 {
147   mutex->p = g_rec_mutex_impl_new ();
148 }
149
150 void
151 g_rec_mutex_clear (GRecMutex *mutex)
152 {
153   g_rec_mutex_impl_free (mutex->p);
154 }
155
156 void
157 g_rec_mutex_lock (GRecMutex *mutex)
158 {
159   EnterCriticalSection (g_rec_mutex_get_impl (mutex));
160 }
161
162 void
163 g_rec_mutex_unlock (GRecMutex *mutex)
164 {
165   LeaveCriticalSection (mutex->p);
166 }
167
168 gboolean
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
177 g_rw_lock_init (GRWLock *lock)
178 {
179   InitializeSRWLock ((gpointer) lock);
180 }
181
182 void
183 g_rw_lock_clear (GRWLock *lock)
184 {
185 }
186
187 void
188 g_rw_lock_writer_lock (GRWLock *lock)
189 {
190   AcquireSRWLockExclusive ((gpointer) lock);
191 }
192
193 gboolean
194 g_rw_lock_writer_trylock (GRWLock *lock)
195 {
196   return TryAcquireSRWLockExclusive ((gpointer) lock);
197 }
198
199 void
200 g_rw_lock_writer_unlock (GRWLock *lock)
201 {
202   ReleaseSRWLockExclusive ((gpointer) lock);
203 }
204
205 void
206 g_rw_lock_reader_lock (GRWLock *lock)
207 {
208   AcquireSRWLockShared ((gpointer) lock);
209 }
210
211 gboolean
212 g_rw_lock_reader_trylock (GRWLock *lock)
213 {
214   return TryAcquireSRWLockShared ((gpointer) lock);
215 }
216
217 void
218 g_rw_lock_reader_unlock (GRWLock *lock)
219 {
220   ReleaseSRWLockShared ((gpointer) lock);
221 }
222
223 /* {{{1 GCond */
224 void
225 g_cond_init (GCond *cond)
226 {
227   InitializeConditionVariable ((gpointer) cond);
228 }
229
230 void
231 g_cond_clear (GCond *cond)
232 {
233 }
234
235 void
236 g_cond_signal (GCond *cond)
237 {
238   WakeConditionVariable ((gpointer) cond);
239 }
240
241 void
242 g_cond_broadcast (GCond *cond)
243 {
244   WakeAllConditionVariable ((gpointer) cond);
245 }
246
247 void
248 g_cond_wait (GCond  *cond,
249              GMutex *entered_mutex)
250 {
251   SleepConditionVariableSRW ((gpointer) cond, (gpointer) entered_mutex, INFINITE, 0);
252 }
253
254 gboolean
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
308 g_private_get_impl (GPrivate *key)
309 {
310   DWORD impl = (DWORD) GPOINTER_TO_UINT(key->p);
311
312   if G_UNLIKELY (impl == 0)
313     {
314       EnterCriticalSection (&g_private_lock);
315       impl = (UINT_PTR) key->p;
316       if (impl == 0)
317         {
318           GPrivateDestructor *destructor;
319
320           impl = TlsAlloc ();
321
322           if G_UNLIKELY (impl == 0)
323             {
324               /* Ignore TLS index 0 temporarily (as 0 is the indicator that we
325                * haven't allocated TLS yet) and alloc again;
326                * See https://gitlab.gnome.org/GNOME/glib/-/issues/2058 */
327               DWORD impl2 = TlsAlloc ();
328               TlsFree (impl);
329               impl = impl2;
330             }
331
332           if (impl == TLS_OUT_OF_INDEXES || impl == 0)
333             g_thread_abort (0, "TlsAlloc");
334
335           if (key->notify != NULL)
336             {
337               destructor = malloc (sizeof (GPrivateDestructor));
338               if G_UNLIKELY (destructor == NULL)
339                 g_thread_abort (errno, "malloc");
340               destructor->index = impl;
341               destructor->notify = key->notify;
342               destructor->next = g_atomic_pointer_get (&g_private_destructors);
343
344               /* We need to do an atomic store due to the unlocked
345                * access to the destructor list from the thread exit
346                * function.
347                *
348                * It can double as a sanity check...
349                */
350               if (!g_atomic_pointer_compare_and_exchange (&g_private_destructors,
351                                                           destructor->next,
352                                                           destructor))
353                 g_thread_abort (0, "g_private_get_impl(1)");
354             }
355
356           /* Ditto, due to the unlocked access on the fast path */
357           if (!g_atomic_pointer_compare_and_exchange (&key->p, NULL, impl))
358             g_thread_abort (0, "g_private_get_impl(2)");
359         }
360       LeaveCriticalSection (&g_private_lock);
361     }
362
363   return impl;
364 }
365
366 gpointer
367 g_private_get (GPrivate *key)
368 {
369   return TlsGetValue (g_private_get_impl (key));
370 }
371
372 void
373 g_private_set (GPrivate *key,
374                gpointer  value)
375 {
376   TlsSetValue (g_private_get_impl (key), value);
377 }
378
379 void
380 g_private_replace (GPrivate *key,
381                    gpointer  value)
382 {
383   DWORD impl = g_private_get_impl (key);
384   gpointer old;
385
386   old = TlsGetValue (impl);
387   TlsSetValue (impl, value);
388   if (old && key->notify)
389     key->notify (old);
390 }
391
392 /* {{{1 GThread */
393
394 #define win32_check_for_error(what) G_STMT_START{                       \
395   if (!(what))                                                          \
396     g_error ("file %s: line %d (%s): error %s during %s",               \
397              __FILE__, __LINE__, G_STRFUNC,                             \
398              g_win32_error_message (GetLastError ()), #what);           \
399   }G_STMT_END
400
401 #define G_MUTEX_SIZE (sizeof (gpointer))
402
403 typedef BOOL (__stdcall *GTryEnterCriticalSectionFunc) (CRITICAL_SECTION *);
404
405 typedef struct
406 {
407   GRealThread thread;
408
409   GThreadFunc proxy;
410   HANDLE      handle;
411 } GThreadWin32;
412
413 void
414 g_system_thread_free (GRealThread *thread)
415 {
416   GThreadWin32 *wt = (GThreadWin32 *) thread;
417
418   win32_check_for_error (CloseHandle (wt->handle));
419   g_slice_free (GThreadWin32, wt);
420 }
421
422 void
423 g_system_thread_exit (void)
424 {
425   /* In static compilation, DllMain doesn't exist and so DLL_THREAD_DETACH
426    * case is never called and thread destroy notifications are not triggered.
427    * To ensure that notifications are correctly triggered in static
428    * compilation mode, we call directly the "detach" function here right
429    * before terminating the thread.
430    * As all win32 threads initialized through the glib API are run through
431    * the same proxy function g_thread_win32_proxy() which calls systematically
432    * g_system_thread_exit() when finishing, we obtain the same behavior as
433    * with dynamic compilation.
434    *
435    * WARNING: unfortunately this mechanism cannot work with threads created
436    * directly from the Windows API using CreateThread() or _beginthread/ex().
437    * It only works with threads created by using the glib API with
438    * g_system_thread_new(). If users need absolutely to use a thread NOT
439    * created with glib API under Windows and in static compilation mode, they
440    * should not use glib functions within their thread or they may encounter
441    * memory leaks when the thread finishes.
442    */
443 #ifdef GLIB_STATIC_COMPILATION
444   g_thread_win32_thread_detach ();
445 #endif
446
447   _endthreadex (0);
448 }
449
450 static guint __stdcall
451 g_thread_win32_proxy (gpointer data)
452 {
453   GThreadWin32 *self = data;
454
455   self->proxy (self);
456
457   g_system_thread_exit ();
458
459   g_assert_not_reached ();
460
461   return 0;
462 }
463
464 gboolean
465 g_system_thread_get_scheduler_settings (GThreadSchedulerSettings *scheduler_settings)
466 {
467   HANDLE current_thread = GetCurrentThread ();
468   scheduler_settings->thread_prio = GetThreadPriority (current_thread);
469
470   return TRUE;
471 }
472
473 GRealThread *
474 g_system_thread_new (GThreadFunc proxy,
475                      gulong stack_size,
476                      const GThreadSchedulerSettings *scheduler_settings,
477                      const char *name,
478                      GThreadFunc func,
479                      gpointer data,
480                      GError **error)
481 {
482   GThreadWin32 *thread;
483   GRealThread *base_thread;
484   guint ignore;
485   const gchar *message = NULL;
486   int thread_prio;
487
488   thread = g_slice_new0 (GThreadWin32);
489   thread->proxy = proxy;
490   thread->handle = (HANDLE) NULL;
491   base_thread = (GRealThread*)thread;
492   base_thread->ref_count = 2;
493   base_thread->ours = TRUE;
494   base_thread->thread.joinable = TRUE;
495   base_thread->thread.func = func;
496   base_thread->thread.data = data;
497   base_thread->name = g_strdup (name);
498
499   thread->handle = (HANDLE) _beginthreadex (NULL, stack_size, g_thread_win32_proxy, thread,
500                                             CREATE_SUSPENDED, &ignore);
501
502   if (thread->handle == NULL)
503     {
504       message = "Error creating thread";
505       goto error;
506     }
507
508   /* For thread priority inheritance we need to manually set the thread
509    * priority of the new thread to the priority of the current thread. We
510    * also have to start the thread suspended and resume it after actually
511    * setting the priority here.
512    *
513    * On Windows, by default all new threads are created with NORMAL thread
514    * priority.
515    */
516
517   if (scheduler_settings)
518     {
519       thread_prio = scheduler_settings->thread_prio;
520     }
521   else
522     {
523       HANDLE current_thread = GetCurrentThread ();
524       thread_prio = GetThreadPriority (current_thread);
525     }
526
527   if (thread_prio == THREAD_PRIORITY_ERROR_RETURN)
528     {
529       message = "Error getting current thread priority";
530       goto error;
531     }
532
533   if (SetThreadPriority (thread->handle, thread_prio) == 0)
534     {
535       message = "Error setting new thread priority";
536       goto error;
537     }
538
539   if (ResumeThread (thread->handle) == (DWORD) -1)
540     {
541       message = "Error resuming new thread";
542       goto error;
543     }
544
545   return (GRealThread *) thread;
546
547 error:
548   {
549     gchar *win_error = g_win32_error_message (GetLastError ());
550     g_set_error (error, G_THREAD_ERROR, G_THREAD_ERROR_AGAIN,
551                  "%s: %s", message, win_error);
552     g_free (win_error);
553     if (thread->handle)
554       CloseHandle (thread->handle);
555     g_slice_free (GThreadWin32, thread);
556     return NULL;
557   }
558 }
559
560 void
561 g_thread_yield (void)
562 {
563   Sleep(0);
564 }
565
566 void
567 g_system_thread_wait (GRealThread *thread)
568 {
569   GThreadWin32 *wt = (GThreadWin32 *) thread;
570
571   win32_check_for_error (WAIT_FAILED != WaitForSingleObject (wt->handle, INFINITE));
572 }
573
574 #define EXCEPTION_SET_THREAD_NAME ((DWORD) 0x406D1388)
575
576 #ifndef _MSC_VER
577 static void *SetThreadName_VEH_handle = NULL;
578
579 static LONG __stdcall
580 SetThreadName_VEH (PEXCEPTION_POINTERS ExceptionInfo)
581 {
582   if (ExceptionInfo->ExceptionRecord != NULL &&
583       ExceptionInfo->ExceptionRecord->ExceptionCode == EXCEPTION_SET_THREAD_NAME)
584     return EXCEPTION_CONTINUE_EXECUTION;
585
586   return EXCEPTION_CONTINUE_SEARCH;
587 }
588 #endif
589
590 typedef struct _THREADNAME_INFO
591 {
592   DWORD  dwType;        /* must be 0x1000 */
593   LPCSTR szName;        /* pointer to name (in user addr space) */
594   DWORD  dwThreadID;    /* thread ID (-1=caller thread) */
595   DWORD  dwFlags;       /* reserved for future use, must be zero */
596 } THREADNAME_INFO;
597
598 static void
599 SetThreadName (DWORD  dwThreadID,
600                LPCSTR szThreadName)
601 {
602    THREADNAME_INFO info;
603    DWORD infosize;
604
605    info.dwType = 0x1000;
606    info.szName = szThreadName;
607    info.dwThreadID = dwThreadID;
608    info.dwFlags = 0;
609
610    infosize = sizeof (info) / sizeof (DWORD);
611
612 #ifdef _MSC_VER
613    __try
614      {
615        RaiseException (EXCEPTION_SET_THREAD_NAME, 0, infosize,
616                        (const ULONG_PTR *) &info);
617      }
618    __except (EXCEPTION_EXECUTE_HANDLER)
619      {
620      }
621 #else
622    /* Without a debugger we *must* have an exception handler,
623     * otherwise raising an exception will crash the process.
624     */
625    if ((!IsDebuggerPresent ()) && (SetThreadName_VEH_handle == NULL))
626      return;
627
628    RaiseException (EXCEPTION_SET_THREAD_NAME, 0, infosize, (const ULONG_PTR *) &info);
629 #endif
630 }
631
632 typedef HRESULT (WINAPI *pSetThreadDescription) (HANDLE hThread,
633                                                  PCWSTR lpThreadDescription);
634 static pSetThreadDescription SetThreadDescriptionFunc = NULL;
635 static HMODULE kernel32_module = NULL;
636
637 static gboolean
638 g_thread_win32_load_library (void)
639 {
640   /* FIXME: Add support for UWP app */
641 #if !defined(G_WINAPI_ONLY_APP)
642   static gsize _init_once = 0;
643   if (g_once_init_enter (&_init_once))
644     {
645       kernel32_module = LoadLibraryW (L"kernel32.dll");
646       if (kernel32_module)
647         {
648           SetThreadDescriptionFunc =
649               (pSetThreadDescription) GetProcAddress (kernel32_module,
650                                                       "SetThreadDescription");
651           if (!SetThreadDescriptionFunc)
652             FreeLibrary (kernel32_module);
653         }
654       g_once_init_leave (&_init_once, 1);
655     }
656 #endif
657
658   return !!SetThreadDescriptionFunc;
659 }
660
661 static gboolean
662 g_thread_win32_set_thread_desc (const gchar *name)
663 {
664   HRESULT hr;
665   wchar_t *namew;
666
667   if (!g_thread_win32_load_library () || !name)
668     return FALSE;
669
670   namew = g_utf8_to_utf16 (name, -1, NULL, NULL, NULL);
671   if (!namew)
672     return FALSE;
673
674   hr = SetThreadDescriptionFunc (GetCurrentThread (), namew);
675
676   g_free (namew);
677   return SUCCEEDED (hr);
678 }
679
680 void
681 g_system_thread_set_name (const gchar *name)
682 {
683   /* Prefer SetThreadDescription over exception based way if available,
684    * since thread description set by SetThreadDescription will be preserved
685    * in dump file */
686   if (!g_thread_win32_set_thread_desc (name))
687     SetThreadName ((DWORD) -1, name);
688 }
689
690 /* {{{1 Epilogue */
691
692 void
693 g_thread_win32_init (void)
694 {
695   InitializeCriticalSection (&g_private_lock);
696
697 #ifndef _MSC_VER
698   SetThreadName_VEH_handle = AddVectoredExceptionHandler (1, &SetThreadName_VEH);
699   if (SetThreadName_VEH_handle == NULL)
700     {
701       /* This is bad, but what can we do? */
702     }
703 #endif
704 }
705
706 void
707 g_thread_win32_thread_detach (void)
708 {
709   gboolean dtors_called;
710
711   do
712     {
713       GPrivateDestructor *dtor;
714
715       /* We go by the POSIX book on this one.
716        *
717        * If we call a destructor then there is a chance that some new
718        * TLS variables got set by code called in that destructor.
719        *
720        * Loop until nothing is left.
721        */
722       dtors_called = FALSE;
723
724       for (dtor = g_atomic_pointer_get (&g_private_destructors); dtor; dtor = dtor->next)
725         {
726           gpointer value;
727
728           value = TlsGetValue (dtor->index);
729           if (value != NULL && dtor->notify != NULL)
730             {
731               /* POSIX says to clear this before the call */
732               TlsSetValue (dtor->index, NULL);
733               dtor->notify (value);
734               dtors_called = TRUE;
735             }
736         }
737     }
738   while (dtors_called);
739 }
740
741 void
742 g_thread_win32_process_detach (void)
743 {
744 #ifndef _MSC_VER
745   if (SetThreadName_VEH_handle != NULL)
746     {
747       RemoveVectoredExceptionHandler (SetThreadName_VEH_handle);
748       SetThreadName_VEH_handle = NULL;
749     }
750 #endif
751 }
752
753 /* vim:set foldmethod=marker: */