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