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