pthread_stop_world.c 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316
  1. /*
  2. * Copyright (c) 1994 by Xerox Corporation. All rights reserved.
  3. * Copyright (c) 1996 by Silicon Graphics. All rights reserved.
  4. * Copyright (c) 1998 by Fergus Henderson. All rights reserved.
  5. * Copyright (c) 2000-2009 by Hewlett-Packard Development Company.
  6. * All rights reserved.
  7. *
  8. * THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED
  9. * OR IMPLIED. ANY USE IS AT YOUR OWN RISK.
  10. *
  11. * Permission is hereby granted to use or copy this program
  12. * for any purpose, provided the above notices are retained on all copies.
  13. * Permission to modify the code and to distribute modified code is granted,
  14. * provided the above notices are retained, and a notice that the code was
  15. * modified is included with the above copyright notice.
  16. */
  17. #include "private/pthread_support.h"
  18. #if defined(GC_PTHREADS) && !defined(GC_WIN32_THREADS) && \
  19. !defined(GC_DARWIN_THREADS) && !defined(SN_TARGET_ORBIS) \
  20. && !defined(SN_TARGET_PSP2)
  21. #ifdef NACL
  22. # include <unistd.h>
  23. # include <sys/time.h>
  24. STATIC int GC_nacl_num_gc_threads = 0;
  25. STATIC __thread int GC_nacl_thread_idx = -1;
  26. STATIC volatile int GC_nacl_park_threads_now = 0;
  27. STATIC volatile pthread_t GC_nacl_thread_parker = -1;
  28. GC_INNER __thread GC_thread GC_nacl_gc_thread_self = NULL;
  29. volatile int GC_nacl_thread_parked[MAX_NACL_GC_THREADS];
  30. int GC_nacl_thread_used[MAX_NACL_GC_THREADS];
  31. #elif defined(GC_OPENBSD_UTHREADS)
  32. # include <pthread_np.h>
  33. #else /* !GC_OPENBSD_UTHREADS && !NACL */
  34. #include <signal.h>
  35. #include <semaphore.h>
  36. #include <errno.h>
  37. #include <time.h> /* for nanosleep() */
  38. #include <unistd.h>
  39. #if (!defined(AO_HAVE_load_acquire) || !defined(AO_HAVE_store_release)) \
  40. && !defined(CPPCHECK)
  41. # error AO_load_acquire and/or AO_store_release are missing;
  42. # error please define AO_REQUIRE_CAS manually
  43. #endif
  44. /* It's safe to call original pthread_sigmask() here. */
  45. #undef pthread_sigmask
  46. #ifdef GC_ENABLE_SUSPEND_THREAD
  47. static void *GC_CALLBACK suspend_self_inner(void *client_data);
  48. #endif
  49. #ifdef DEBUG_THREADS
  50. # ifndef NSIG
  51. # if defined(MAXSIG)
  52. # define NSIG (MAXSIG+1)
  53. # elif defined(_NSIG)
  54. # define NSIG _NSIG
  55. # elif defined(__SIGRTMAX)
  56. # define NSIG (__SIGRTMAX+1)
  57. # else
  58. # error define NSIG
  59. # endif
  60. # endif /* NSIG */
  61. void GC_print_sig_mask(void)
  62. {
  63. sigset_t blocked;
  64. int i;
  65. if (pthread_sigmask(SIG_BLOCK, NULL, &blocked) != 0)
  66. ABORT("pthread_sigmask failed");
  67. for (i = 1; i < NSIG; i++) {
  68. if (sigismember(&blocked, i))
  69. GC_printf("Signal blocked: %d\n", i);
  70. }
  71. }
  72. #endif /* DEBUG_THREADS */
  73. /* Remove the signals that we want to allow in thread stopping */
  74. /* handler from a set. */
  75. STATIC void GC_remove_allowed_signals(sigset_t *set)
  76. {
  77. if (sigdelset(set, SIGINT) != 0
  78. || sigdelset(set, SIGQUIT) != 0
  79. || sigdelset(set, SIGABRT) != 0
  80. || sigdelset(set, SIGTERM) != 0) {
  81. ABORT("sigdelset failed");
  82. }
  83. # ifdef MPROTECT_VDB
  84. /* Handlers write to the thread structure, which is in the heap, */
  85. /* and hence can trigger a protection fault. */
  86. if (sigdelset(set, SIGSEGV) != 0
  87. # ifdef HAVE_SIGBUS
  88. || sigdelset(set, SIGBUS) != 0
  89. # endif
  90. ) {
  91. ABORT("sigdelset failed");
  92. }
  93. # endif
  94. }
  95. static sigset_t suspend_handler_mask;
  96. STATIC volatile AO_t GC_stop_count = 0;
  97. /* Incremented by two at the beginning of */
  98. /* GC_stop_world (the lowest bit is always 0). */
  99. STATIC volatile AO_t GC_world_is_stopped = FALSE;
  100. /* FALSE ==> it is safe for threads to restart, */
  101. /* i.e. they will see another suspend signal */
  102. /* before they are expected to stop (unless */
  103. /* they have stopped voluntarily). */
  104. #if defined(GC_OSF1_THREADS) || defined(THREAD_SANITIZER) \
  105. || defined(ADDRESS_SANITIZER) || defined(MEMORY_SANITIZER)
  106. STATIC GC_bool GC_retry_signals = TRUE;
  107. #else
  108. // Unity: Always enable retry signals, since any platform could lose signals
  109. STATIC GC_bool GC_retry_signals = TRUE;
  110. #endif
  111. #define UNITY_RETRY_SIGNALS
  112. /*
  113. * We use signals to stop threads during GC.
  114. *
  115. * Suspended threads wait in signal handler for SIG_THR_RESTART.
  116. * That's more portable than semaphores or condition variables.
  117. * (We do use sem_post from a signal handler, but that should be portable.)
  118. *
  119. * The thread suspension signal SIG_SUSPEND is now defined in gc_priv.h.
  120. * Note that we can't just stop a thread; we need it to save its stack
  121. * pointer(s) and acknowledge.
  122. */
  123. #ifndef SIG_THR_RESTART
  124. # if defined(GC_HPUX_THREADS) || defined(GC_OSF1_THREADS) \
  125. || defined(GC_NETBSD_THREADS) || defined(GC_USESIGRT_SIGNALS)
  126. # if defined(_SIGRTMIN) && !defined(CPPCHECK)
  127. # define SIG_THR_RESTART _SIGRTMIN + 5
  128. # else
  129. # define SIG_THR_RESTART SIGRTMIN + 5
  130. # endif
  131. # else
  132. # define SIG_THR_RESTART SIGXCPU
  133. # endif
  134. #endif
  135. #define SIGNAL_UNSET (-1)
  136. /* Since SIG_SUSPEND and/or SIG_THR_RESTART could represent */
  137. /* a non-constant expression (e.g., in case of SIGRTMIN), */
  138. /* actual signal numbers are determined by GC_stop_init() */
  139. /* unless manually set (before GC initialization). */
  140. STATIC int GC_sig_suspend = SIGNAL_UNSET;
  141. STATIC int GC_sig_thr_restart = SIGNAL_UNSET;
  142. GC_API void GC_CALL GC_set_suspend_signal(int sig)
  143. {
  144. if (GC_is_initialized) return;
  145. GC_sig_suspend = sig;
  146. }
  147. GC_API void GC_CALL GC_set_thr_restart_signal(int sig)
  148. {
  149. if (GC_is_initialized) return;
  150. GC_sig_thr_restart = sig;
  151. }
  152. GC_API int GC_CALL GC_get_suspend_signal(void)
  153. {
  154. return GC_sig_suspend != SIGNAL_UNSET ? GC_sig_suspend : SIG_SUSPEND;
  155. }
  156. GC_API int GC_CALL GC_get_thr_restart_signal(void)
  157. {
  158. return GC_sig_thr_restart != SIGNAL_UNSET
  159. ? GC_sig_thr_restart : SIG_THR_RESTART;
  160. }
  161. #if defined(GC_EXPLICIT_SIGNALS_UNBLOCK) \
  162. || !defined(NO_SIGNALS_UNBLOCK_IN_MAIN)
  163. /* Some targets (e.g., Solaris) might require this to be called when */
  164. /* doing thread registering from the thread destructor. */
  165. GC_INNER void GC_unblock_gc_signals(void)
  166. {
  167. sigset_t set;
  168. sigemptyset(&set);
  169. GC_ASSERT(GC_sig_suspend != SIGNAL_UNSET);
  170. GC_ASSERT(GC_sig_thr_restart != SIGNAL_UNSET);
  171. sigaddset(&set, GC_sig_suspend);
  172. sigaddset(&set, GC_sig_thr_restart);
  173. if (pthread_sigmask(SIG_UNBLOCK, &set, NULL) != 0)
  174. ABORT("pthread_sigmask failed");
  175. }
  176. #endif /* GC_EXPLICIT_SIGNALS_UNBLOCK */
  177. STATIC sem_t GC_suspend_ack_sem; /* also used to acknowledge restart */
  178. STATIC void GC_suspend_handler_inner(ptr_t dummy, void *context);
  179. #ifndef NO_SA_SIGACTION
  180. STATIC void GC_suspend_handler(int sig, siginfo_t * info GC_ATTR_UNUSED,
  181. void * context GC_ATTR_UNUSED)
  182. #else
  183. STATIC void GC_suspend_handler(int sig)
  184. #endif
  185. {
  186. int old_errno = errno;
  187. if (sig != GC_sig_suspend) {
  188. # if defined(GC_FREEBSD_THREADS)
  189. /* Workaround "deferred signal handling" bug in FreeBSD 9.2. */
  190. if (0 == sig) return;
  191. # endif
  192. ABORT("Bad signal in suspend_handler");
  193. }
  194. # if defined(IA64) || defined(HP_PA) || defined(M68K)
  195. GC_with_callee_saves_pushed(GC_suspend_handler_inner, NULL);
  196. # else
  197. /* We believe that in all other cases the full context is already */
  198. /* in the signal handler frame. */
  199. {
  200. # ifdef NO_SA_SIGACTION
  201. void *context = 0;
  202. # endif
  203. GC_suspend_handler_inner(NULL, context);
  204. }
  205. # endif
  206. errno = old_errno;
  207. }
  208. /* The lookup here is safe, since this is done on behalf */
  209. /* of a thread which holds the allocation lock in order */
  210. /* to stop the world. Thus concurrent modification of the */
  211. /* data structure is impossible. Unfortunately, we have to */
  212. /* instruct TSan that the lookup is safe. */
  213. #ifdef THREAD_SANITIZER
  214. /* The implementation of the function is the same as that of */
  215. /* GC_lookup_thread except for the attribute added here. */
  216. GC_ATTR_NO_SANITIZE_THREAD
  217. static GC_thread GC_lookup_thread_async(pthread_t id)
  218. {
  219. GC_thread p = GC_threads[THREAD_TABLE_INDEX(id)];
  220. while (p != NULL && !THREAD_EQUAL(p->id, id))
  221. p = p->next;
  222. return p;
  223. }
  224. #else
  225. # define GC_lookup_thread_async GC_lookup_thread
  226. #endif
  227. GC_INLINE void GC_store_stack_ptr(GC_thread me)
  228. {
  229. /* There is no data race between the suspend handler (storing */
  230. /* stack_ptr) and GC_push_all_stacks (fetching stack_ptr) because */
  231. /* GC_push_all_stacks is executed after GC_stop_world exits and the */
  232. /* latter runs sem_wait repeatedly waiting for all the suspended */
  233. /* threads to call sem_post. Nonetheless, stack_ptr is stored (here) */
  234. /* and fetched (by GC_push_all_stacks) using the atomic primitives to */
  235. /* avoid the related TSan warning. */
  236. # ifdef SPARC
  237. AO_store((volatile AO_t *)&me->stop_info.stack_ptr,
  238. (AO_t)GC_save_regs_in_stack());
  239. # else
  240. # ifdef IA64
  241. me -> backing_store_ptr = GC_save_regs_in_stack();
  242. # endif
  243. AO_store((volatile AO_t *)&me->stop_info.stack_ptr, (AO_t)GC_approx_sp());
  244. # endif
  245. }
  246. STATIC void GC_suspend_handler_inner(ptr_t dummy GC_ATTR_UNUSED,
  247. void * context GC_ATTR_UNUSED)
  248. {
  249. pthread_t self = pthread_self();
  250. GC_thread me;
  251. IF_CANCEL(int cancel_state;)
  252. AO_t my_stop_count = AO_load_acquire(&GC_stop_count);
  253. /* After the barrier, this thread should see */
  254. /* the actual content of GC_threads. */
  255. DISABLE_CANCEL(cancel_state);
  256. /* pthread_setcancelstate is not defined to be async-signal-safe. */
  257. /* But the glibc version appears to be in the absence of */
  258. /* asynchronous cancellation. And since this signal handler */
  259. /* to block on sigsuspend, which is both async-signal-safe */
  260. /* and a cancellation point, there seems to be no obvious way */
  261. /* out of it. In fact, it looks to me like an async-signal-safe */
  262. /* cancellation point is inherently a problem, unless there is */
  263. /* some way to disable cancellation in the handler. */
  264. # ifdef DEBUG_THREADS
  265. GC_log_printf("Suspending %p\n", (void *)self);
  266. # endif
  267. GC_ASSERT(((word)my_stop_count & 1) == 0);
  268. me = GC_lookup_thread_async(self);
  269. # ifdef GC_ENABLE_SUSPEND_THREAD
  270. if (AO_load(&me->suspended_ext)) {
  271. GC_store_stack_ptr(me);
  272. sem_post(&GC_suspend_ack_sem);
  273. suspend_self_inner(me);
  274. # ifdef DEBUG_THREADS
  275. GC_log_printf("Continuing %p on GC_resume_thread\n", (void *)self);
  276. # endif
  277. RESTORE_CANCEL(cancel_state);
  278. return;
  279. }
  280. # endif
  281. if (((word)me->stop_info.last_stop_count & ~(word)0x1)
  282. == (word)my_stop_count) {
  283. /* Duplicate signal. OK if we are retrying. */
  284. if (!GC_retry_signals) {
  285. WARN("Duplicate suspend signal in thread %p\n", self);
  286. }
  287. RESTORE_CANCEL(cancel_state);
  288. return;
  289. }
  290. GC_store_stack_ptr(me);
  291. # ifdef THREAD_SANITIZER
  292. /* TSan disables signals around signal handlers. Without */
  293. /* a pthread_sigmask call, sigsuspend may block forever. */
  294. {
  295. sigset_t set;
  296. sigemptyset(&set);
  297. GC_ASSERT(GC_sig_suspend != SIGNAL_UNSET);
  298. GC_ASSERT(GC_sig_thr_restart != SIGNAL_UNSET);
  299. sigaddset(&set, GC_sig_suspend);
  300. sigaddset(&set, GC_sig_thr_restart);
  301. if (pthread_sigmask(SIG_UNBLOCK, &set, NULL) != 0)
  302. ABORT("pthread_sigmask failed in suspend handler");
  303. }
  304. # endif
  305. /* Tell the thread that wants to stop the world that this */
  306. /* thread has been stopped. Note that sem_post() is */
  307. /* the only async-signal-safe primitive in LinuxThreads. */
  308. sem_post(&GC_suspend_ack_sem);
  309. AO_store_release(&me->stop_info.last_stop_count, my_stop_count);
  310. /* Wait until that thread tells us to restart by sending */
  311. /* this thread a GC_sig_thr_restart signal (should be masked */
  312. /* at this point thus there is no race). */
  313. /* We do not continue until we receive that signal, */
  314. /* but we do not take that as authoritative. (We may be */
  315. /* accidentally restarted by one of the user signals we */
  316. /* don't block.) After we receive the signal, we use a */
  317. /* primitive and expensive mechanism to wait until it's */
  318. /* really safe to proceed. Under normal circumstances, */
  319. /* this code should not be executed. */
  320. do {
  321. sigsuspend (&suspend_handler_mask);
  322. } while (AO_load_acquire(&GC_world_is_stopped)
  323. && AO_load(&GC_stop_count) == my_stop_count);
  324. # ifdef DEBUG_THREADS
  325. GC_log_printf("Continuing %p\n", (void *)self);
  326. # endif
  327. # ifndef GC_NETBSD_THREADS_WORKAROUND
  328. if (GC_retry_signals)
  329. # endif
  330. {
  331. /* If the RESTART signal loss is possible (though it should be */
  332. /* less likely than losing the SUSPEND signal as we do not do */
  333. /* much between the first sem_post and sigsuspend calls), more */
  334. /* handshaking is provided to work around it. */
  335. sem_post(&GC_suspend_ack_sem);
  336. # ifdef GC_NETBSD_THREADS_WORKAROUND
  337. if (GC_retry_signals)
  338. # endif
  339. {
  340. /* Set the flag (the lowest bit of last_stop_count) that the */
  341. /* thread has been restarted. */
  342. AO_store_release(&me->stop_info.last_stop_count,
  343. (AO_t)((word)my_stop_count | 1));
  344. }
  345. }
  346. RESTORE_CANCEL(cancel_state);
  347. }
  348. static void suspend_restart_barrier(int n_live_threads)
  349. {
  350. int i;
  351. for (i = 0; i < n_live_threads; i++) {
  352. while (0 != sem_wait(&GC_suspend_ack_sem)) {
  353. /* On Linux, sem_wait is documented to always return zero. */
  354. /* But the documentation appears to be incorrect. */
  355. /* EINTR seems to happen with some versions of gdb. */
  356. if (errno != EINTR)
  357. ABORT("sem_wait failed");
  358. }
  359. }
  360. # ifdef GC_ASSERTIONS
  361. sem_getvalue(&GC_suspend_ack_sem, &i);
  362. GC_ASSERT(0 == i);
  363. # endif
  364. }
  365. static int resend_lost_signals(int n_live_threads,
  366. int (*suspend_restart_all)(void))
  367. {
  368. # define WAIT_UNIT 3000
  369. # define RETRY_INTERVAL 100000
  370. if (n_live_threads > 0) {
  371. unsigned long wait_usecs = 0; /* Total wait since retry. */
  372. for (;;) {
  373. int ack_count;
  374. sem_getvalue(&GC_suspend_ack_sem, &ack_count);
  375. if (ack_count == n_live_threads)
  376. break;
  377. if (wait_usecs > RETRY_INTERVAL) {
  378. int newly_sent = suspend_restart_all();
  379. GC_COND_LOG_PRINTF("Resent %d signals after timeout\n", newly_sent);
  380. sem_getvalue(&GC_suspend_ack_sem, &ack_count);
  381. if (newly_sent < n_live_threads - ack_count) {
  382. WARN("Lost some threads while stopping or starting world?!\n", 0);
  383. n_live_threads = ack_count + newly_sent;
  384. }
  385. wait_usecs = 0;
  386. }
  387. # ifdef LINT2
  388. /* Workaround "waiting while holding a lock" warning. */
  389. # undef WAIT_UNIT
  390. # define WAIT_UNIT 1
  391. sched_yield();
  392. # elif defined(CPPCHECK) /* || _POSIX_C_SOURCE >= 199309L */
  393. {
  394. struct timespec ts;
  395. ts.tv_sec = 0;
  396. ts.tv_nsec = WAIT_UNIT * 1000;
  397. (void)nanosleep(&ts, NULL);
  398. }
  399. # else
  400. usleep(WAIT_UNIT);
  401. # endif
  402. wait_usecs += WAIT_UNIT;
  403. }
  404. }
  405. return n_live_threads;
  406. }
  407. #ifdef UNITY_RETRY_SIGNALS
  408. static void suspend_restart_barrier_retry(int n_live_threads,
  409. int (*suspend_restart_all)(void))
  410. {
  411. # define TIMEOUT_UNIT 10000
  412. int i;
  413. int acked_threads = 0;
  414. struct timespec ts;
  415. if (clock_gettime(CLOCK_REALTIME, &ts) == -1) {
  416. n_live_threads = resend_lost_signals(n_live_threads, suspend_restart_all);
  417. suspend_restart_barrier(n_live_threads);
  418. return;
  419. }
  420. ts.tv_nsec += TIMEOUT_UNIT * 1000;
  421. for (i = 0; i < n_live_threads; i++) {
  422. while (0 != sem_timedwait(&GC_suspend_ack_sem, &ts)) {
  423. /* On Linux, sem_wait is documented to always return zero. */
  424. /* But the documentation appears to be incorrect. */
  425. /* EINTR seems to happen with some versions of gdb. */
  426. if (errno == ETIMEDOUT || errno == EINVAL) {
  427. // Wait timed out or the timeout period has passed
  428. n_live_threads = resend_lost_signals(n_live_threads - acked_threads, suspend_restart_all);
  429. suspend_restart_barrier(n_live_threads);
  430. return;
  431. }
  432. else if (errno != EINTR) {
  433. ABORT("sem_wait failed");
  434. }
  435. }
  436. acked_threads++;
  437. }
  438. # ifdef GC_ASSERTIONS
  439. sem_getvalue(&GC_suspend_ack_sem, &i);
  440. GC_ASSERT(0 == i);
  441. # endif
  442. }
  443. #endif
  444. STATIC void GC_restart_handler(int sig)
  445. {
  446. # if defined(DEBUG_THREADS)
  447. int old_errno = errno; /* Preserve errno value. */
  448. # endif
  449. if (sig != GC_sig_thr_restart)
  450. ABORT("Bad signal in restart handler");
  451. /*
  452. ** Note: even if we don't do anything useful here,
  453. ** it would still be necessary to have a signal handler,
  454. ** rather than ignoring the signals, otherwise
  455. ** the signals will not be delivered at all, and
  456. ** will thus not interrupt the sigsuspend() above.
  457. */
  458. # ifdef DEBUG_THREADS
  459. GC_log_printf("In GC_restart_handler for %p\n", (void *)pthread_self());
  460. errno = old_errno;
  461. # endif
  462. }
  463. # ifdef USE_TKILL_ON_ANDROID
  464. EXTERN_C_BEGIN
  465. extern int tkill(pid_t tid, int sig); /* from sys/linux-unistd.h */
  466. EXTERN_C_END
  467. static int android_thread_kill(pid_t tid, int sig)
  468. {
  469. int ret;
  470. int old_errno = errno;
  471. ret = tkill(tid, sig);
  472. if (ret < 0) {
  473. ret = errno;
  474. errno = old_errno;
  475. }
  476. return ret;
  477. }
  478. # define THREAD_SYSTEM_ID(t) (t)->kernel_id
  479. # define RAISE_SIGNAL(t, sig) android_thread_kill(THREAD_SYSTEM_ID(t), sig)
  480. # else
  481. # define THREAD_SYSTEM_ID(t) (t)->id
  482. # define RAISE_SIGNAL(t, sig) pthread_kill(THREAD_SYSTEM_ID(t), sig)
  483. # endif /* !USE_TKILL_ON_ANDROID */
  484. # ifdef GC_ENABLE_SUSPEND_THREAD
  485. # include <sys/time.h>
  486. # include "javaxfc.h" /* to get the prototypes as extern "C" */
  487. STATIC void GC_brief_async_signal_safe_sleep(void)
  488. {
  489. struct timeval tv;
  490. tv.tv_sec = 0;
  491. # if defined(GC_TIME_LIMIT) && !defined(CPPCHECK)
  492. tv.tv_usec = 1000 * GC_TIME_LIMIT / 2;
  493. # else
  494. tv.tv_usec = 1000 * 50 / 2;
  495. # endif
  496. (void)select(0, 0, 0, 0, &tv);
  497. }
  498. static void *GC_CALLBACK suspend_self_inner(void *client_data) {
  499. GC_thread me = (GC_thread)client_data;
  500. while (AO_load_acquire(&me->suspended_ext)) {
  501. /* TODO: Use sigsuspend() instead. */
  502. GC_brief_async_signal_safe_sleep();
  503. }
  504. return NULL;
  505. }
  506. GC_API void GC_CALL GC_suspend_thread(GC_SUSPEND_THREAD_ID thread) {
  507. GC_thread t;
  508. IF_CANCEL(int cancel_state;)
  509. DCL_LOCK_STATE;
  510. LOCK();
  511. t = GC_lookup_thread((pthread_t)thread);
  512. if (t == NULL || t -> suspended_ext) {
  513. UNLOCK();
  514. return;
  515. }
  516. /* Set the flag making the change visible to the signal handler. */
  517. /* This also removes the protection for t object, preventing */
  518. /* write faults in GC_store_stack_ptr (thus double-locking should */
  519. /* not occur in async_set_pht_entry_from_index). */
  520. AO_store_release(&t->suspended_ext, TRUE);
  521. if (THREAD_EQUAL((pthread_t)thread, pthread_self())) {
  522. UNLOCK();
  523. /* It is safe as "t" cannot become invalid here (no race with */
  524. /* GC_unregister_my_thread). */
  525. (void)GC_do_blocking(suspend_self_inner, t);
  526. return;
  527. }
  528. if ((t -> flags & FINISHED) != 0) {
  529. /* Terminated but not joined yet. */
  530. UNLOCK();
  531. return;
  532. }
  533. DISABLE_CANCEL(cancel_state);
  534. /* GC_suspend_thread is not a cancellation point. */
  535. # ifdef PARALLEL_MARK
  536. /* Ensure we do not suspend a thread while it is rebuilding */
  537. /* a free list, otherwise such a dead-lock is possible: */
  538. /* thread 1 is blocked in GC_wait_for_reclaim holding */
  539. /* the allocation lock, thread 2 is suspended in */
  540. /* GC_reclaim_generic invoked from GC_generic_malloc_many */
  541. /* (with GC_fl_builder_count > 0), and thread 3 is blocked */
  542. /* acquiring the allocation lock in GC_resume_thread. */
  543. if (GC_parallel)
  544. GC_wait_for_reclaim();
  545. # endif
  546. /* TODO: Support GC_retry_signals (not needed for TSan) */
  547. GC_acquire_dirty_lock();
  548. switch (RAISE_SIGNAL(t, GC_sig_suspend)) {
  549. /* ESRCH cannot happen as terminated threads are handled above. */
  550. case 0:
  551. break;
  552. default:
  553. ABORT("pthread_kill failed");
  554. }
  555. /* Wait for the thread to complete threads table lookup and */
  556. /* stack_ptr assignment. */
  557. GC_ASSERT(GC_thr_initialized);
  558. while (sem_wait(&GC_suspend_ack_sem) != 0) {
  559. if (errno != EINTR)
  560. ABORT("sem_wait for handler failed (suspend_self)");
  561. }
  562. GC_release_dirty_lock();
  563. RESTORE_CANCEL(cancel_state);
  564. UNLOCK();
  565. }
  566. GC_API void GC_CALL GC_resume_thread(GC_SUSPEND_THREAD_ID thread) {
  567. GC_thread t;
  568. DCL_LOCK_STATE;
  569. LOCK();
  570. t = GC_lookup_thread((pthread_t)thread);
  571. if (t != NULL)
  572. AO_store(&t->suspended_ext, FALSE);
  573. UNLOCK();
  574. }
  575. GC_API int GC_CALL GC_is_thread_suspended(GC_SUSPEND_THREAD_ID thread) {
  576. GC_thread t;
  577. int is_suspended = 0;
  578. DCL_LOCK_STATE;
  579. LOCK();
  580. t = GC_lookup_thread((pthread_t)thread);
  581. if (t != NULL && t -> suspended_ext)
  582. is_suspended = (int)TRUE;
  583. UNLOCK();
  584. return is_suspended;
  585. }
  586. # endif /* GC_ENABLE_SUSPEND_THREAD */
  587. #endif /* !GC_OPENBSD_UTHREADS && !NACL */
  588. #ifdef IA64
  589. # define IF_IA64(x) x
  590. #else
  591. # define IF_IA64(x)
  592. #endif
  593. /* We hold allocation lock. Should do exactly the right thing if the */
  594. /* world is stopped. Should not fail if it isn't. */
  595. GC_INNER void GC_push_all_stacks(void)
  596. {
  597. GC_bool found_me = FALSE;
  598. size_t nthreads = 0;
  599. int i;
  600. GC_thread p;
  601. ptr_t lo, hi;
  602. /* On IA64, we also need to scan the register backing store. */
  603. IF_IA64(ptr_t bs_lo; ptr_t bs_hi;)
  604. struct GC_traced_stack_sect_s *traced_stack_sect;
  605. pthread_t self = pthread_self();
  606. word total_size = 0;
  607. if (!EXPECT(GC_thr_initialized, TRUE))
  608. GC_thr_init();
  609. # ifdef DEBUG_THREADS
  610. GC_log_printf("Pushing stacks from thread %p\n", (void *)self);
  611. # endif
  612. for (i = 0; i < THREAD_TABLE_SZ; i++) {
  613. for (p = GC_threads[i]; p != 0; p = p -> next) {
  614. if (p -> flags & FINISHED) continue;
  615. ++nthreads;
  616. traced_stack_sect = p -> traced_stack_sect;
  617. if (THREAD_EQUAL(p -> id, self)) {
  618. GC_ASSERT(!p->thread_blocked);
  619. # ifdef SPARC
  620. lo = (ptr_t)GC_save_regs_in_stack();
  621. # else
  622. lo = GC_approx_sp();
  623. # endif
  624. found_me = TRUE;
  625. IF_IA64(bs_hi = (ptr_t)GC_save_regs_in_stack();)
  626. } else {
  627. lo = (ptr_t)AO_load((volatile AO_t *)&p->stop_info.stack_ptr);
  628. IF_IA64(bs_hi = p -> backing_store_ptr;)
  629. if (traced_stack_sect != NULL
  630. && traced_stack_sect->saved_stack_ptr == lo) {
  631. /* If the thread has never been stopped since the recent */
  632. /* GC_call_with_gc_active invocation then skip the top */
  633. /* "stack section" as stack_ptr already points to. */
  634. traced_stack_sect = traced_stack_sect->prev;
  635. }
  636. }
  637. if ((p -> flags & MAIN_THREAD) == 0) {
  638. hi = p -> stack_end;
  639. IF_IA64(bs_lo = p -> backing_store_end);
  640. } else {
  641. /* The original stack. */
  642. hi = GC_stackbottom;
  643. IF_IA64(bs_lo = BACKING_STORE_BASE;)
  644. }
  645. # ifdef DEBUG_THREADS
  646. GC_log_printf("Stack for thread %p = [%p,%p)\n",
  647. (void *)p->id, (void *)lo, (void *)hi);
  648. # endif
  649. if (0 == lo) ABORT("GC_push_all_stacks: sp not set!");
  650. if (p->altstack != NULL && (word)p->altstack <= (word)lo
  651. && (word)lo <= (word)p->altstack + p->altstack_size) {
  652. hi = p->altstack + p->altstack_size;
  653. /* FIXME: Need to scan the normal stack too, but how ? */
  654. /* FIXME: Assume stack grows down */
  655. }
  656. GC_push_all_stack_sections(lo, hi, traced_stack_sect);
  657. # ifdef STACK_GROWS_UP
  658. total_size += lo - hi;
  659. # else
  660. total_size += hi - lo; /* lo <= hi */
  661. # endif
  662. # ifdef NACL
  663. /* Push reg_storage as roots, this will cover the reg context. */
  664. GC_push_all_stack((ptr_t)p -> stop_info.reg_storage,
  665. (ptr_t)(p -> stop_info.reg_storage + NACL_GC_REG_STORAGE_SIZE));
  666. total_size += NACL_GC_REG_STORAGE_SIZE * sizeof(ptr_t);
  667. # endif
  668. # ifdef IA64
  669. # ifdef DEBUG_THREADS
  670. GC_log_printf("Reg stack for thread %p = [%p,%p)\n",
  671. (void *)p->id, (void *)bs_lo, (void *)bs_hi);
  672. # endif
  673. /* FIXME: This (if p->id==self) may add an unbounded number of */
  674. /* entries, and hence overflow the mark stack, which is bad. */
  675. GC_push_all_register_sections(bs_lo, bs_hi,
  676. THREAD_EQUAL(p -> id, self),
  677. traced_stack_sect);
  678. total_size += bs_hi - bs_lo; /* bs_lo <= bs_hi */
  679. # endif
  680. }
  681. }
  682. GC_VERBOSE_LOG_PRINTF("Pushed %d thread stacks\n", (int)nthreads);
  683. if (!found_me && !GC_in_thread_creation)
  684. ABORT("Collecting from unknown thread");
  685. GC_total_stacksize = total_size;
  686. }
  687. #ifdef DEBUG_THREADS
  688. /* There seems to be a very rare thread stopping problem. To help us */
  689. /* debug that, we save the ids of the stopping thread. */
  690. pthread_t GC_stopping_thread;
  691. int GC_stopping_pid = 0;
  692. #endif
  693. /* We hold the allocation lock. Suspend all threads that might */
  694. /* still be running. Return the number of suspend signals that */
  695. /* were sent. */
  696. STATIC int GC_suspend_all(void)
  697. {
  698. int n_live_threads = 0;
  699. int i;
  700. # ifndef NACL
  701. GC_thread p;
  702. # ifndef GC_OPENBSD_UTHREADS
  703. int result;
  704. # endif
  705. pthread_t self = pthread_self();
  706. for (i = 0; i < THREAD_TABLE_SZ; i++) {
  707. for (p = GC_threads[i]; p != 0; p = p -> next) {
  708. if (!THREAD_EQUAL(p -> id, self)) {
  709. if ((p -> flags & FINISHED) != 0) continue;
  710. if (p -> thread_blocked) /* Will wait */ continue;
  711. # ifndef GC_OPENBSD_UTHREADS
  712. # ifdef GC_ENABLE_SUSPEND_THREAD
  713. if (p -> suspended_ext) continue;
  714. # endif
  715. if (AO_load(&p->stop_info.last_stop_count) == GC_stop_count)
  716. continue; /* matters only if GC_retry_signals */
  717. n_live_threads++;
  718. # endif
  719. # ifdef DEBUG_THREADS
  720. GC_log_printf("Sending suspend signal to %p\n", (void *)p->id);
  721. # endif
  722. # ifdef GC_OPENBSD_UTHREADS
  723. {
  724. stack_t stack;
  725. GC_acquire_dirty_lock();
  726. if (pthread_suspend_np(p -> id) != 0)
  727. ABORT("pthread_suspend_np failed");
  728. GC_release_dirty_lock();
  729. if (pthread_stackseg_np(p->id, &stack))
  730. ABORT("pthread_stackseg_np failed");
  731. p -> stop_info.stack_ptr = (ptr_t)stack.ss_sp - stack.ss_size;
  732. if (GC_on_thread_event)
  733. GC_on_thread_event(GC_EVENT_THREAD_SUSPENDED,
  734. (void *)p->id);
  735. }
  736. # else
  737. /* The synchronization between GC_dirty (based on */
  738. /* test-and-set) and the signal-based thread suspension */
  739. /* is performed in GC_stop_world because */
  740. /* GC_release_dirty_lock cannot be called before */
  741. /* acknowledging the thread is really suspended. */
  742. result = RAISE_SIGNAL(p, GC_sig_suspend);
  743. switch(result) {
  744. case ESRCH:
  745. /* Not really there anymore. Possible? */
  746. n_live_threads--;
  747. break;
  748. case 0:
  749. if (GC_on_thread_event)
  750. GC_on_thread_event(GC_EVENT_THREAD_SUSPENDED,
  751. (void *)(word)THREAD_SYSTEM_ID(p));
  752. /* Note: thread id might be truncated. */
  753. break;
  754. default:
  755. ABORT_ARG1("pthread_kill failed at suspend",
  756. ": errcode= %d", result);
  757. }
  758. # endif
  759. }
  760. }
  761. }
  762. # else /* NACL */
  763. # ifndef NACL_PARK_WAIT_NANOSECONDS
  764. # define NACL_PARK_WAIT_NANOSECONDS (100 * 1000)
  765. # endif
  766. # define NANOS_PER_SECOND (1000UL * 1000 * 1000)
  767. unsigned long num_sleeps = 0;
  768. # ifdef DEBUG_THREADS
  769. GC_log_printf("pthread_stop_world: num_threads=%d\n",
  770. GC_nacl_num_gc_threads - 1);
  771. # endif
  772. GC_nacl_thread_parker = pthread_self();
  773. GC_nacl_park_threads_now = 1;
  774. while (1) {
  775. int num_threads_parked = 0;
  776. struct timespec ts;
  777. int num_used = 0;
  778. /* Check the 'parked' flag for each thread the GC knows about. */
  779. for (i = 0; i < MAX_NACL_GC_THREADS
  780. && num_used < GC_nacl_num_gc_threads; i++) {
  781. if (GC_nacl_thread_used[i] == 1) {
  782. num_used++;
  783. if (GC_nacl_thread_parked[i] == 1) {
  784. num_threads_parked++;
  785. if (GC_on_thread_event)
  786. GC_on_thread_event(GC_EVENT_THREAD_SUSPENDED, (void *)(word)i);
  787. }
  788. }
  789. }
  790. /* -1 for the current thread. */
  791. if (num_threads_parked >= GC_nacl_num_gc_threads - 1)
  792. break;
  793. ts.tv_sec = 0;
  794. ts.tv_nsec = NACL_PARK_WAIT_NANOSECONDS;
  795. # ifdef DEBUG_THREADS
  796. GC_log_printf("Sleep waiting for %d threads to park...\n",
  797. GC_nacl_num_gc_threads - num_threads_parked - 1);
  798. # endif
  799. /* This requires _POSIX_TIMERS feature. */
  800. nanosleep(&ts, 0);
  801. if (++num_sleeps > NANOS_PER_SECOND / NACL_PARK_WAIT_NANOSECONDS) {
  802. WARN("GC appears stalled waiting for %" WARN_PRIdPTR
  803. " threads to park...\n",
  804. GC_nacl_num_gc_threads - num_threads_parked - 1);
  805. num_sleeps = 0;
  806. }
  807. }
  808. # endif /* NACL */
  809. return n_live_threads;
  810. }
  811. GC_INNER void GC_stop_world(void)
  812. {
  813. # if !defined(GC_OPENBSD_UTHREADS) && !defined(NACL)
  814. int n_live_threads;
  815. # endif
  816. GC_ASSERT(I_HOLD_LOCK());
  817. # ifdef DEBUG_THREADS
  818. GC_stopping_thread = pthread_self();
  819. GC_stopping_pid = getpid();
  820. GC_log_printf("Stopping the world from %p\n", (void *)GC_stopping_thread);
  821. # endif
  822. /* Make sure all free list construction has stopped before we start. */
  823. /* No new construction can start, since free list construction is */
  824. /* required to acquire and release the GC lock before it starts, */
  825. /* and we have the lock. */
  826. # ifdef PARALLEL_MARK
  827. if (GC_parallel) {
  828. GC_acquire_mark_lock();
  829. GC_ASSERT(GC_fl_builder_count == 0);
  830. /* We should have previously waited for it to become zero. */
  831. }
  832. # endif /* PARALLEL_MARK */
  833. # if defined(GC_OPENBSD_UTHREADS) || defined(NACL)
  834. (void)GC_suspend_all();
  835. # else
  836. AO_store(&GC_stop_count, (AO_t)((word)GC_stop_count + 2));
  837. /* Only concurrent reads are possible. */
  838. # ifdef MANUAL_VDB
  839. GC_acquire_dirty_lock();
  840. /* The write fault handler cannot be called if GC_manual_vdb */
  841. /* (thus double-locking should not occur in */
  842. /* async_set_pht_entry_from_index based on test-and-set). */
  843. # endif
  844. AO_store_release(&GC_world_is_stopped, TRUE);
  845. n_live_threads = GC_suspend_all();
  846. #ifndef UNITY_RETRY_SIGNALS
  847. if (GC_retry_signals)
  848. n_live_threads = resend_lost_signals(n_live_threads, GC_suspend_all);
  849. suspend_restart_barrier(n_live_threads);
  850. #else
  851. if (GC_retry_signals)
  852. suspend_restart_barrier_retry(n_live_threads, GC_suspend_all);
  853. else
  854. suspend_restart_barrier(n_live_threads);
  855. #endif
  856. # ifdef MANUAL_VDB
  857. GC_release_dirty_lock(); /* cannot be done in GC_suspend_all */
  858. # endif
  859. # endif
  860. # ifdef PARALLEL_MARK
  861. if (GC_parallel)
  862. GC_release_mark_lock();
  863. # endif
  864. # ifdef DEBUG_THREADS
  865. GC_log_printf("World stopped from %p\n", (void *)pthread_self());
  866. GC_stopping_thread = 0;
  867. # endif
  868. }
  869. #ifdef NACL
  870. # if defined(__x86_64__)
  871. # define NACL_STORE_REGS() \
  872. do { \
  873. __asm__ __volatile__ ("push %rbx"); \
  874. __asm__ __volatile__ ("push %rbp"); \
  875. __asm__ __volatile__ ("push %r12"); \
  876. __asm__ __volatile__ ("push %r13"); \
  877. __asm__ __volatile__ ("push %r14"); \
  878. __asm__ __volatile__ ("push %r15"); \
  879. __asm__ __volatile__ ("mov %%esp, %0" \
  880. : "=m" (GC_nacl_gc_thread_self->stop_info.stack_ptr)); \
  881. BCOPY(GC_nacl_gc_thread_self->stop_info.stack_ptr, \
  882. GC_nacl_gc_thread_self->stop_info.reg_storage, \
  883. NACL_GC_REG_STORAGE_SIZE * sizeof(ptr_t)); \
  884. __asm__ __volatile__ ("naclasp $48, %r15"); \
  885. } while (0)
  886. # elif defined(__i386__)
  887. # define NACL_STORE_REGS() \
  888. do { \
  889. __asm__ __volatile__ ("push %ebx"); \
  890. __asm__ __volatile__ ("push %ebp"); \
  891. __asm__ __volatile__ ("push %esi"); \
  892. __asm__ __volatile__ ("push %edi"); \
  893. __asm__ __volatile__ ("mov %%esp, %0" \
  894. : "=m" (GC_nacl_gc_thread_self->stop_info.stack_ptr)); \
  895. BCOPY(GC_nacl_gc_thread_self->stop_info.stack_ptr, \
  896. GC_nacl_gc_thread_self->stop_info.reg_storage, \
  897. NACL_GC_REG_STORAGE_SIZE * sizeof(ptr_t));\
  898. __asm__ __volatile__ ("add $16, %esp"); \
  899. } while (0)
  900. # elif defined(__arm__)
  901. # define NACL_STORE_REGS() \
  902. do { \
  903. __asm__ __volatile__ ("push {r4-r8,r10-r12,lr}"); \
  904. __asm__ __volatile__ ("mov r0, %0" \
  905. : : "r" (&GC_nacl_gc_thread_self->stop_info.stack_ptr)); \
  906. __asm__ __volatile__ ("bic r0, r0, #0xc0000000"); \
  907. __asm__ __volatile__ ("str sp, [r0]"); \
  908. BCOPY(GC_nacl_gc_thread_self->stop_info.stack_ptr, \
  909. GC_nacl_gc_thread_self->stop_info.reg_storage, \
  910. NACL_GC_REG_STORAGE_SIZE * sizeof(ptr_t)); \
  911. __asm__ __volatile__ ("add sp, sp, #40"); \
  912. __asm__ __volatile__ ("bic sp, sp, #0xc0000000"); \
  913. } while (0)
  914. # else
  915. # error TODO Please port NACL_STORE_REGS
  916. # endif
  917. GC_API_OSCALL void nacl_pre_syscall_hook(void)
  918. {
  919. if (GC_nacl_thread_idx != -1) {
  920. NACL_STORE_REGS();
  921. GC_nacl_gc_thread_self->stop_info.stack_ptr = GC_approx_sp();
  922. GC_nacl_thread_parked[GC_nacl_thread_idx] = 1;
  923. }
  924. }
  925. GC_API_OSCALL void __nacl_suspend_thread_if_needed(void)
  926. {
  927. if (GC_nacl_park_threads_now) {
  928. pthread_t self = pthread_self();
  929. /* Don't try to park the thread parker. */
  930. if (GC_nacl_thread_parker == self)
  931. return;
  932. /* This can happen when a thread is created outside of the GC */
  933. /* system (wthread mostly). */
  934. if (GC_nacl_thread_idx < 0)
  935. return;
  936. /* If it was already 'parked', we're returning from a syscall, */
  937. /* so don't bother storing registers again, the GC has a set. */
  938. if (!GC_nacl_thread_parked[GC_nacl_thread_idx]) {
  939. NACL_STORE_REGS();
  940. GC_nacl_gc_thread_self->stop_info.stack_ptr = GC_approx_sp();
  941. }
  942. GC_nacl_thread_parked[GC_nacl_thread_idx] = 1;
  943. while (GC_nacl_park_threads_now) {
  944. /* Just spin. */
  945. }
  946. GC_nacl_thread_parked[GC_nacl_thread_idx] = 0;
  947. /* Clear out the reg storage for next suspend. */
  948. BZERO(GC_nacl_gc_thread_self->stop_info.reg_storage,
  949. NACL_GC_REG_STORAGE_SIZE * sizeof(ptr_t));
  950. }
  951. }
  952. GC_API_OSCALL void nacl_post_syscall_hook(void)
  953. {
  954. /* Calling __nacl_suspend_thread_if_needed right away should */
  955. /* guarantee we don't mutate the GC set. */
  956. __nacl_suspend_thread_if_needed();
  957. if (GC_nacl_thread_idx != -1) {
  958. GC_nacl_thread_parked[GC_nacl_thread_idx] = 0;
  959. }
  960. }
  961. STATIC GC_bool GC_nacl_thread_parking_inited = FALSE;
  962. STATIC pthread_mutex_t GC_nacl_thread_alloc_lock = PTHREAD_MUTEX_INITIALIZER;
  963. struct nacl_irt_blockhook {
  964. int (*register_block_hooks)(void (*pre)(void), void (*post)(void));
  965. };
  966. EXTERN_C_BEGIN
  967. extern size_t nacl_interface_query(const char *interface_ident,
  968. void *table, size_t tablesize);
  969. EXTERN_C_END
  970. GC_INNER void GC_nacl_initialize_gc_thread(void)
  971. {
  972. int i;
  973. static struct nacl_irt_blockhook gc_hook;
  974. pthread_mutex_lock(&GC_nacl_thread_alloc_lock);
  975. if (!EXPECT(GC_nacl_thread_parking_inited, TRUE)) {
  976. BZERO(GC_nacl_thread_parked, sizeof(GC_nacl_thread_parked));
  977. BZERO(GC_nacl_thread_used, sizeof(GC_nacl_thread_used));
  978. /* TODO: replace with public 'register hook' function when */
  979. /* available from glibc. */
  980. nacl_interface_query("nacl-irt-blockhook-0.1",
  981. &gc_hook, sizeof(gc_hook));
  982. gc_hook.register_block_hooks(nacl_pre_syscall_hook,
  983. nacl_post_syscall_hook);
  984. GC_nacl_thread_parking_inited = TRUE;
  985. }
  986. GC_ASSERT(GC_nacl_num_gc_threads <= MAX_NACL_GC_THREADS);
  987. for (i = 0; i < MAX_NACL_GC_THREADS; i++) {
  988. if (GC_nacl_thread_used[i] == 0) {
  989. GC_nacl_thread_used[i] = 1;
  990. GC_nacl_thread_idx = i;
  991. GC_nacl_num_gc_threads++;
  992. break;
  993. }
  994. }
  995. pthread_mutex_unlock(&GC_nacl_thread_alloc_lock);
  996. }
  997. GC_INNER void GC_nacl_shutdown_gc_thread(void)
  998. {
  999. pthread_mutex_lock(&GC_nacl_thread_alloc_lock);
  1000. GC_ASSERT(GC_nacl_thread_idx >= 0);
  1001. GC_ASSERT(GC_nacl_thread_idx < MAX_NACL_GC_THREADS);
  1002. GC_ASSERT(GC_nacl_thread_used[GC_nacl_thread_idx] != 0);
  1003. GC_nacl_thread_used[GC_nacl_thread_idx] = 0;
  1004. GC_nacl_thread_idx = -1;
  1005. GC_nacl_num_gc_threads--;
  1006. pthread_mutex_unlock(&GC_nacl_thread_alloc_lock);
  1007. }
  1008. #else /* !NACL */
  1009. /* Restart all threads that were suspended by the collector. */
  1010. /* Return the number of restart signals that were sent. */
  1011. STATIC int GC_restart_all(void)
  1012. {
  1013. int n_live_threads = 0;
  1014. int i;
  1015. pthread_t self = pthread_self();
  1016. GC_thread p;
  1017. # ifndef GC_OPENBSD_UTHREADS
  1018. int result;
  1019. # endif
  1020. for (i = 0; i < THREAD_TABLE_SZ; i++) {
  1021. for (p = GC_threads[i]; p != NULL; p = p -> next) {
  1022. if (!THREAD_EQUAL(p -> id, self)) {
  1023. if ((p -> flags & FINISHED) != 0) continue;
  1024. if (p -> thread_blocked) continue;
  1025. # ifndef GC_OPENBSD_UTHREADS
  1026. # ifdef GC_ENABLE_SUSPEND_THREAD
  1027. if (p -> suspended_ext) continue;
  1028. # endif
  1029. if (GC_retry_signals && AO_load(&p->stop_info.last_stop_count)
  1030. == (AO_t)((word)GC_stop_count | 1))
  1031. continue; /* The thread has been restarted. */
  1032. n_live_threads++;
  1033. # endif
  1034. # ifdef DEBUG_THREADS
  1035. GC_log_printf("Sending restart signal to %p\n", (void *)p->id);
  1036. # endif
  1037. # ifdef GC_OPENBSD_UTHREADS
  1038. if (pthread_resume_np(p -> id) != 0)
  1039. ABORT("pthread_resume_np failed");
  1040. if (GC_on_thread_event)
  1041. GC_on_thread_event(GC_EVENT_THREAD_UNSUSPENDED, (void *)p->id);
  1042. # else
  1043. result = RAISE_SIGNAL(p, GC_sig_thr_restart);
  1044. switch(result) {
  1045. case ESRCH:
  1046. /* Not really there anymore. Possible? */
  1047. n_live_threads--;
  1048. break;
  1049. case 0:
  1050. if (GC_on_thread_event)
  1051. GC_on_thread_event(GC_EVENT_THREAD_UNSUSPENDED,
  1052. (void *)(word)THREAD_SYSTEM_ID(p));
  1053. break;
  1054. default:
  1055. ABORT_ARG1("pthread_kill failed at resume",
  1056. ": errcode= %d", result);
  1057. }
  1058. # endif
  1059. }
  1060. }
  1061. }
  1062. return n_live_threads;
  1063. }
  1064. #endif /* !NACL */
  1065. /* Caller holds allocation lock, and has held it continuously since */
  1066. /* the world stopped. */
  1067. GC_INNER void GC_start_world(void)
  1068. {
  1069. # ifndef NACL
  1070. int n_live_threads;
  1071. GC_ASSERT(I_HOLD_LOCK());
  1072. # ifdef DEBUG_THREADS
  1073. GC_log_printf("World starting\n");
  1074. # endif
  1075. # ifndef GC_OPENBSD_UTHREADS
  1076. AO_store_release(&GC_world_is_stopped, FALSE);
  1077. /* The updated value should now be visible to the */
  1078. /* signal handler (note that pthread_kill is not on */
  1079. /* the list of functions which synchronize memory). */
  1080. # endif
  1081. n_live_threads = GC_restart_all();
  1082. # ifndef GC_OPENBSD_UTHREADS
  1083. # ifndef UNITY_RETRY_SIGNALS
  1084. if (GC_retry_signals)
  1085. n_live_threads = resend_lost_signals(n_live_threads, GC_restart_all);
  1086. # endif
  1087. # ifdef GC_NETBSD_THREADS_WORKAROUND
  1088. suspend_restart_barrier(n_live_threads);
  1089. # else
  1090. if (GC_retry_signals)
  1091. # ifndef UNITY_RETRY_SIGNALS
  1092. suspend_restart_barrier(n_live_threads);
  1093. # else
  1094. suspend_restart_barrier_retry(n_live_threads, GC_restart_all);
  1095. # endif
  1096. # endif
  1097. # else
  1098. (void)n_live_threads;
  1099. # endif
  1100. # ifdef DEBUG_THREADS
  1101. GC_log_printf("World started\n");
  1102. # endif
  1103. # else /* NACL */
  1104. # ifdef DEBUG_THREADS
  1105. GC_log_printf("World starting...\n");
  1106. # endif
  1107. GC_nacl_park_threads_now = 0;
  1108. if (GC_on_thread_event)
  1109. GC_on_thread_event(GC_EVENT_THREAD_UNSUSPENDED, NULL);
  1110. /* TODO: Send event for every unsuspended thread. */
  1111. # endif
  1112. }
  1113. GC_INNER void GC_stop_init(void)
  1114. {
  1115. # if !defined(GC_OPENBSD_UTHREADS) && !defined(NACL)
  1116. struct sigaction act;
  1117. char *str;
  1118. if (SIGNAL_UNSET == GC_sig_suspend)
  1119. GC_sig_suspend = SIG_SUSPEND;
  1120. if (SIGNAL_UNSET == GC_sig_thr_restart)
  1121. GC_sig_thr_restart = SIG_THR_RESTART;
  1122. if (GC_sig_suspend == GC_sig_thr_restart)
  1123. ABORT("Cannot use same signal for thread suspend and resume");
  1124. if (sem_init(&GC_suspend_ack_sem, GC_SEM_INIT_PSHARED, 0) != 0)
  1125. ABORT("sem_init failed");
  1126. # ifdef SA_RESTART
  1127. act.sa_flags = SA_RESTART
  1128. # else
  1129. act.sa_flags = 0
  1130. # endif
  1131. # ifndef NO_SA_SIGACTION
  1132. | SA_SIGINFO
  1133. # endif
  1134. ;
  1135. if (sigfillset(&act.sa_mask) != 0) {
  1136. ABORT("sigfillset failed");
  1137. }
  1138. # ifdef GC_RTEMS_PTHREADS
  1139. if(sigprocmask(SIG_UNBLOCK, &act.sa_mask, NULL) != 0) {
  1140. ABORT("sigprocmask failed");
  1141. }
  1142. # endif
  1143. GC_remove_allowed_signals(&act.sa_mask);
  1144. /* GC_sig_thr_restart is set in the resulting mask. */
  1145. /* It is unmasked by the handler when necessary. */
  1146. # ifndef NO_SA_SIGACTION
  1147. act.sa_sigaction = GC_suspend_handler;
  1148. # else
  1149. act.sa_handler = GC_suspend_handler;
  1150. # endif
  1151. /* act.sa_restorer is deprecated and should not be initialized. */
  1152. if (sigaction(GC_sig_suspend, &act, NULL) != 0) {
  1153. ABORT("Cannot set SIG_SUSPEND handler");
  1154. }
  1155. # ifndef NO_SA_SIGACTION
  1156. act.sa_flags &= ~SA_SIGINFO;
  1157. # endif
  1158. act.sa_handler = GC_restart_handler;
  1159. if (sigaction(GC_sig_thr_restart, &act, NULL) != 0) {
  1160. ABORT("Cannot set SIG_THR_RESTART handler");
  1161. }
  1162. /* Initialize suspend_handler_mask (excluding GC_sig_thr_restart). */
  1163. if (sigfillset(&suspend_handler_mask) != 0) ABORT("sigfillset failed");
  1164. GC_remove_allowed_signals(&suspend_handler_mask);
  1165. if (sigdelset(&suspend_handler_mask, GC_sig_thr_restart) != 0)
  1166. ABORT("sigdelset failed");
  1167. /* Override the default value of GC_retry_signals. */
  1168. str = GETENV("GC_RETRY_SIGNALS");
  1169. if (str != NULL) {
  1170. if (*str == '0' && *(str + 1) == '\0') {
  1171. /* Do not retry if the environment variable is set to "0". */
  1172. GC_retry_signals = FALSE;
  1173. } else {
  1174. GC_retry_signals = TRUE;
  1175. }
  1176. }
  1177. if (GC_retry_signals) {
  1178. GC_COND_LOG_PRINTF(
  1179. "Will retry suspend and restart signals if necessary\n");
  1180. }
  1181. # ifndef NO_SIGNALS_UNBLOCK_IN_MAIN
  1182. /* Explicitly unblock the signals once before new threads creation. */
  1183. GC_unblock_gc_signals();
  1184. # endif
  1185. # endif /* !GC_OPENBSD_UTHREADS && !NACL */
  1186. }
  1187. #endif /* GC_PTHREADS && !GC_DARWIN_THREADS && !GC_WIN32_THREADS */