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