win32_threads.c 23 KB

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