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