1 /*
2  * C11 <threads.h> emulation library
3  *
4  * (C) Copyright yohhoy 2012.
5  * Distributed under the Boost Software License, Version 1.0.
6  *
7  * Permission is hereby granted, free of charge, to any person or organization
8  * obtaining a copy of the software and accompanying documentation covered by
9  * this license (the "Software") to use, reproduce, display, distribute,
10  * execute, and transmit the Software, and to prepare [[derivative work]]s of the
11  * Software, and to permit third-parties to whom the Software is furnished to
12  * do so, all subject to the following:
13  *
14  * The copyright notices in the Software and this entire statement, including
15  * the above license grant, this restriction and the following disclaimer,
16  * must be included in all copies of the Software, in whole or in part, and
17  * all derivative works of the Software, unless such copies or derivative
18  * works are solely in the form of machine-executable object code generated by
19  * a source language processor.
20  *
21  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23  * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
24  * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
25  * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
26  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
27  * DEALINGS IN THE SOFTWARE.
28  */
29 #include <assert.h>
30 #include <limits.h>
31 #include <errno.h>
32 #include <process.h>  // MSVCRT
33 #include <stdlib.h>
34 #include <stdbool.h>
35 
36 #include "c11/threads.h"
37 
38 #include "threads_win32.h"
39 
40 #include <windows.h>
41 
42 /*
43 Configuration macro:
44   EMULATED_THREADS_TSS_DTOR_SLOTNUM
45     Max registerable TSS dtor number.
46 */
47 
48 #define EMULATED_THREADS_TSS_DTOR_SLOTNUM 64  // see TLS_MINIMUM_AVAILABLE
49 
50 
51 static_assert(sizeof(cnd_t) == sizeof(CONDITION_VARIABLE), "The size of cnd_t must equal to CONDITION_VARIABLE");
52 static_assert(sizeof(thrd_t) == sizeof(HANDLE), "The size of thrd_t must equal to HANDLE");
53 static_assert(sizeof(tss_t) == sizeof(DWORD), "The size of tss_t must equal to DWORD");
54 static_assert(sizeof(mtx_t) == sizeof(CRITICAL_SECTION), "The size of mtx_t must equal to CRITICAL_SECTION");
55 static_assert(sizeof(once_flag) == sizeof(INIT_ONCE), "The size of once_flag must equal to INIT_ONCE");
56 
57 /*
58 Implementation limits:
59   - Emulated `mtx_timelock()' with mtx_trylock() + *busy loop*
60 */
61 
62 struct impl_thrd_param {
63     thrd_start_t func;
64     void *arg;
65     thrd_t thrd;
66 };
67 
68 struct thrd_state {
69     thrd_t thrd;
70     bool handle_need_close;
71 };
72 
73 static thread_local struct thrd_state impl_current_thread = { 0 };
74 
impl_thrd_routine(void * p)75 static unsigned __stdcall impl_thrd_routine(void *p)
76 {
77     struct impl_thrd_param *pack_p = (struct impl_thrd_param *)p;
78     struct impl_thrd_param pack;
79     int code;
80     impl_current_thread.thrd = pack_p->thrd;
81     impl_current_thread.handle_need_close = false;
82     memcpy(&pack, pack_p, sizeof(struct impl_thrd_param));
83     free(p);
84     code = pack.func(pack.arg);
85     return (unsigned)code;
86 }
87 
impl_timespec2msec(const struct timespec * ts)88 static time_t impl_timespec2msec(const struct timespec *ts)
89 {
90     return (ts->tv_sec * 1000U) + (ts->tv_nsec / 1000000L);
91 }
92 
impl_abs2relmsec(const struct timespec * abs_time)93 static DWORD impl_abs2relmsec(const struct timespec *abs_time)
94 {
95     const time_t abs_ms = impl_timespec2msec(abs_time);
96     struct timespec now;
97     timespec_get(&now, TIME_UTC);
98     const time_t now_ms = impl_timespec2msec(&now);
99     const DWORD rel_ms = (abs_ms > now_ms) ? (DWORD)(abs_ms - now_ms) : 0;
100     return rel_ms;
101 }
102 
103 struct impl_call_once_param { void (*func)(void); };
impl_call_once_callback(PINIT_ONCE InitOnce,PVOID Parameter,PVOID * Context)104 static BOOL CALLBACK impl_call_once_callback(PINIT_ONCE InitOnce, PVOID Parameter, PVOID *Context)
105 {
106     struct impl_call_once_param *param = (struct impl_call_once_param*)Parameter;
107     (param->func)();
108     ((void)InitOnce); ((void)Context);  // suppress warning
109     return true;
110 }
111 
112 static struct impl_tss_dtor_entry {
113     tss_t key;
114     tss_dtor_t dtor;
115 } impl_tss_dtor_tbl[EMULATED_THREADS_TSS_DTOR_SLOTNUM];
116 
impl_tss_dtor_register(tss_t key,tss_dtor_t dtor)117 static int impl_tss_dtor_register(tss_t key, tss_dtor_t dtor)
118 {
119     int i;
120     for (i = 0; i < EMULATED_THREADS_TSS_DTOR_SLOTNUM; i++) {
121         if (!impl_tss_dtor_tbl[i].dtor)
122             break;
123     }
124     if (i == EMULATED_THREADS_TSS_DTOR_SLOTNUM)
125         return 1;
126     impl_tss_dtor_tbl[i].key = key;
127     impl_tss_dtor_tbl[i].dtor = dtor;
128     return 0;
129 }
130 
impl_tss_dtor_invoke(void)131 static void impl_tss_dtor_invoke(void)
132 {
133     int i;
134     for (i = 0; i < EMULATED_THREADS_TSS_DTOR_SLOTNUM; i++) {
135         if (impl_tss_dtor_tbl[i].dtor) {
136             void* val = tss_get(impl_tss_dtor_tbl[i].key);
137             if (val)
138                 (impl_tss_dtor_tbl[i].dtor)(val);
139         }
140     }
141 }
142 
143 
144 /*--------------- 7.25.2 Initialization functions ---------------*/
145 // 7.25.2.1
146 void
call_once(once_flag * flag,void (* func)(void))147 call_once(once_flag *flag, void (*func)(void))
148 {
149     assert(flag && func);
150     struct impl_call_once_param param;
151     param.func = func;
152     InitOnceExecuteOnce((PINIT_ONCE)flag, impl_call_once_callback, (PVOID)&param, NULL);
153 }
154 
155 
156 /*------------- 7.25.3 Condition variable functions -------------*/
157 // 7.25.3.1
158 int
cnd_broadcast(cnd_t * cond)159 cnd_broadcast(cnd_t *cond)
160 {
161     assert(cond != NULL);
162     WakeAllConditionVariable((PCONDITION_VARIABLE)cond);
163     return thrd_success;
164 }
165 
166 // 7.25.3.2
167 void
cnd_destroy(cnd_t * cond)168 cnd_destroy(cnd_t *cond)
169 {
170     (void)cond;
171     assert(cond != NULL);
172     // do nothing
173 }
174 
175 // 7.25.3.3
176 int
cnd_init(cnd_t * cond)177 cnd_init(cnd_t *cond)
178 {
179     assert(cond != NULL);
180     InitializeConditionVariable((PCONDITION_VARIABLE)cond);
181     return thrd_success;
182 }
183 
184 // 7.25.3.4
185 int
cnd_signal(cnd_t * cond)186 cnd_signal(cnd_t *cond)
187 {
188     assert(cond != NULL);
189     WakeConditionVariable((PCONDITION_VARIABLE)cond);
190     return thrd_success;
191 }
192 
193 // 7.25.3.5
194 int
cnd_timedwait(cnd_t * cond,mtx_t * mtx,const struct timespec * abs_time)195 cnd_timedwait(cnd_t *cond, mtx_t *mtx, const struct timespec *abs_time)
196 {
197     assert(cond != NULL);
198     assert(mtx != NULL);
199     assert(abs_time != NULL);
200     const DWORD timeout = impl_abs2relmsec(abs_time);
201     if (SleepConditionVariableCS((PCONDITION_VARIABLE)cond, (PCRITICAL_SECTION)mtx, timeout))
202         return thrd_success;
203     return (GetLastError() == ERROR_TIMEOUT) ? thrd_timedout : thrd_error;
204 }
205 
206 // 7.25.3.6
207 int
cnd_wait(cnd_t * cond,mtx_t * mtx)208 cnd_wait(cnd_t *cond, mtx_t *mtx)
209 {
210     assert(cond != NULL);
211     assert(mtx != NULL);
212     SleepConditionVariableCS((PCONDITION_VARIABLE)cond, (PCRITICAL_SECTION)mtx, INFINITE);
213     return thrd_success;
214 }
215 
216 
217 /*-------------------- 7.25.4 Mutex functions --------------------*/
218 // 7.25.4.1
219 void
mtx_destroy(mtx_t * mtx)220 mtx_destroy(mtx_t *mtx)
221 {
222     assert(mtx);
223     DeleteCriticalSection((PCRITICAL_SECTION)mtx);
224 }
225 
226 // 7.25.4.2
227 int
mtx_init(mtx_t * mtx,int type)228 mtx_init(mtx_t *mtx, int type)
229 {
230     assert(mtx != NULL);
231     if (type != mtx_plain && type != mtx_timed
232       && type != (mtx_plain|mtx_recursive)
233       && type != (mtx_timed|mtx_recursive))
234         return thrd_error;
235     InitializeCriticalSection((PCRITICAL_SECTION)mtx);
236     return thrd_success;
237 }
238 
239 // 7.25.4.3
240 int
mtx_lock(mtx_t * mtx)241 mtx_lock(mtx_t *mtx)
242 {
243     assert(mtx != NULL);
244     EnterCriticalSection((PCRITICAL_SECTION)mtx);
245     return thrd_success;
246 }
247 
248 // 7.25.4.4
249 int
mtx_timedlock(mtx_t * mtx,const struct timespec * ts)250 mtx_timedlock(mtx_t *mtx, const struct timespec *ts)
251 {
252     assert(mtx != NULL);
253     assert(ts != NULL);
254     while (mtx_trylock(mtx) != thrd_success) {
255         if (impl_abs2relmsec(ts) == 0)
256             return thrd_timedout;
257         // busy loop!
258         thrd_yield();
259     }
260     return thrd_success;
261 }
262 
263 // 7.25.4.5
264 int
mtx_trylock(mtx_t * mtx)265 mtx_trylock(mtx_t *mtx)
266 {
267     assert(mtx != NULL);
268     return TryEnterCriticalSection((PCRITICAL_SECTION)mtx) ? thrd_success : thrd_busy;
269 }
270 
271 // 7.25.4.6
272 int
mtx_unlock(mtx_t * mtx)273 mtx_unlock(mtx_t *mtx)
274 {
275     assert(mtx != NULL);
276     LeaveCriticalSection((PCRITICAL_SECTION)mtx);
277     return thrd_success;
278 }
279 
280 void
__threads_win32_tls_callback(void)281 __threads_win32_tls_callback(void)
282 {
283     struct thrd_state *state = &impl_current_thread;
284     impl_tss_dtor_invoke();
285     if (state->handle_need_close) {
286         state->handle_need_close = false;
287         CloseHandle(state->thrd.handle);
288     }
289 }
290 
291 /*------------------- 7.25.5 Thread functions -------------------*/
292 // 7.25.5.1
293 int
thrd_create(thrd_t * thr,thrd_start_t func,void * arg)294 thrd_create(thrd_t *thr, thrd_start_t func, void *arg)
295 {
296     struct impl_thrd_param *pack;
297     uintptr_t handle;
298     assert(thr != NULL);
299     pack = (struct impl_thrd_param *)malloc(sizeof(struct impl_thrd_param));
300     if (!pack) return thrd_nomem;
301     pack->func = func;
302     pack->arg = arg;
303     handle = _beginthreadex(NULL, 0, impl_thrd_routine, pack, CREATE_SUSPENDED, NULL);
304     if (handle == 0) {
305         free(pack);
306         if (errno == EAGAIN || errno == EACCES)
307             return thrd_nomem;
308         return thrd_error;
309     }
310     thr->handle = (void*)handle;
311     pack->thrd = *thr;
312     ResumeThread((HANDLE)handle);
313     return thrd_success;
314 }
315 
316 // 7.25.5.2
317 thrd_t
thrd_current(void)318 thrd_current(void)
319 {
320     /* GetCurrentThread() returns a pseudo-handle, which we need
321      * to pass to DuplicateHandle(). Only the resulting handle can be used
322      * from other threads.
323      *
324      * Note that neither handle can be compared to the one by thread_create.
325      * Only the thread IDs - as returned by GetThreadId() and GetCurrentThreadId()
326      * can be compared directly.
327      *
328      * Other potential solutions would be:
329      * - define thrd_t as a thread Ids, but this would mean we'd need to OpenThread for many operations
330      * - use malloc'ed memory for thrd_t. This would imply using TLS for current thread.
331      *
332      * Neither is particularly nice.
333      *
334      * Life would be much easier if C11 threads had different abstractions for
335      * threads and thread IDs, just like C++11 threads does...
336      */
337     struct thrd_state *state = &impl_current_thread;
338     if (state->thrd.handle == NULL)
339     {
340         if (!DuplicateHandle(GetCurrentProcess(), GetCurrentThread(), GetCurrentProcess(),
341             &(state->thrd.handle), 0, false, DUPLICATE_SAME_ACCESS))
342         {
343             abort();
344         }
345         state->handle_need_close = true;
346     }
347     return state->thrd;
348 }
349 
350 // 7.25.5.3
351 int
thrd_detach(thrd_t thr)352 thrd_detach(thrd_t thr)
353 {
354     CloseHandle(thr.handle);
355     return thrd_success;
356 }
357 
358 // 7.25.5.4
359 int
thrd_equal(thrd_t thr0,thrd_t thr1)360 thrd_equal(thrd_t thr0, thrd_t thr1)
361 {
362     return GetThreadId(thr0.handle) == GetThreadId(thr1.handle);
363 }
364 
365 // 7.25.5.5
366 _Noreturn
367 void
thrd_exit(int res)368 thrd_exit(int res)
369 {
370     _endthreadex((unsigned)res);
371 }
372 
373 // 7.25.5.6
374 int
thrd_join(thrd_t thr,int * res)375 thrd_join(thrd_t thr, int *res)
376 {
377     DWORD w, code;
378     if (thr.handle == NULL) {
379         return thrd_error;
380     }
381     w = WaitForSingleObject(thr.handle, INFINITE);
382     if (w != WAIT_OBJECT_0)
383         return thrd_error;
384     if (res) {
385         if (!GetExitCodeThread(thr.handle, &code)) {
386             CloseHandle(thr.handle);
387             return thrd_error;
388         }
389         *res = (int)code;
390     }
391     CloseHandle(thr.handle);
392     return thrd_success;
393 }
394 
395 // 7.25.5.7
396 int
thrd_sleep(const struct timespec * time_point,struct timespec * remaining)397 thrd_sleep(const struct timespec *time_point, struct timespec *remaining)
398 {
399     (void)remaining;
400     assert(time_point);
401     assert(!remaining); /* not implemented */
402     Sleep((DWORD)impl_timespec2msec(time_point));
403     return 0;
404 }
405 
406 // 7.25.5.8
407 void
thrd_yield(void)408 thrd_yield(void)
409 {
410     SwitchToThread();
411 }
412 
413 
414 /*----------- 7.25.6 Thread-specific storage functions -----------*/
415 // 7.25.6.1
416 int
tss_create(tss_t * key,tss_dtor_t dtor)417 tss_create(tss_t *key, tss_dtor_t dtor)
418 {
419     assert(key != NULL);
420     *key = TlsAlloc();
421     if (dtor) {
422         if (impl_tss_dtor_register(*key, dtor)) {
423             TlsFree(*key);
424             return thrd_error;
425         }
426     }
427     return (*key != 0xFFFFFFFF) ? thrd_success : thrd_error;
428 }
429 
430 // 7.25.6.2
431 void
tss_delete(tss_t key)432 tss_delete(tss_t key)
433 {
434     TlsFree(key);
435 }
436 
437 // 7.25.6.3
438 void *
tss_get(tss_t key)439 tss_get(tss_t key)
440 {
441     return TlsGetValue(key);
442 }
443 
444 // 7.25.6.4
445 int
tss_set(tss_t key,void * val)446 tss_set(tss_t key, void *val)
447 {
448     return TlsSetValue(key, val) ? thrd_success : thrd_error;
449 }
450