2005-04-12 Dick Porter <dick@ximian.com>
[mono.git] / libgc / win32_threads.c
1 #if defined(GC_WIN32_THREADS) 
2
3 #include "private/gc_priv.h"
4 #include <windows.h>
5
6 #ifdef CYGWIN32
7 # include <errno.h>
8
9  /* Cygwin-specific forward decls */
10 # undef pthread_create 
11 # undef pthread_sigmask 
12 # undef pthread_join 
13 # undef dlopen 
14
15 # define DEBUG_CYGWIN_THREADS 0
16
17   void * GC_start_routine(void * arg);
18   void GC_thread_exit_proc(void *arg);
19
20 #endif
21
22 /* The type of the first argument to InterlockedExchange.       */
23 /* Documented to be LONG volatile *, but at least gcc likes     */
24 /* this better.                                                 */
25 typedef LONG * IE_t;
26
27 #ifndef MAX_THREADS
28 # define MAX_THREADS 256
29     /* FIXME:                                                   */
30     /* Things may get quite slow for large numbers of threads,  */
31     /* since we look them up with sequential search.            */
32 #endif
33
34 GC_bool GC_thr_initialized = FALSE;
35
36 DWORD GC_main_thread = 0;
37
38 struct GC_thread_Rep {
39   LONG in_use; /* Updated without lock. */
40                         /* We assert that unused        */
41                         /* entries have invalid ids of  */
42                         /* zero and zero stack fields.  */
43   DWORD id;
44   HANDLE handle;
45   ptr_t stack_base;     /* The cold end of the stack.   */
46                         /* 0 ==> entry not valid.       */
47                         /* !in_use ==> stack_base == 0  */
48   GC_bool suspended;
49
50 # ifdef CYGWIN32
51     void *status; /* hold exit value until join in case it's a pointer */
52     pthread_t pthread_id;
53     short flags;                /* Protected by GC lock.        */
54 #       define FINISHED 1       /* Thread has exited.   */
55 #       define DETACHED 2       /* Thread is intended to be detached.   */
56 # endif
57 };
58
59 typedef volatile struct GC_thread_Rep * GC_thread;
60
61 /*
62  * We generally assume that volatile ==> memory ordering, at least among
63  * volatiles.
64  */
65
66 volatile GC_bool GC_please_stop = FALSE;
67
68 volatile struct GC_thread_Rep thread_table[MAX_THREADS];
69
70 volatile LONG GC_max_thread_index = 0; /* Largest index in thread_table */
71                                        /* that was ever used.           */
72
73 extern LONG WINAPI GC_write_fault_handler(struct _EXCEPTION_POINTERS *exc_info);
74
75 int GC_thread_is_registered (void)
76 {
77         return 1;
78 }
79
80 /*
81  * This may be called from DllMain, and hence operates under unusual
82  * constraints.
83  */
84 static GC_thread GC_new_thread(void) {
85   int i;
86   /* It appears to be unsafe to acquire a lock here, since this */
87   /* code is apparently not preeemptible on some systems.       */
88   /* (This is based on complaints, not on Microsoft's official  */
89   /* documentation, which says this should perform "only simple */
90   /* initialization tasks".)                                    */
91   /* Hence we make do with nonblocking synchronization.         */
92
93   /* The following should be a noop according to the win32      */
94   /* documentation.  There is empirical evidence that it        */
95   /* isn't.             - HB                                    */
96 # if defined(MPROTECT_VDB)
97    if (GC_incremental) SetUnhandledExceptionFilter(GC_write_fault_handler);
98 # endif
99                 /* cast away volatile qualifier */
100   for (i = 0; InterlockedExchange((IE_t)&thread_table[i].in_use,1) != 0; i++) {
101     /* Compare-and-swap would make this cleaner, but that's not         */
102     /* supported before Windows 98 and NT 4.0.  In Windows 2000,        */
103     /* InterlockedExchange is supposed to be replaced by                */
104     /* InterlockedExchangePointer, but that's not really what I         */
105     /* want here.                                                       */
106     if (i == MAX_THREADS - 1)
107       ABORT("too many threads");
108   }
109   /* Update GC_max_thread_index if necessary.  The following is safe,   */
110   /* and unlike CompareExchange-based solutions seems to work on all    */
111   /* Windows95 and later platforms.                                     */
112   /* Unfortunately, GC_max_thread_index may be temporarily out of       */
113   /* bounds, so readers have to compensate.                             */
114   while (i > GC_max_thread_index) {
115     InterlockedIncrement((IE_t)&GC_max_thread_index);
116   }
117   if (GC_max_thread_index >= MAX_THREADS) {
118     /* We overshot due to simultaneous increments.      */
119     /* Setting it to MAX_THREADS-1 is always safe.      */
120     GC_max_thread_index = MAX_THREADS - 1;
121   }
122   
123 # ifdef CYGWIN32
124     thread_table[i].pthread_id = pthread_self();
125 # endif
126   if (!DuplicateHandle(GetCurrentProcess(),
127                        GetCurrentThread(),
128                        GetCurrentProcess(),
129                        (HANDLE*)&thread_table[i].handle,
130                        0,
131                        0,
132                        DUPLICATE_SAME_ACCESS)) {
133         DWORD last_error = GetLastError();
134         GC_printf1("Last error code: %lx\n", last_error);
135         ABORT("DuplicateHandle failed");
136   }
137   thread_table[i].stack_base = GC_get_stack_base();
138   /* Up until this point, GC_push_all_stacks considers this thread      */
139   /* invalid.                                                           */
140   if (thread_table[i].stack_base == NULL) 
141     ABORT("Failed to find stack base in GC_new_thread");
142   /* Up until this point, this entry is viewed as reserved but invalid  */
143   /* by GC_delete_thread.                                               */
144   thread_table[i].id = GetCurrentThreadId();
145   /* If this thread is being created while we are trying to stop        */
146   /* the world, wait here.  Hopefully this can't happen on any  */
147   /* systems that don't allow us to block here.                 */
148   while (GC_please_stop) Sleep(20);
149   return thread_table + i;
150 }
151
152 /*
153  * GC_max_thread_index may temporarily be larger than MAX_THREADS.
154  * To avoid subscript errors, we check on access.
155  */
156 #ifdef __GNUC__
157 __inline__
158 #endif
159 LONG GC_get_max_thread_index()
160 {
161   LONG my_max = GC_max_thread_index;
162
163   if (my_max >= MAX_THREADS) return MAX_THREADS-1;
164   return my_max;
165 }
166
167 /* This is intended to be lock-free, though that                        */
168 /* assumes that the CloseHandle becomes visible before the              */
169 /* in_use assignment.                                                   */
170 static void GC_delete_gc_thread(GC_thread thr)
171 {
172     CloseHandle(thr->handle);
173       /* cast away volatile qualifier */
174     thr->stack_base = 0;
175     thr->id = 0;
176 #   ifdef CYGWIN32
177       thr->pthread_id = 0;
178 #   endif /* CYGWIN32 */
179     thr->in_use = FALSE;
180 }
181
182 static void GC_delete_thread(DWORD thread_id) {
183   int i;
184   LONG my_max = GC_get_max_thread_index();
185
186   for (i = 0;
187        i <= my_max &&
188        (!thread_table[i].in_use || thread_table[i].id != thread_id);
189        /* Must still be in_use, since nobody else can store our thread_id. */
190        i++) {}
191   if (i > my_max) {
192     WARN("Removing nonexisiting thread %ld\n", (GC_word)thread_id);
193   } else {
194     GC_delete_gc_thread(thread_table+i);
195   }
196 }
197
198
199 #ifdef CYGWIN32
200
201 /* Return a GC_thread corresponding to a given pthread_t.       */
202 /* Returns 0 if it's not there.                                 */
203 /* We assume that this is only called for pthread ids that      */
204 /* have not yet terminated or are still joinable.               */
205 static GC_thread GC_lookup_thread(pthread_t id)
206 {
207   int i;
208   LONG my_max = GC_get_max_thread_index();
209
210   for (i = 0;
211        i <= my_max &&
212        (!thread_table[i].in_use || thread_table[i].pthread_id != id
213         || !thread_table[i].in_use);
214        /* Must still be in_use, since nobody else can store our thread_id. */
215        i++);
216   if (i > my_max) return 0;
217   return thread_table + i;
218 }
219
220 #endif /* CYGWIN32 */
221
222 void GC_push_thread_structures GC_PROTO((void))
223 {
224     /* Unlike the other threads implementations, the thread table here  */
225     /* contains no pointers to the collectable heap.  Thus we have      */
226     /* no private structures we need to preserve.                       */
227 # ifdef CYGWIN32
228   { int i; /* pthreads may keep a pointer in the thread exit value */
229     LONG my_max = GC_get_max_thread_index();
230
231     for (i = 0; i <= my_max; i++)
232       if (thread_table[i].in_use)
233         GC_push_all((ptr_t)&(thread_table[i].status),
234                     (ptr_t)(&(thread_table[i].status)+1));
235   }
236 # endif
237 }
238
239 void GC_stop_world()
240 {
241   DWORD thread_id = GetCurrentThreadId();
242   int i;
243
244   if (!GC_thr_initialized) ABORT("GC_stop_world() called before GC_thr_init()");
245
246   GC_please_stop = TRUE;
247   for (i = 0; i <= GC_get_max_thread_index(); i++)
248     if (thread_table[i].stack_base != 0
249         && thread_table[i].id != thread_id) {
250 #     ifdef MSWINCE
251         /* SuspendThread will fail if thread is running kernel code */
252         while (SuspendThread(thread_table[i].handle) == (DWORD)-1)
253           Sleep(10);
254 #     else
255         /* Apparently the Windows 95 GetOpenFileName call creates       */
256         /* a thread that does not properly get cleaned up, and          */
257         /* SuspendThread on its descriptor may provoke a crash.         */
258         /* This reduces the probability of that event, though it still  */
259         /* appears there's a race here.                                 */
260         DWORD exitCode; 
261         if (GetExitCodeThread(thread_table[i].handle,&exitCode) &&
262             exitCode != STILL_ACTIVE) {
263           thread_table[i].stack_base = 0; /* prevent stack from being pushed */
264 #         ifndef CYGWIN32
265             /* this breaks pthread_join on Cygwin, which is guaranteed to  */
266             /* only see user pthreads                                      */
267             thread_table[i].in_use = FALSE;
268             CloseHandle(thread_table[i].handle);
269 #         endif
270           continue;
271         }
272         if (SuspendThread(thread_table[i].handle) == (DWORD)-1)
273           ABORT("SuspendThread failed");
274 #     endif
275       thread_table[i].suspended = TRUE;
276     }
277 }
278
279 void GC_start_world()
280 {
281   DWORD thread_id = GetCurrentThreadId();
282   int i;
283   LONG my_max = GC_get_max_thread_index();
284
285   for (i = 0; i <= my_max; i++)
286     if (thread_table[i].stack_base != 0 && thread_table[i].suspended
287         && thread_table[i].id != thread_id) {
288       if (ResumeThread(thread_table[i].handle) == (DWORD)-1)
289         ABORT("ResumeThread failed");
290       thread_table[i].suspended = FALSE;
291     }
292   GC_please_stop = FALSE;
293 }
294
295 # ifdef _MSC_VER
296 #   pragma warning(disable:4715)
297 # endif
298 ptr_t GC_current_stackbottom()
299 {
300   DWORD thread_id = GetCurrentThreadId();
301   int i;
302   LONG my_max = GC_get_max_thread_index();
303
304   for (i = 0; i <= my_max; i++)
305     if (thread_table[i].stack_base && thread_table[i].id == thread_id)
306       return thread_table[i].stack_base;
307   ABORT("no thread table entry for current thread");
308 }
309 # ifdef _MSC_VER
310 #   pragma warning(default:4715)
311 # endif
312
313 # ifdef MSWINCE
314     /* The VirtualQuery calls below won't work properly on WinCE, but   */
315     /* since each stack is restricted to an aligned 64K region of       */
316     /* virtual memory we can just take the next lowest multiple of 64K. */
317 #   define GC_get_stack_min(s) \
318         ((ptr_t)(((DWORD)(s) - 1) & 0xFFFF0000))
319 # else
320     static ptr_t GC_get_stack_min(ptr_t s)
321     {
322         ptr_t bottom;
323         MEMORY_BASIC_INFORMATION info;
324         VirtualQuery(s, &info, sizeof(info));
325         do {
326             bottom = info.BaseAddress;
327             VirtualQuery(bottom - 1, &info, sizeof(info));
328         } while ((info.Protect & PAGE_READWRITE)
329                  && !(info.Protect & PAGE_GUARD));
330         return(bottom);
331     }
332 # endif
333
334 void GC_push_all_stacks()
335 {
336   DWORD thread_id = GetCurrentThreadId();
337   GC_bool found_me = FALSE;
338   int i;
339   int dummy;
340   ptr_t sp, stack_min;
341   GC_thread thread;
342   LONG my_max = GC_get_max_thread_index();
343   
344   for (i = 0; i <= my_max; i++) {
345     thread = thread_table + i;
346     if (thread -> in_use && thread -> stack_base) {
347       if (thread -> id == thread_id) {
348         sp = (ptr_t) &dummy;
349         found_me = TRUE;
350       } else {
351         CONTEXT context;
352         context.ContextFlags = CONTEXT_INTEGER|CONTEXT_CONTROL;
353         if (!GetThreadContext(thread_table[i].handle, &context))
354           ABORT("GetThreadContext failed");
355
356         /* Push all registers that might point into the heap.  Frame    */
357         /* pointer registers are included in case client code was       */
358         /* compiled with the 'omit frame pointer' optimisation.         */
359 #       define PUSH1(reg) GC_push_one((word)context.reg)
360 #       define PUSH2(r1,r2) PUSH1(r1), PUSH1(r2)
361 #       define PUSH4(r1,r2,r3,r4) PUSH2(r1,r2), PUSH2(r3,r4)
362 #       if defined(I386)
363           PUSH4(Edi,Esi,Ebx,Edx), PUSH2(Ecx,Eax), PUSH1(Ebp);
364           sp = (ptr_t)context.Esp;
365 #       elif defined(ARM32)
366           PUSH4(R0,R1,R2,R3),PUSH4(R4,R5,R6,R7),PUSH4(R8,R9,R10,R11),PUSH1(R12);
367           sp = (ptr_t)context.Sp;
368 #       elif defined(SHx)
369           PUSH4(R0,R1,R2,R3), PUSH4(R4,R5,R6,R7), PUSH4(R8,R9,R10,R11);
370           PUSH2(R12,R13), PUSH1(R14);
371           sp = (ptr_t)context.R15;
372 #       elif defined(MIPS)
373           PUSH4(IntAt,IntV0,IntV1,IntA0), PUSH4(IntA1,IntA2,IntA3,IntT0);
374           PUSH4(IntT1,IntT2,IntT3,IntT4), PUSH4(IntT5,IntT6,IntT7,IntS0);
375           PUSH4(IntS1,IntS2,IntS3,IntS4), PUSH4(IntS5,IntS6,IntS7,IntT8);
376           PUSH4(IntT9,IntK0,IntK1,IntS8);
377           sp = (ptr_t)context.IntSp;
378 #       elif defined(PPC)
379           PUSH4(Gpr0, Gpr3, Gpr4, Gpr5),  PUSH4(Gpr6, Gpr7, Gpr8, Gpr9);
380           PUSH4(Gpr10,Gpr11,Gpr12,Gpr14), PUSH4(Gpr15,Gpr16,Gpr17,Gpr18);
381           PUSH4(Gpr19,Gpr20,Gpr21,Gpr22), PUSH4(Gpr23,Gpr24,Gpr25,Gpr26);
382           PUSH4(Gpr27,Gpr28,Gpr29,Gpr30), PUSH1(Gpr31);
383           sp = (ptr_t)context.Gpr1;
384 #       elif defined(ALPHA)
385           PUSH4(IntV0,IntT0,IntT1,IntT2), PUSH4(IntT3,IntT4,IntT5,IntT6);
386           PUSH4(IntT7,IntS0,IntS1,IntS2), PUSH4(IntS3,IntS4,IntS5,IntFp);
387           PUSH4(IntA0,IntA1,IntA2,IntA3), PUSH4(IntA4,IntA5,IntT8,IntT9);
388           PUSH4(IntT10,IntT11,IntT12,IntAt);
389           sp = (ptr_t)context.IntSp;
390 #       else
391 #         error "architecture is not supported"
392 #       endif
393       }
394
395       stack_min = GC_get_stack_min(thread->stack_base);
396
397       if (sp >= stack_min && sp < thread->stack_base)
398         GC_push_all_stack(sp, thread->stack_base);
399       else {
400         WARN("Thread stack pointer 0x%lx out of range, pushing everything\n",
401              (unsigned long)sp);
402         GC_push_all_stack(stack_min, thread->stack_base);
403       }
404     }
405   }
406   if (!found_me) ABORT("Collecting from unknown thread.");
407 }
408
409 void GC_get_next_stack(char *start, char **lo, char **hi)
410 {
411     int i;
412 #   define ADDR_LIMIT (char *)(-1L)
413     char * current_min = ADDR_LIMIT;
414     LONG my_max = GC_get_max_thread_index();
415   
416     for (i = 0; i <= my_max; i++) {
417         char * s = (char *)thread_table[i].stack_base;
418
419         if (0 != s && s > start && s < current_min) {
420             current_min = s;
421         }
422     }
423     *hi = current_min;
424     if (current_min == ADDR_LIMIT) {
425         *lo = ADDR_LIMIT;
426         return;
427     }
428     *lo = GC_get_stack_min(current_min);
429     if (*lo < start) *lo = start;
430 }
431
432 #if !defined(CYGWIN32)
433
434 #if !defined(MSWINCE) && defined(GC_DLL)
435
436 /* We register threads from DllMain */
437
438 GC_API HANDLE WINAPI GC_CreateThread(
439     LPSECURITY_ATTRIBUTES lpThreadAttributes, 
440     DWORD dwStackSize, LPTHREAD_START_ROUTINE lpStartAddress, 
441     LPVOID lpParameter, DWORD dwCreationFlags, LPDWORD lpThreadId )
442 {
443     return CreateThread(lpThreadAttributes, dwStackSize, lpStartAddress,
444                         lpParameter, dwCreationFlags, lpThreadId);
445 }
446
447 #else /* defined(MSWINCE) || !defined(GC_DLL))  */
448
449 /* We have no DllMain to take care of new threads.  Thus we     */
450 /* must properly intercept thread creation.                     */
451
452 typedef struct {
453     LPTHREAD_START_ROUTINE start;
454     LPVOID param;
455 } thread_args;
456
457 static DWORD WINAPI thread_start(LPVOID arg);
458
459 GC_API HANDLE WINAPI GC_CreateThread(
460     LPSECURITY_ATTRIBUTES lpThreadAttributes, 
461     DWORD dwStackSize, LPTHREAD_START_ROUTINE lpStartAddress, 
462     LPVOID lpParameter, DWORD dwCreationFlags, LPDWORD lpThreadId )
463 {
464     HANDLE thread_h = NULL;
465
466     thread_args *args;
467
468     if (!GC_is_initialized) GC_init();
469                 /* make sure GC is initialized (i.e. main thread is attached) */
470     
471     args = GC_malloc_uncollectable(sizeof(thread_args)); 
472         /* Handed off to and deallocated by child thread.       */
473     if (0 == args) {
474         SetLastError(ERROR_NOT_ENOUGH_MEMORY);
475         return NULL;
476     }
477
478     /* set up thread arguments */
479         args -> start = lpStartAddress;
480         args -> param = lpParameter;
481
482     thread_h = CreateThread(lpThreadAttributes,
483                             dwStackSize, thread_start,
484                             args, dwCreationFlags,
485                             lpThreadId);
486
487     return thread_h;
488 }
489
490 static DWORD WINAPI thread_start(LPVOID arg)
491 {
492     DWORD ret = 0;
493     thread_args *args = (thread_args *)arg;
494
495     GC_new_thread();
496
497     /* Clear the thread entry even if we exit with an exception.        */
498     /* This is probably pointless, since an uncaught exception is       */
499     /* supposed to result in the process being killed.                  */
500 #ifndef __GNUC__
501     __try {
502 #endif /* __GNUC__ */
503         ret = args->start (args->param);
504 #ifndef __GNUC__
505     } __finally {
506 #endif /* __GNUC__ */
507         GC_free(args);
508         GC_delete_thread(GetCurrentThreadId());
509 #ifndef __GNUC__
510     }
511 #endif /* __GNUC__ */
512
513     return ret;
514 }
515 #endif /* !defined(MSWINCE) && !(defined(__MINGW32__) && !defined(_DLL))  */
516
517 #endif /* !CYGWIN32 */
518
519 #ifdef MSWINCE
520
521 typedef struct {
522     HINSTANCE hInstance;
523     HINSTANCE hPrevInstance;
524     LPWSTR lpCmdLine;
525     int nShowCmd;
526 } main_thread_args;
527
528 DWORD WINAPI main_thread_start(LPVOID arg);
529
530 int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
531                    LPWSTR lpCmdLine, int nShowCmd)
532 {
533     DWORD exit_code = 1;
534
535     main_thread_args args = {
536         hInstance, hPrevInstance, lpCmdLine, nShowCmd
537     };
538     HANDLE thread_h;
539     DWORD thread_id;
540
541     /* initialize everything */
542     GC_init();
543
544     /* start the main thread */
545     thread_h = GC_CreateThread(
546         NULL, 0, main_thread_start, &args, 0, &thread_id);
547
548     if (thread_h != NULL)
549     {
550         WaitForSingleObject (thread_h, INFINITE);
551         GetExitCodeThread (thread_h, &exit_code);
552         CloseHandle (thread_h);
553     }
554
555     GC_deinit();
556     DeleteCriticalSection(&GC_allocate_ml);
557
558     return (int) exit_code;
559 }
560
561 DWORD WINAPI main_thread_start(LPVOID arg)
562 {
563     main_thread_args * args = (main_thread_args *) arg;
564
565     return (DWORD) GC_WinMain (args->hInstance, args->hPrevInstance,
566                                args->lpCmdLine, args->nShowCmd);
567 }
568
569 # else /* !MSWINCE */
570
571 /* Called by GC_init() - we hold the allocation lock.   */
572 void GC_thr_init() {
573     if (GC_thr_initialized) return;
574     GC_main_thread = GetCurrentThreadId();
575     GC_thr_initialized = TRUE;
576
577     /* Add the initial thread, so we can stop it.       */
578     GC_new_thread();
579 }
580
581 #ifdef CYGWIN32
582
583 struct start_info {
584     void *(*start_routine)(void *);
585     void *arg;
586     GC_bool detached;
587 };
588
589 int GC_pthread_join(pthread_t pthread_id, void **retval) {
590     int result;
591     int i;
592     GC_thread me;
593
594 #   if DEBUG_CYGWIN_THREADS
595       GC_printf3("thread 0x%x(0x%x) is joining thread 0x%x.\n",
596                  (int)pthread_self(), GetCurrentThreadId(), (int)pthread_id);
597 #   endif
598
599     /* Thread being joined might not have registered itself yet. */
600     /* After the join,thread id may have been recycled.          */
601     /* FIXME: It would be better if this worked more like        */
602     /* pthread_support.c.                                        */
603
604     while ((me = GC_lookup_thread(pthread_id)) == 0) Sleep(10);
605
606     result = pthread_join(pthread_id, retval);
607
608     GC_delete_gc_thread(me);
609
610 #   if DEBUG_CYGWIN_THREADS
611       GC_printf3("thread 0x%x(0x%x) completed join with thread 0x%x.\n",
612                  (int)pthread_self(), GetCurrentThreadId(), (int)pthread_id);
613 #   endif
614
615     return result;
616 }
617
618 /* Cygwin-pthreads calls CreateThread internally, but it's not
619  * easily interceptible by us..
620  *   so intercept pthread_create instead
621  */
622 int
623 GC_pthread_create(pthread_t *new_thread,
624                   const pthread_attr_t *attr,
625                   void *(*start_routine)(void *), void *arg) {
626     int result;
627     struct start_info * si;
628
629     if (!GC_is_initialized) GC_init();
630                 /* make sure GC is initialized (i.e. main thread is attached) */
631     
632     /* This is otherwise saved only in an area mmapped by the thread */
633     /* library, which isn't visible to the collector.            */
634     si = GC_malloc_uncollectable(sizeof(struct start_info)); 
635     if (0 == si) return(EAGAIN);
636
637     si -> start_routine = start_routine;
638     si -> arg = arg;
639     if (attr != 0 &&
640         pthread_attr_getdetachstate(attr, &si->detached)
641         == PTHREAD_CREATE_DETACHED) {
642       si->detached = TRUE;
643     }
644
645 #   if DEBUG_CYGWIN_THREADS
646       GC_printf2("About to create a thread from 0x%x(0x%x)\n",
647                  (int)pthread_self(), GetCurrentThreadId);
648 #   endif
649     result = pthread_create(new_thread, attr, GC_start_routine, si); 
650
651     if (result) { /* failure */
652         GC_free(si);
653     } 
654
655     return(result);
656 }
657
658 void * GC_start_routine(void * arg)
659 {
660     struct start_info * si = arg;
661     void * result;
662     void *(*start)(void *);
663     void *start_arg;
664     pthread_t pthread_id;
665     GC_thread me;
666     GC_bool detached;
667     int i;
668
669 #   if DEBUG_CYGWIN_THREADS
670       GC_printf2("thread 0x%x(0x%x) starting...\n",(int)pthread_self(),
671                                                    GetCurrentThreadId());
672 #   endif
673
674     /* If a GC occurs before the thread is registered, that GC will     */
675     /* ignore this thread.  That's fine, since it will block trying to  */
676     /* acquire the allocation lock, and won't yet hold interesting      */
677     /* pointers.                                                        */
678     LOCK();
679     /* We register the thread here instead of in the parent, so that    */
680     /* we don't need to hold the allocation lock during pthread_create. */
681     me = GC_new_thread();
682     UNLOCK();
683
684     start = si -> start_routine;
685     start_arg = si -> arg;
686     if (si-> detached) me -> flags |= DETACHED;
687     me -> pthread_id = pthread_id = pthread_self();
688
689     GC_free(si); /* was allocated uncollectable */
690
691     pthread_cleanup_push(GC_thread_exit_proc, (void *)me);
692     result = (*start)(start_arg);
693     me -> status = result;
694     pthread_cleanup_pop(0);
695
696 #   if DEBUG_CYGWIN_THREADS
697       GC_printf2("thread 0x%x(0x%x) returned from start routine.\n",
698                  (int)pthread_self(),GetCurrentThreadId());
699 #   endif
700
701     return(result);
702 }
703
704 void GC_thread_exit_proc(void *arg)
705 {
706     GC_thread me = (GC_thread)arg;
707     int i;
708
709 #   if DEBUG_CYGWIN_THREADS
710       GC_printf2("thread 0x%x(0x%x) called pthread_exit().\n",
711                  (int)pthread_self(),GetCurrentThreadId());
712 #   endif
713
714     LOCK();
715     if (me -> flags & DETACHED) {
716       GC_delete_thread(GetCurrentThreadId());
717     } else {
718       /* deallocate it as part of join */
719       me -> flags |= FINISHED;
720     }
721     UNLOCK();
722 }
723
724 /* nothing required here... */
725 int GC_pthread_sigmask(int how, const sigset_t *set, sigset_t *oset) {
726   return pthread_sigmask(how, set, oset);
727 }
728
729 int GC_pthread_detach(pthread_t thread)
730 {
731     int result;
732     GC_thread thread_gc_id;
733     
734     LOCK();
735     thread_gc_id = GC_lookup_thread(thread);
736     UNLOCK();
737     result = pthread_detach(thread);
738     if (result == 0) {
739       LOCK();
740       thread_gc_id -> flags |= DETACHED;
741       /* Here the pthread thread id may have been recycled. */
742       if (thread_gc_id -> flags & FINISHED) {
743         GC_delete_gc_thread(thread_gc_id);
744       }
745       UNLOCK();
746     }
747     return result;
748 }
749
750 #else /* !CYGWIN32 */
751
752 /*
753  * We avoid acquiring locks here, since this doesn't seem to be preemptable.
754  * Pontus Rydin suggests wrapping the thread start routine instead.
755  */
756 #ifdef GC_DLL
757 BOOL WINAPI DllMain(HINSTANCE inst, ULONG reason, LPVOID reserved)
758 {
759   switch (reason) {
760   case DLL_PROCESS_ATTACH:
761     GC_init();  /* Force initialization before thread attach.   */
762     /* fall through */
763   case DLL_THREAD_ATTACH:
764     GC_ASSERT(GC_thr_initialized);
765     if (GC_main_thread != GetCurrentThreadId()) {
766         GC_new_thread();
767     } /* o.w. we already did it during GC_thr_init(), called by GC_init() */
768     break;
769
770   case DLL_THREAD_DETACH:
771     GC_delete_thread(GetCurrentThreadId());
772     break;
773
774   case DLL_PROCESS_DETACH:
775     {
776       int i;
777
778       LOCK();
779       for (i = 0; i <= GC_get_max_thread_index(); ++i)
780       {
781           if (thread_table[i].in_use)
782             GC_delete_gc_thread(thread_table + i);
783       }
784       UNLOCK();
785
786       GC_deinit();
787       DeleteCriticalSection(&GC_allocate_ml);
788     }
789     break;
790
791   }
792   return TRUE;
793 }
794 #endif /* GC_DLL */
795 #endif /* !CYGWIN32 */
796
797 # endif /* !MSWINCE */
798
799 #endif /* GC_WIN32_THREADS */