OSDN Git Service

3e1aac7fce093930e3ad64dc36e8c47caeb25b12
[pf3gnuchains/gcc-fork.git] / gcc / gthr-win32.h
1 /* Threads compatibility routines for libgcc2 and libobjc.  */
2 /* Compile this one with gcc.  */
3 /* Copyright (C) 1999, 2000, 2002, 2003, 2004  Free Software Foundation, Inc.
4    Contributed by Mumit Khan <khan@xraylith.wisc.edu>.
5
6 This file is part of GCC.
7
8 GCC is free software; you can redistribute it and/or modify it under
9 the terms of the GNU General Public License as published by the Free
10 Software Foundation; either version 2, or (at your option) any later
11 version.
12
13 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
14 WARRANTY; without even the implied warranty of MERCHANTABILITY or
15 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
16 for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING.  If not, write to the Free
20 Software Foundation, 59 Temple Place - Suite 330, Boston, MA
21 02111-1307, USA.  */
22
23 /* As a special exception, if you link this library with other files,
24    some of which are compiled with GCC, to produce an executable,
25    this library does not by itself cause the resulting executable
26    to be covered by the GNU General Public License.
27    This exception does not however invalidate any other reasons why
28    the executable file might be covered by the GNU General Public License.  */
29
30 #ifndef GCC_GTHR_WIN32_H
31 #define GCC_GTHR_WIN32_H
32
33 /* Windows32 threads specific definitions. The windows32 threading model
34    does not map well into pthread-inspired gcc's threading model, and so
35    there are caveats one needs to be aware of.
36
37    1. The destructor supplied to __gthread_key_create is ignored for
38       generic x86-win32 ports. This will certainly cause memory leaks
39       due to unreclaimed eh contexts (sizeof (eh_context) is at least
40       24 bytes for x86 currently).
41
42       This memory leak may be significant for long-running applications
43       that make heavy use of C++ EH.
44
45       However, Mingw runtime (version 0.3 or newer) provides a mechanism
46       to emulate pthreads key dtors; the runtime provides a special DLL,
47       linked in if -mthreads option is specified, that runs the dtors in
48       the reverse order of registration when each thread exits. If
49       -mthreads option is not given, a stub is linked in instead of the
50       DLL, which results in memory leak. Other x86-win32 ports can use
51       the same technique of course to avoid the leak.
52
53    2. The error codes returned are non-POSIX like, and cast into ints.
54       This may cause incorrect error return due to truncation values on
55       hw where sizeof (DWORD) > sizeof (int).
56
57    3. We are currently using a special mutex instead of the Critical
58       Sections, since Win9x does not support TryEnterCriticalSection
59       (while NT does).
60
61    The basic framework should work well enough. In the long term, GCC
62    needs to use Structured Exception Handling on Windows32.  */
63
64 #define __GTHREADS 1
65
66 #include <errno.h>
67 #ifdef __MINGW32__
68 #include <_mingw.h>
69 #endif
70
71 #ifdef _LIBOBJC
72
73 /* This is necessary to prevent windef.h (included from windows.h) from
74    defining it's own BOOL as a typedef.  */
75 #ifndef __OBJC__
76 #define __OBJC__
77 #endif
78 #include <windows.h>
79 /* Now undef the windows BOOL.  */
80 #undef BOOL
81
82 /* Key structure for maintaining thread specific storage */
83 static DWORD    __gthread_objc_data_tls = (DWORD) -1;
84
85 /* Backend initialization functions */
86
87 /* Initialize the threads subsystem.  */
88 int
89 __gthread_objc_init_thread_system (void)
90 {
91   /* Initialize the thread storage key */
92   if ((__gthread_objc_data_tls = TlsAlloc ()) != (DWORD) -1)
93     return 0;
94   else
95     return -1;
96 }
97
98 /* Close the threads subsystem.  */
99 int
100 __gthread_objc_close_thread_system (void)
101 {
102   if (__gthread_objc_data_tls != (DWORD) -1)
103     TlsFree (__gthread_objc_data_tls);
104   return 0;
105 }
106
107 /* Backend thread functions */
108
109 /* Create a new thread of execution.  */
110 objc_thread_t
111 __gthread_objc_thread_detach (void (*func)(void *arg), void *arg)
112 {
113   DWORD thread_id = 0;
114   HANDLE win32_handle;
115
116   if (!(win32_handle = CreateThread (NULL, 0, (LPTHREAD_START_ROUTINE) func,
117                                      arg, 0, &thread_id)))
118     thread_id = 0;
119
120   return (objc_thread_t) thread_id;
121 }
122
123 /* Set the current thread's priority.  */
124 int
125 __gthread_objc_thread_set_priority (int priority)
126 {
127   int sys_priority = 0;
128
129   switch (priority)
130     {
131     case OBJC_THREAD_INTERACTIVE_PRIORITY:
132       sys_priority = THREAD_PRIORITY_NORMAL;
133       break;
134     default:
135     case OBJC_THREAD_BACKGROUND_PRIORITY:
136       sys_priority = THREAD_PRIORITY_BELOW_NORMAL;
137       break;
138     case OBJC_THREAD_LOW_PRIORITY:
139       sys_priority = THREAD_PRIORITY_LOWEST;
140       break;
141     }
142
143   /* Change priority */
144   if (SetThreadPriority (GetCurrentThread (), sys_priority))
145     return 0;
146   else
147     return -1;
148 }
149
150 /* Return the current thread's priority.  */
151 int
152 __gthread_objc_thread_get_priority (void)
153 {
154   int sys_priority;
155
156   sys_priority = GetThreadPriority (GetCurrentThread ());
157
158   switch (sys_priority)
159     {
160     case THREAD_PRIORITY_HIGHEST:
161     case THREAD_PRIORITY_TIME_CRITICAL:
162     case THREAD_PRIORITY_ABOVE_NORMAL:
163     case THREAD_PRIORITY_NORMAL:
164       return OBJC_THREAD_INTERACTIVE_PRIORITY;
165
166     default:
167     case THREAD_PRIORITY_BELOW_NORMAL:
168       return OBJC_THREAD_BACKGROUND_PRIORITY;
169
170     case THREAD_PRIORITY_IDLE:
171     case THREAD_PRIORITY_LOWEST:
172       return OBJC_THREAD_LOW_PRIORITY;
173     }
174
175   /* Couldn't get priority.  */
176   return -1;
177 }
178
179 /* Yield our process time to another thread.  */
180 void
181 __gthread_objc_thread_yield (void)
182 {
183   Sleep (0);
184 }
185
186 /* Terminate the current thread.  */
187 int
188 __gthread_objc_thread_exit (void)
189 {
190   /* exit the thread */
191   ExitThread (__objc_thread_exit_status);
192
193   /* Failed if we reached here */
194   return -1;
195 }
196
197 /* Returns an integer value which uniquely describes a thread.  */
198 objc_thread_t
199 __gthread_objc_thread_id (void)
200 {
201   return (objc_thread_t) GetCurrentThreadId ();
202 }
203
204 /* Sets the thread's local storage pointer.  */
205 int
206 __gthread_objc_thread_set_data (void *value)
207 {
208   if (TlsSetValue (__gthread_objc_data_tls, value))
209     return 0;
210   else
211     return -1;
212 }
213
214 /* Returns the thread's local storage pointer.  */
215 void *
216 __gthread_objc_thread_get_data (void)
217 {
218   DWORD lasterror;
219   void *ptr;
220
221   lasterror = GetLastError ();
222
223   ptr = TlsGetValue (__gthread_objc_data_tls);          /* Return thread data.  */
224
225   SetLastError (lasterror);
226
227   return ptr;
228 }
229
230 /* Backend mutex functions */
231
232 /* Allocate a mutex.  */
233 int
234 __gthread_objc_mutex_allocate (objc_mutex_t mutex)
235 {
236   if ((mutex->backend = (void *) CreateMutex (NULL, 0, NULL)) == NULL)
237     return -1;
238   else
239     return 0;
240 }
241
242 /* Deallocate a mutex.  */
243 int
244 __gthread_objc_mutex_deallocate (objc_mutex_t mutex)
245 {
246   CloseHandle ((HANDLE) (mutex->backend));
247   return 0;
248 }
249
250 /* Grab a lock on a mutex.  */
251 int
252 __gthread_objc_mutex_lock (objc_mutex_t mutex)
253 {
254   int status;
255
256   status = WaitForSingleObject ((HANDLE) (mutex->backend), INFINITE);
257   if (status != WAIT_OBJECT_0 && status != WAIT_ABANDONED)
258     return -1;
259   else
260     return 0;
261 }
262
263 /* Try to grab a lock on a mutex.  */
264 int
265 __gthread_objc_mutex_trylock (objc_mutex_t mutex)
266 {
267   int status;
268
269   status = WaitForSingleObject ((HANDLE) (mutex->backend), 0);
270   if (status != WAIT_OBJECT_0 && status != WAIT_ABANDONED)
271     return -1;
272   else
273     return 0;
274 }
275
276 /* Unlock the mutex */
277 int
278 __gthread_objc_mutex_unlock (objc_mutex_t mutex)
279 {
280   if (ReleaseMutex ((HANDLE) (mutex->backend)) == 0)
281     return -1;
282   else
283     return 0;
284 }
285
286 /* Backend condition mutex functions */
287
288 /* Allocate a condition.  */
289 int
290 __gthread_objc_condition_allocate (objc_condition_t condition)
291 {
292   /* Unimplemented.  */
293   return -1;
294 }
295
296 /* Deallocate a condition.  */
297 int
298 __gthread_objc_condition_deallocate (objc_condition_t condition)
299 {
300   /* Unimplemented.  */
301   return -1;
302 }
303
304 /* Wait on the condition */
305 int
306 __gthread_objc_condition_wait (objc_condition_t condition, objc_mutex_t mutex)
307 {
308   /* Unimplemented.  */
309   return -1;
310 }
311
312 /* Wake up all threads waiting on this condition.  */
313 int
314 __gthread_objc_condition_broadcast (objc_condition_t condition)
315 {
316   /* Unimplemented.  */
317   return -1;
318 }
319
320 /* Wake up one thread waiting on this condition.  */
321 int
322 __gthread_objc_condition_signal (objc_condition_t condition)
323 {
324   /* Unimplemented.  */
325   return -1;
326 }
327
328 #else /* _LIBOBJC */
329
330 #ifdef __cplusplus
331 extern "C" {
332 #endif
333
334 typedef unsigned long __gthread_key_t;
335
336 typedef struct {
337   int done;
338   long started;
339 } __gthread_once_t;
340
341 typedef struct {
342   long counter;
343   void *sema;
344 } __gthread_mutex_t;
345
346 typedef struct {
347   long counter;
348   long depth;
349   DWORD owner;
350   void *sema;
351 } __gthread_recursive_mutex_t;
352
353 #define __GTHREAD_ONCE_INIT {0, -1}
354 #define __GTHREAD_MUTEX_INIT_FUNCTION __gthread_mutex_init_function
355 #define __GTHREAD_MUTEX_INIT_DEFAULT {-1, 0}
356 #define __GTHREAD_RECURSIVE_MUTEX_INIT_FUNCTION __gthread_mutex_init_function
357 #define __GTHREAD_RECURSIVE_MUTEX_INIT_DEFAULT {-1, 0}
358
359 #if __MINGW32_MAJOR_VERSION >= 1 || \
360   (__MINGW32_MAJOR_VERSION == 0 && __MINGW32_MINOR_VERSION > 2)
361 #define MINGW32_SUPPORTS_MT_EH 1
362 /* Mingw runtime >= v0.3 provides a magic variable that is set to nonzero
363    if -mthreads option was specified, or 0 otherwise. This is to get around
364    the lack of weak symbols in PE-COFF.  */
365 extern int _CRT_MT;
366 extern int __mingwthr_key_dtor (unsigned long, void (*) (void *));
367 #endif /* __MINGW32__ version */
368
369 /* The Windows95 kernel does not export InterlockedCompareExchange.
370    This provides a substitute.   When building apps that reference
371    gthread_mutex_try_lock, the  __GTHREAD_I486_INLINE_LOCK_PRIMITIVES
372    macro  must be defined if Windows95 is a target.  Currently
373    gthread_mutex_try_lock is not referenced by libgcc or libstdc++.  */
374 #ifdef __GTHREAD_I486_INLINE_LOCK_PRIMITIVES
375 static inline long
376 __gthr_i486_lock_cmp_xchg(long *dest, long xchg, long comperand)
377 {
378   long result;
379   __asm__ __volatile__ ("\n\
380         lock\n\
381         cmpxchg{l} {%4, %1|%1, %4}\n"
382         : "=a" (result), "=m" (*dest)
383         : "0" (comperand), "m" (*dest), "r" (xchg)
384         : "cc");
385   return result;
386 }
387 #define __GTHR_W32_InterlockedCompareExchange __gthr_i486_lock_cmp_xchg
388 #else  /* __GTHREAD_I486_INLINE_LOCK_PRIMITIVES */
389 #define __GTHR_W32_InterlockedCompareExchange InterlockedCompareExchange
390 #endif /* __GTHREAD_I486_INLINE_LOCK_PRIMITIVES */
391
392 static inline int
393 __gthread_active_p (void)
394 {
395 #ifdef MINGW32_SUPPORTS_MT_EH
396   return _CRT_MT;
397 #else
398   return 1;
399 #endif
400 }
401
402 #if __GTHREAD_HIDE_WIN32API
403
404 /* The implementations are in config/i386/gthr-win32.c in libgcc.a.
405    Only stubs are exposed to avoid polluting the C++ namespace with
406    windows api definitions.  */
407
408 extern int __gthr_win32_once (__gthread_once_t *, void (*) (void));
409 extern int __gthr_win32_key_create (__gthread_key_t *, void (*) (void*));
410 extern int __gthr_win32_key_delete (__gthread_key_t);
411 extern void * __gthr_win32_getspecific (__gthread_key_t);
412 extern int __gthr_win32_setspecific (__gthread_key_t, const void *);
413 extern void __gthr_win32_mutex_init_function (__gthread_mutex_t *);
414 extern int __gthr_win32_mutex_lock (__gthread_mutex_t *);
415 extern int __gthr_win32_mutex_trylock (__gthread_mutex_t *);
416 extern int __gthr_win32_mutex_unlock (__gthread_mutex_t *);
417
418 static inline int
419 __gthread_once (__gthread_once_t *once, void (*func) (void))
420 {
421   if (__gthread_active_p ())
422     return __gthr_win32_once (once, func);
423   else
424     return -1;
425 }
426
427 static inline int
428 __gthread_key_create (__gthread_key_t *key, void (*dtor) (void *))
429 {
430   return __gthr_win32_key_create (key, dtor);
431 }
432
433 static inline int
434 __gthread_key_delete (__gthread_key_t key)
435 {
436   return __gthr_win32_key_delete (key);
437 }
438
439 static inline void *
440 __gthread_getspecific (__gthread_key_t key)
441 {
442   return __gthr_win32_getspecific (key);
443 }
444
445 static inline int
446 __gthread_setspecific (__gthread_key_t key, const void *ptr)
447 {
448   return __gthr_win32_setspecific (key, ptr);
449 }
450
451 static inline void
452 __gthread_mutex_init_function (__gthread_mutex_t *mutex)
453 {
454   __gthr_win32_mutex_init_function (mutex);
455 }
456
457 static inline int
458 __gthread_mutex_lock (__gthread_mutex_t *mutex)
459 {
460   if (__gthread_active_p ())
461     return __gthr_win32_mutex_lock (mutex);
462   else
463     return 0;
464 }
465
466 static inline int
467 __gthread_mutex_trylock (__gthread_mutex_t *mutex)
468 {
469   if (__gthread_active_p ())
470     return __gthr_win32_mutex_trylock (mutex);
471   else
472     return 0;
473 }
474
475 static inline int
476 __gthread_mutex_unlock (__gthread_mutex_t *mutex)
477 {
478   if (__gthread_active_p ())
479     return __gthr_win32_mutex_unlock (mutex);
480   else
481     return 0;
482 }
483
484 static inline int
485 __gthread_recursive_mutex_lock (__gthread_recursive_mutex_t *mutex)
486 {
487   if (__gthread_active_p ())
488     return __gthr_win32_recursive_mutex_lock (mutex);
489   else
490     return 0;
491 }
492
493 static inline int
494 __gthread_recursive_mutex_trylock (__gthread_recursive_mutex_t *mutex)
495 {
496   if (__gthread_active_p ())
497     return __gthr_win32_recursive_mutex_trylock (mutex);
498   else
499     return 0;
500 }
501
502 static inline int
503 __gthread_recursive_mutex_unlock (__gthread_recursive_mutex_t *mutex)
504 {
505   if (__gthread_active_p ())
506     return __gthr_win32_recursive_mutex_unlock (mutex);
507   else
508     return 0;
509 }
510
511 #else /* ! __GTHREAD_HIDE_WIN32API */
512
513 #include <windows.h>
514 #include <errno.h>
515
516 static inline int
517 __gthread_once (__gthread_once_t *once, void (*func) (void))
518 {
519   if (! __gthread_active_p ())
520     return -1;
521   else if (once == NULL || func == NULL)
522     return EINVAL;
523
524   if (! once->done)
525     {
526       if (InterlockedIncrement (&(once->started)) == 0)
527         {
528           (*func) ();
529           once->done = TRUE;
530         }
531       else
532         {
533           /* Another thread is currently executing the code, so wait for it
534              to finish; yield the CPU in the meantime.  If performance
535              does become an issue, the solution is to use an Event that
536              we wait on here (and set above), but that implies a place to
537              create the event before this routine is called.  */
538           while (! once->done)
539             Sleep (0);
540         }
541     }
542
543   return 0;
544 }
545
546 /* Windows32 thread local keys don't support destructors; this leads to
547    leaks, especially in threaded applications making extensive use of
548    C++ EH. Mingw uses a thread-support DLL to work-around this problem.  */
549 static inline int
550 __gthread_key_create (__gthread_key_t *key, void (*dtor) (void *))
551 {
552   int status = 0;
553   DWORD tls_index = TlsAlloc ();
554   if (tls_index != 0xFFFFFFFF)
555     {
556       *key = tls_index;
557 #ifdef MINGW32_SUPPORTS_MT_EH
558       /* Mingw runtime will run the dtors in reverse order for each thread
559          when the thread exits.  */
560       status = __mingwthr_key_dtor (*key, dtor);
561 #endif
562     }
563   else
564     status = (int) GetLastError ();
565   return status;
566 }
567
568 static inline int
569 __gthread_key_delete (__gthread_key_t key)
570 {
571   return (TlsFree (key) != 0) ? 0 : (int) GetLastError ();
572 }
573
574 static inline void *
575 __gthread_getspecific (__gthread_key_t key)
576 {
577   DWORD lasterror;
578   void *ptr;
579
580   lasterror = GetLastError ();
581
582   ptr = TlsGetValue (key);
583
584   SetLastError (lasterror);
585
586   return ptr;
587 }
588
589 static inline int
590 __gthread_setspecific (__gthread_key_t key, const void *ptr)
591 {
592   return (TlsSetValue (key, (void*) ptr) != 0) ? 0 : (int) GetLastError ();
593 }
594
595 static inline void
596 __gthread_mutex_init_function (__gthread_mutex_t *mutex)
597 {
598   mutex->counter = -1;
599   mutex->sema = CreateSemaphore (NULL, 0, 65535, NULL);
600 }
601
602 static inline int
603 __gthread_mutex_lock (__gthread_mutex_t *mutex)
604 {
605   int status = 0;
606
607   if (__gthread_active_p ())
608     {
609       if (InterlockedIncrement (&mutex->counter) == 0 ||
610           WaitForSingleObject (mutex->sema, INFINITE) == WAIT_OBJECT_0)
611         status = 0;
612       else
613         {
614           /* WaitForSingleObject returns WAIT_FAILED, and we can only do
615              some best-effort cleanup here.  */
616           InterlockedDecrement (&mutex->counter);
617           status = 1;
618         }
619     }
620   return status;
621 }
622
623 static inline int
624 __gthread_mutex_trylock (__gthread_mutex_t *mutex)
625 {
626   int status = 0;
627
628   if (__gthread_active_p ())
629     {
630       if (__GTHR_W32_InterlockedCompareExchange (&mutex->counter, 0, -1) < 0)
631         status = 0;
632       else
633         status = 1;
634     }
635   return status;
636 }
637
638 static inline int
639 __gthread_mutex_unlock (__gthread_mutex_t *mutex)
640 {
641   if (__gthread_active_p ())
642     {
643       if (InterlockedDecrement (&mutex->counter) >= 0)
644         return ReleaseSemaphore (mutex->sema, 1, NULL) ? 0 : 1;
645     }
646   return 0;
647 }
648
649 static inline void
650 __gthread_recursive_mutex_init_function (__gthread_recursive_mutex_t *mutex)
651 {
652   mutex->counter = -1;
653   mutex->depth = 0;
654   mutex->owner = 0;
655   mutex->sema = CreateSemaphore (NULL, 0, 65535, NULL);
656 }
657
658 static inline int
659 __gthread_recursive_mutex_lock (__gthread_recursive_mutex_t *mutex)
660 {
661   if (__gthread_active_p ())
662     {
663       DWORD me = GetCurrentThreadId();
664       if (InterlockedIncrement (&mutex->counter) == 0)
665         {
666           mutex->depth = 1;
667           mutex->owner = me;
668         }
669       else if (mutex->owner == me)
670         {
671           InterlockedDecrement (&mx->lock_idx);
672           ++(mutex->depth);
673         }
674       else if (WaitForSingleObject (mutex->sema, INFINITE) == WAIT_OBJECT_0)
675         {
676           mutex->depth = 1;
677           mutex->owner = me;
678         }
679       else
680         {
681           /* WaitForSingleObject returns WAIT_FAILED, and we can only do
682              some best-effort cleanup here.  */
683           InterlockedDecrement (&mutex->counter);
684           return 1;
685         }
686     }
687   return 0;
688 }
689
690 static inline int
691 __gthread_recursive_mutex_trylock (__gthread_recursive_mutex_t *mutex)
692 {
693   if (__gthread_active_p ())
694     {
695       DWORD me = GetCurrentThreadId();
696       if (__GTHR_W32_InterlockedCompareExchange (&mutex->counter, 0, -1) < 0)
697         {
698           mutex->depth = 1;
699           mutex->owner = me;
700         }
701       else if (mutex->owner == me)
702         ++(mutex->depth);
703       else
704         return 1;
705     }
706   return 0;
707 }
708
709 static inline int
710 __gthread_recursive_mutex_unlock (__gthread_recursive_mutex_t *mutex)
711 {
712   if (__gthread_active_p ())
713     {
714       --(mutex->depth);
715       if (mutex->depth == 0)
716         {
717           mutex->owner = 0;
718
719           if (InterlockedDecrement (&mutex->counter) >= 0)
720             return ReleaseSemaphore (mutex->sema, 1, NULL) ? 0 : 1;
721         }
722     }
723   return 0;
724 }
725
726 #endif /*  __GTHREAD_HIDE_WIN32API */
727
728 #ifdef __cplusplus
729 }
730 #endif
731
732 #endif /* _LIBOBJC */
733
734 #endif /* ! GCC_GTHR_WIN32_H */