Updated so it's in line with README.
[wine.git] / scheduler / pthread.c
blob9ed1513e9963ad2d307670f9f553871b309f9615
1 /*
2 * pthread emulation for re-entrant libcs
4 * We can't use pthreads directly, so why not let libcs
5 * that want pthreads use Wine's own threading instead...
7 * Copyright 1999 Ove Kåven
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with this library; if not, write to the Free Software
21 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
24 #include "config.h"
25 #include "wine/port.h"
27 #define _GNU_SOURCE /* we may need to override some GNU extensions */
29 #include <assert.h>
30 #include <errno.h>
31 #include <stdlib.h>
32 #include <unistd.h>
33 #include <string.h>
35 #include "winbase.h"
36 #include "thread.h"
37 #include "ntddk.h"
39 static int init_done;
41 void PTHREAD_init_done(void)
43 init_done = 1;
46 /* Currently this probably works only for glibc2,
47 * which checks for the presence of double-underscore-prepended
48 * pthread primitives, and use them if available.
49 * If they are not available, the libc defaults to
50 * non-threadsafe operation (not good). */
52 #if defined(__GLIBC__)
53 #include <pthread.h>
54 #include <signal.h>
56 #ifdef NEED_UNDERSCORE_PREFIX
57 # define PREFIX "_"
58 #else
59 # define PREFIX
60 #endif
62 #define PSTR(str) PREFIX #str
64 /* adapt as necessary (a construct like this is used in glibc sources) */
65 #define strong_alias(orig, alias) \
66 asm(".globl " PSTR(alias) "\n" \
67 "\t.set " PSTR(alias) "," PSTR(orig))
69 /* strong_alias does not work on external symbols (.o format limitation?),
70 * so for those, we need to use the pogo stick */
71 #if defined(__i386__) && !defined(__PIC__)
72 /* FIXME: PIC */
73 #define jump_alias(orig, alias) \
74 asm(".globl " PSTR(alias) "\n" \
75 "\t.type " PSTR(alias) ",@function\n" \
76 PSTR(alias) ":\n" \
77 "\tjmp " PSTR(orig))
78 #endif
80 /* get necessary libc symbols */
81 #if (__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 1) && defined(HAVE___LIBC_FORK)
82 #define LIBC_FORK __libc_fork
83 #define PTHREAD_FORK __fork
84 #define ALIAS_FORK
85 #else
86 #define LIBC_FORK __fork
87 #define PTHREAD_FORK fork
88 #endif
89 extern pid_t LIBC_FORK(void);
91 #define LIBC_SIGACTION __sigaction
92 extern int LIBC_SIGACTION(int signum,
93 const struct sigaction *act,
94 struct sigaction *oldact);
96 /* NOTE: This is a truly extremely incredibly ugly hack!
97 * But it does seem to work... */
99 /* assume that pthread_mutex_t has room for at least one pointer,
100 * and hope that the users of pthread_mutex_t considers it opaque
101 * (never checks what's in it)
102 * also: assume that static initializer sets pointer to NULL
104 typedef struct {
105 CRITICAL_SECTION *critsect;
106 } *wine_mutex;
108 /* see wine_mutex above for comments */
109 typedef struct {
110 RTL_RWLOCK *lock;
111 } *wine_rwlock;
113 typedef struct _wine_cleanup {
114 void (*routine)(void *);
115 void *arg;
116 } *wine_cleanup;
118 typedef const void *key_data;
120 #define FIRST_KEY 0
121 #define MAX_KEYS 16 /* libc6 doesn't use that many, but... */
123 #define P_OUTPUT(stuff) write(2,stuff,strlen(stuff))
125 void __pthread_initialize(void)
129 struct pthread_thread_init {
130 void* (*start_routine)(void*);
131 void* arg;
134 static DWORD CALLBACK pthread_thread_start(LPVOID data)
136 struct pthread_thread_init init = *(struct pthread_thread_init*)data;
137 HeapFree(GetProcessHeap(),0,data);
138 return (DWORD)init.start_routine(init.arg);
141 int pthread_create(pthread_t* thread, const pthread_attr_t* attr, void*
142 (*start_routine)(void *), void* arg)
144 HANDLE hThread;
145 struct pthread_thread_init* idata = HeapAlloc(GetProcessHeap(), 0,
146 sizeof(struct pthread_thread_init));
148 idata->start_routine = start_routine;
149 idata->arg = arg;
150 hThread = CreateThread(NULL, 0, pthread_thread_start, idata, 0, thread);
152 if(hThread)
153 CloseHandle(hThread);
154 else
156 HeapFree(GetProcessHeap(),0,idata); /* free idata struct on failure */
157 return EAGAIN;
160 return 0;
163 int pthread_cancel(pthread_t thread)
165 HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, FALSE, thread);
167 if(!TerminateThread(hThread, 0))
169 CloseHandle(hThread);
170 return EINVAL; /* return error */
173 CloseHandle(hThread);
175 return 0; /* return success */
178 int pthread_join(pthread_t thread, void **value_ptr)
180 HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, FALSE, thread);
182 WaitForSingleObject(hThread, INFINITE);
183 if(!GetExitCodeThread(hThread, (LPDWORD)value_ptr))
185 CloseHandle(hThread);
186 return EINVAL; /* FIXME: make this more correctly match */
187 } /* windows errors */
189 CloseHandle(hThread);
190 return 0;
193 /*FIXME: not sure what to do with this one... */
194 int pthread_detach(pthread_t thread)
196 P_OUTPUT("FIXME:pthread_detach\n");
197 return 0;
200 /* FIXME: we have no equivalents in win32 for the policys */
201 /* so just keep this as a stub */
202 int pthread_attr_setschedpolicy(pthread_attr_t *attr, int policy)
204 P_OUTPUT("FIXME:pthread_attr_setschedpolicy\n");
205 return 0;
208 /* FIXME: no win32 equivalent for scope */
209 int pthread_attr_setscope(pthread_attr_t *attr, int scope)
211 P_OUTPUT("FIXME:pthread_attr_setscope\n");
212 return 0; /* return success */
215 /* FIXME: no win32 equivalent for schedule param */
216 int pthread_attr_setschedparam(pthread_attr_t *attr,
217 const struct sched_param *param)
219 P_OUTPUT("FIXME:pthread_attr_setschedparam\n");
220 return 0; /* return success */
223 int __pthread_once(pthread_once_t *once_control, void (*init_routine)(void))
225 static pthread_once_t the_once = PTHREAD_ONCE_INIT;
226 LONG once_now = *(LONG *)&the_once;
228 if (InterlockedCompareExchange((LONG*)once_control, once_now+1, once_now) == once_now)
229 (*init_routine)();
230 return 0;
232 strong_alias(__pthread_once, pthread_once);
234 void __pthread_kill_other_threads_np(void)
236 /* we don't need to do anything here */
238 strong_alias(__pthread_kill_other_threads_np, pthread_kill_other_threads_np);
240 /***** atfork *****/
242 #define MAX_ATFORK 8 /* libc doesn't need that many anyway */
244 static CRITICAL_SECTION atfork_section = CRITICAL_SECTION_INIT("atfork_section");
245 typedef void (*atfork_handler)();
246 static atfork_handler atfork_prepare[MAX_ATFORK];
247 static atfork_handler atfork_parent[MAX_ATFORK];
248 static atfork_handler atfork_child[MAX_ATFORK];
249 static int atfork_count;
251 int __pthread_atfork(void (*prepare)(void),
252 void (*parent)(void),
253 void (*child)(void))
255 if (init_done) EnterCriticalSection( &atfork_section );
256 assert( atfork_count < MAX_ATFORK );
257 atfork_prepare[atfork_count] = prepare;
258 atfork_parent[atfork_count] = parent;
259 atfork_child[atfork_count] = child;
260 atfork_count++;
261 if (init_done) LeaveCriticalSection( &atfork_section );
262 return 0;
264 strong_alias(__pthread_atfork, pthread_atfork);
266 pid_t PTHREAD_FORK(void)
268 pid_t pid;
269 int i;
271 EnterCriticalSection( &atfork_section );
272 /* prepare handlers are called in reverse insertion order */
273 for (i = atfork_count - 1; i >= 0; i--) if (atfork_prepare[i]) atfork_prepare[i]();
274 if (!(pid = LIBC_FORK()))
276 InitializeCriticalSection( &atfork_section );
277 for (i = 0; i < atfork_count; i++) if (atfork_child[i]) atfork_child[i]();
279 else
281 for (i = 0; i < atfork_count; i++) if (atfork_parent[i]) atfork_parent[i]();
282 LeaveCriticalSection( &atfork_section );
284 return pid;
286 #ifdef ALIAS_FORK
287 strong_alias(PTHREAD_FORK, fork);
288 #endif
290 /***** MUTEXES *****/
292 int __pthread_mutex_init(pthread_mutex_t *mutex,
293 const pthread_mutexattr_t *mutexattr)
295 /* glibc has a tendency to initialize mutexes very often, even
296 in situations where they are not really used later on.
298 As for us, initializing a mutex is very expensive, we postpone
299 the real initialization until the time the mutex is first used. */
301 ((wine_mutex)mutex)->critsect = NULL;
302 return 0;
304 strong_alias(__pthread_mutex_init, pthread_mutex_init);
306 static void mutex_real_init( pthread_mutex_t *mutex )
308 CRITICAL_SECTION *critsect = HeapAlloc(GetProcessHeap(), 0, sizeof(CRITICAL_SECTION));
309 InitializeCriticalSection(critsect);
311 if (InterlockedCompareExchangePointer((void**)&(((wine_mutex)mutex)->critsect),critsect,NULL) != NULL) {
312 /* too late, some other thread already did it */
313 DeleteCriticalSection(critsect);
314 HeapFree(GetProcessHeap(), 0, critsect);
318 int __pthread_mutex_lock(pthread_mutex_t *mutex)
320 if (!init_done) return 0;
321 if (!((wine_mutex)mutex)->critsect)
322 mutex_real_init( mutex );
324 EnterCriticalSection(((wine_mutex)mutex)->critsect);
325 return 0;
327 strong_alias(__pthread_mutex_lock, pthread_mutex_lock);
329 int __pthread_mutex_trylock(pthread_mutex_t *mutex)
331 if (!init_done) return 0;
332 if (!((wine_mutex)mutex)->critsect)
333 mutex_real_init( mutex );
335 if (!TryEnterCriticalSection(((wine_mutex)mutex)->critsect)) {
336 errno = EBUSY;
337 return -1;
339 return 0;
341 strong_alias(__pthread_mutex_trylock, pthread_mutex_trylock);
343 int __pthread_mutex_unlock(pthread_mutex_t *mutex)
345 if (!((wine_mutex)mutex)->critsect) return 0;
346 LeaveCriticalSection(((wine_mutex)mutex)->critsect);
347 return 0;
349 strong_alias(__pthread_mutex_unlock, pthread_mutex_unlock);
351 int __pthread_mutex_destroy(pthread_mutex_t *mutex)
353 if (!((wine_mutex)mutex)->critsect) return 0;
354 if (((wine_mutex)mutex)->critsect->RecursionCount) {
355 #if 0 /* there seems to be a bug in libc6 that makes this a bad idea */
356 return EBUSY;
357 #else
358 while (((wine_mutex)mutex)->critsect->RecursionCount)
359 LeaveCriticalSection(((wine_mutex)mutex)->critsect);
360 #endif
362 DeleteCriticalSection(((wine_mutex)mutex)->critsect);
363 HeapFree(GetProcessHeap(), 0, ((wine_mutex)mutex)->critsect);
364 return 0;
366 strong_alias(__pthread_mutex_destroy, pthread_mutex_destroy);
369 /***** MUTEX ATTRIBUTES *****/
370 /* just dummies, since critical sections are always recursive */
372 int __pthread_mutexattr_init(pthread_mutexattr_t *attr)
374 return 0;
376 strong_alias(__pthread_mutexattr_init, pthread_mutexattr_init);
378 int __pthread_mutexattr_destroy(pthread_mutexattr_t *attr)
380 return 0;
382 strong_alias(__pthread_mutexattr_destroy, pthread_mutexattr_destroy);
384 int __pthread_mutexattr_setkind_np(pthread_mutexattr_t *attr, int kind)
386 return 0;
388 strong_alias(__pthread_mutexattr_setkind_np, pthread_mutexattr_setkind_np);
390 int __pthread_mutexattr_getkind_np(pthread_mutexattr_t *attr, int *kind)
392 *kind = PTHREAD_MUTEX_RECURSIVE_NP;
393 return 0;
395 strong_alias(__pthread_mutexattr_getkind_np, pthread_mutexattr_getkind_np);
397 int __pthread_mutexattr_settype(pthread_mutexattr_t *attr, int kind)
399 return 0;
401 strong_alias(__pthread_mutexattr_settype, pthread_mutexattr_settype);
403 int __pthread_mutexattr_gettype(pthread_mutexattr_t *attr, int *kind)
405 *kind = PTHREAD_MUTEX_RECURSIVE_NP;
406 return 0;
408 strong_alias(__pthread_mutexattr_gettype, pthread_mutexattr_gettype);
411 /***** THREAD-SPECIFIC VARIABLES (KEYS) *****/
413 int __pthread_key_create(pthread_key_t *key, void (*destr_function)(void *))
415 static LONG keycnt = FIRST_KEY;
416 *key = InterlockedExchangeAdd(&keycnt, 1);
417 return 0;
419 strong_alias(__pthread_key_create, pthread_key_create);
421 int __pthread_key_delete(pthread_key_t key)
423 return 0;
425 strong_alias(__pthread_key_delete, pthread_key_delete);
427 int __pthread_setspecific(pthread_key_t key, const void *pointer)
429 TEB *teb = NtCurrentTeb();
430 if (!teb->pthread_data) {
431 teb->pthread_data = calloc(MAX_KEYS,sizeof(key_data));
433 ((key_data*)(teb->pthread_data))[key] = pointer;
434 return 0;
436 strong_alias(__pthread_setspecific, pthread_setspecific);
438 void *__pthread_getspecific(pthread_key_t key)
440 TEB *teb = NtCurrentTeb();
441 if (!teb) return NULL;
442 if (!teb->pthread_data) return NULL;
443 return (void *)(((key_data*)(teb->pthread_data))[key]);
445 strong_alias(__pthread_getspecific, pthread_getspecific);
448 /***** "EXCEPTION" FRAMES *****/
449 /* not implemented right now */
451 void _pthread_cleanup_push(struct _pthread_cleanup_buffer *buffer, void (*routine)(void *), void *arg)
453 ((wine_cleanup)buffer)->routine = routine;
454 ((wine_cleanup)buffer)->arg = arg;
457 void _pthread_cleanup_pop(struct _pthread_cleanup_buffer *buffer, int execute)
459 if (execute) (*(((wine_cleanup)buffer)->routine))(((wine_cleanup)buffer)->arg);
462 void _pthread_cleanup_push_defer(struct _pthread_cleanup_buffer *buffer, void (*routine)(void *), void *arg)
464 _pthread_cleanup_push(buffer, routine, arg);
467 void _pthread_cleanup_pop_restore(struct _pthread_cleanup_buffer *buffer, int execute)
469 _pthread_cleanup_pop(buffer, execute);
473 /***** CONDITIONS *****/
474 /* not implemented right now */
476 int pthread_cond_init(pthread_cond_t *cond, const pthread_condattr_t *cond_attr)
478 P_OUTPUT("FIXME:pthread_cond_init\n");
479 return 0;
482 int pthread_cond_destroy(pthread_cond_t *cond)
484 P_OUTPUT("FIXME:pthread_cond_destroy\n");
485 return 0;
488 int pthread_cond_signal(pthread_cond_t *cond)
490 P_OUTPUT("FIXME:pthread_cond_signal\n");
491 return 0;
494 int pthread_cond_broadcast(pthread_cond_t *cond)
496 P_OUTPUT("FIXME:pthread_cond_broadcast\n");
497 return 0;
500 int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)
502 P_OUTPUT("FIXME:pthread_cond_wait\n");
503 return 0;
506 int pthread_cond_timedwait(pthread_cond_t *cond, pthread_mutex_t *mutex, const struct timespec *abstime)
508 P_OUTPUT("FIXME:pthread_cond_timedwait\n");
509 return 0;
512 /**** CONDITION ATTRIBUTES *****/
513 /* not implemented right now */
515 int pthread_condattr_init(pthread_condattr_t *attr)
517 return 0;
520 int pthread_condattr_destroy(pthread_condattr_t *attr)
522 return 0;
525 #if (__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 2)
526 /***** READ-WRITE LOCKS *****/
528 static void rwlock_real_init(pthread_rwlock_t *rwlock)
530 RTL_RWLOCK *lock = HeapAlloc(GetProcessHeap(), 0, sizeof(RTL_RWLOCK));
531 RtlInitializeResource(lock);
533 if (InterlockedCompareExchangePointer((void**)&(((wine_rwlock)rwlock)->lock),lock,NULL) != NULL) {
534 /* too late, some other thread already did it */
535 RtlDeleteResource(lock);
536 HeapFree(GetProcessHeap(), 0, lock);
540 int __pthread_rwlock_init(pthread_rwlock_t *rwlock, const pthread_rwlockattr_t *rwlock_attr)
542 ((wine_rwlock)rwlock)->lock = NULL;
543 return 0;
545 strong_alias(__pthread_rwlock_init, pthread_rwlock_init);
547 int __pthread_rwlock_destroy(pthread_rwlock_t *rwlock)
549 if (!((wine_rwlock)rwlock)->lock) return 0;
550 RtlDeleteResource(((wine_rwlock)rwlock)->lock);
551 HeapFree(GetProcessHeap(), 0, ((wine_rwlock)rwlock)->lock);
552 return 0;
554 strong_alias(__pthread_rwlock_destroy, pthread_rwlock_destroy);
556 int __pthread_rwlock_rdlock(pthread_rwlock_t *rwlock)
558 if (!init_done) return 0;
559 if (!((wine_rwlock)rwlock)->lock)
560 rwlock_real_init( rwlock );
562 while(TRUE)
563 if (RtlAcquireResourceShared(((wine_rwlock)rwlock)->lock, TRUE))
564 return 0;
566 strong_alias(__pthread_rwlock_rdlock, pthread_rwlock_rdlock);
568 int __pthread_rwlock_tryrdlock(pthread_rwlock_t *rwlock)
570 if (!init_done) return 0;
571 if (!((wine_rwlock)rwlock)->lock)
572 rwlock_real_init( rwlock );
574 if (!RtlAcquireResourceShared(((wine_rwlock)rwlock)->lock, FALSE)) {
575 errno = EBUSY;
576 return -1;
578 return 0;
580 strong_alias(__pthread_rwlock_tryrdlock, pthread_rwlock_tryrdlock);
582 int __pthread_rwlock_wrlock(pthread_rwlock_t *rwlock)
584 if (!init_done) return 0;
585 if (!((wine_rwlock)rwlock)->lock)
586 rwlock_real_init( rwlock );
588 while(TRUE)
589 if (RtlAcquireResourceExclusive(((wine_rwlock)rwlock)->lock, TRUE))
590 return 0;
592 strong_alias(__pthread_rwlock_wrlock, pthread_rwlock_wrlock);
594 int __pthread_rwlock_trywrlock(pthread_rwlock_t *rwlock)
596 if (!init_done) return 0;
597 if (!((wine_rwlock)rwlock)->lock)
598 rwlock_real_init( rwlock );
600 if (!RtlAcquireResourceExclusive(((wine_rwlock)rwlock)->lock, FALSE)) {
601 errno = EBUSY;
602 return -1;
604 return 0;
606 strong_alias(__pthread_rwlock_trywrlock, pthread_rwlock_trywrlock);
608 int __pthread_rwlock_unlock(pthread_rwlock_t *rwlock)
610 if (!((wine_rwlock)rwlock)->lock) return 0;
611 RtlReleaseResource( ((wine_rwlock)rwlock)->lock );
612 return 0;
614 strong_alias(__pthread_rwlock_unlock, pthread_rwlock_unlock);
616 /**** READ-WRITE LOCK ATTRIBUTES *****/
617 /* not implemented right now */
619 int pthread_rwlockattr_init(pthread_rwlockattr_t *attr)
621 return 0;
624 int __pthread_rwlockattr_destroy(pthread_rwlockattr_t *attr)
626 return 0;
628 strong_alias(__pthread_rwlockattr_destroy, pthread_rwlockattr_destroy);
630 int pthread_rwlockattr_getkind_np(const pthread_rwlockattr_t *attr, int *pref)
632 *pref = 0;
633 return 0;
636 int pthread_rwlockattr_setkind_np(pthread_rwlockattr_t *attr, int pref)
638 return 0;
640 #endif /* glibc 2.2 */
642 /***** MISC *****/
644 pthread_t pthread_self(void)
646 return (pthread_t)GetCurrentThreadId();
649 int pthread_equal(pthread_t thread1, pthread_t thread2)
651 return (DWORD)thread1 == (DWORD)thread2;
654 void pthread_exit(void *retval)
656 /* FIXME: pthread cleanup */
657 ExitThread((DWORD)retval);
660 int pthread_setcanceltype(int type, int *oldtype)
662 if (oldtype) *oldtype = PTHREAD_CANCEL_ASYNCHRONOUS;
663 return 0;
666 /***** ANTI-OVERRIDES *****/
667 /* pthreads tries to override these, point them back to libc */
669 #ifdef jump_alias
670 jump_alias(LIBC_SIGACTION, sigaction);
671 #else
672 int sigaction(int signum, const struct sigaction *act, struct sigaction *oldact)
674 return LIBC_SIGACTION(signum, act, oldact);
676 #endif
678 #endif /* __GLIBC__ */