pthread.c 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375
  1. /* Linuxthreads - a simple clone()-based implementation of Posix */
  2. /* threads for Linux. */
  3. /* Copyright (C) 1996 Xavier Leroy (Xavier.Leroy@inria.fr) */
  4. /* */
  5. /* This program is free software; you can redistribute it and/or */
  6. /* modify it under the terms of the GNU Library General Public License */
  7. /* as published by the Free Software Foundation; either version 2 */
  8. /* of the License, or (at your option) any later version. */
  9. /* */
  10. /* This program is distributed in the hope that it will be useful, */
  11. /* but WITHOUT ANY WARRANTY; without even the implied warranty of */
  12. /* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
  13. /* GNU Library General Public License for more details. */
  14. /* Thread creation, initialization, and basic low-level routines */
  15. #include <errno.h>
  16. #include <stddef.h>
  17. #include <stdio.h>
  18. #include <stdlib.h>
  19. #include <string.h>
  20. #include <unistd.h>
  21. #include <fcntl.h>
  22. #include <sys/wait.h>
  23. #include <sys/resource.h>
  24. #include <sys/time.h>
  25. #include "pthread.h"
  26. #include "internals.h"
  27. #include "spinlock.h"
  28. #include "restart.h"
  29. #include "smp.h"
  30. #include <not-cancel.h>
  31. /* Sanity check. */
  32. #if !defined __SIGRTMIN || (__SIGRTMAX - __SIGRTMIN) < 3
  33. # error "This must not happen"
  34. #endif
  35. /* mods for uClibc: __libc_sigaction is not in any standard headers */
  36. extern __typeof(sigaction) __libc_sigaction;
  37. #if !(USE_TLS && HAVE___THREAD)
  38. /* These variables are used by the setup code. */
  39. extern int _errno;
  40. extern int _h_errno;
  41. /* We need the global/static resolver state here. */
  42. # include <resolv.h>
  43. # undef _res
  44. extern struct __res_state _res;
  45. #endif
  46. #ifdef USE_TLS
  47. /* We need only a few variables. */
  48. #define manager_thread __pthread_manager_threadp
  49. pthread_descr __pthread_manager_threadp attribute_hidden;
  50. #else
  51. /* Descriptor of the initial thread */
  52. struct _pthread_descr_struct __pthread_initial_thread = {
  53. .p_header.data.self = &__pthread_initial_thread,
  54. .p_nextlive = &__pthread_initial_thread,
  55. .p_prevlive = &__pthread_initial_thread,
  56. .p_tid = PTHREAD_THREADS_MAX,
  57. .p_lock = &__pthread_handles[0].h_lock,
  58. .p_start_args = PTHREAD_START_ARGS_INITIALIZER(NULL),
  59. #if !(USE_TLS && HAVE___THREAD)
  60. .p_errnop = &_errno,
  61. .p_h_errnop = &_h_errno,
  62. .p_resp = &_res,
  63. #endif
  64. .p_userstack = 1,
  65. .p_resume_count = __ATOMIC_INITIALIZER,
  66. .p_alloca_cutoff = __MAX_ALLOCA_CUTOFF
  67. };
  68. /* Descriptor of the manager thread; none of this is used but the error
  69. variables, the p_pid and p_priority fields,
  70. and the address for identification. */
  71. #define manager_thread (&__pthread_manager_thread)
  72. struct _pthread_descr_struct __pthread_manager_thread = {
  73. .p_header.data.self = &__pthread_manager_thread,
  74. .p_header.data.multiple_threads = 1,
  75. .p_lock = &__pthread_handles[1].h_lock,
  76. .p_start_args = PTHREAD_START_ARGS_INITIALIZER(__pthread_manager),
  77. #if !(USE_TLS && HAVE___THREAD)
  78. .p_errnop = &__pthread_manager_thread.p_errno,
  79. #endif
  80. .p_nr = 1,
  81. .p_resume_count = __ATOMIC_INITIALIZER,
  82. .p_alloca_cutoff = PTHREAD_STACK_MIN / 4
  83. };
  84. #endif
  85. /* Pointer to the main thread (the father of the thread manager thread) */
  86. /* Originally, this is the initial thread, but this changes after fork() */
  87. #ifdef USE_TLS
  88. pthread_descr __pthread_main_thread;
  89. #else
  90. pthread_descr __pthread_main_thread = &__pthread_initial_thread;
  91. #endif
  92. /* Limit between the stack of the initial thread (above) and the
  93. stacks of other threads (below). Aligned on a STACK_SIZE boundary. */
  94. char *__pthread_initial_thread_bos;
  95. /* File descriptor for sending requests to the thread manager. */
  96. /* Initially -1, meaning that the thread manager is not running. */
  97. int __pthread_manager_request = -1;
  98. int __pthread_multiple_threads attribute_hidden;
  99. /* Other end of the pipe for sending requests to the thread manager. */
  100. int __pthread_manager_reader;
  101. /* Limits of the thread manager stack */
  102. char *__pthread_manager_thread_bos;
  103. char *__pthread_manager_thread_tos;
  104. /* For process-wide exit() */
  105. int __pthread_exit_requested;
  106. int __pthread_exit_code;
  107. /* Maximum stack size. */
  108. size_t __pthread_max_stacksize;
  109. /* Nozero if the machine has more than one processor. */
  110. int __pthread_smp_kernel;
  111. #if !__ASSUME_REALTIME_SIGNALS
  112. /* Pointers that select new or old suspend/resume functions
  113. based on availability of rt signals. */
  114. void (*__pthread_restart)(pthread_descr) = __pthread_restart_old;
  115. void (*__pthread_suspend)(pthread_descr) = __pthread_suspend_old;
  116. int (*__pthread_timedsuspend)(pthread_descr, const struct timespec *) = __pthread_timedsuspend_old;
  117. #endif /* __ASSUME_REALTIME_SIGNALS */
  118. /* Communicate relevant LinuxThreads constants to gdb */
  119. const int __pthread_threads_max = PTHREAD_THREADS_MAX;
  120. const int __pthread_sizeof_handle = sizeof(struct pthread_handle_struct);
  121. const int __pthread_offsetof_descr = offsetof(struct pthread_handle_struct,
  122. h_descr);
  123. const int __pthread_offsetof_pid = offsetof(struct _pthread_descr_struct,
  124. p_pid);
  125. const int __linuxthreads_pthread_sizeof_descr
  126. = sizeof(struct _pthread_descr_struct);
  127. const int __linuxthreads_initial_report_events;
  128. const char __linuxthreads_version[] = VERSION;
  129. /* Forward declarations */
  130. static void pthread_onexit_process(int retcode, void *arg);
  131. #ifndef HAVE_Z_NODELETE
  132. static void pthread_atexit_process(void *arg, int retcode);
  133. static void pthread_atexit_retcode(void *arg, int retcode);
  134. #endif
  135. static void pthread_handle_sigcancel(int sig);
  136. static void pthread_handle_sigrestart(int sig);
  137. static void pthread_handle_sigdebug(int sig);
  138. /* Signal numbers used for the communication.
  139. In these variables we keep track of the used variables. If the
  140. platform does not support any real-time signals we will define the
  141. values to some unreasonable value which will signal failing of all
  142. the functions below. */
  143. int __pthread_sig_restart = __SIGRTMIN;
  144. int __pthread_sig_cancel = __SIGRTMIN + 1;
  145. int __pthread_sig_debug = __SIGRTMIN + 2;
  146. extern int __libc_current_sigrtmin_private (void);
  147. #if !__ASSUME_REALTIME_SIGNALS
  148. static int rtsigs_initialized;
  149. static void
  150. init_rtsigs (void)
  151. {
  152. if (rtsigs_initialized)
  153. return;
  154. if (__libc_current_sigrtmin_private () == -1)
  155. {
  156. __pthread_sig_restart = SIGUSR1;
  157. __pthread_sig_cancel = SIGUSR2;
  158. __pthread_sig_debug = 0;
  159. }
  160. else
  161. {
  162. __pthread_restart = __pthread_restart_new;
  163. __pthread_suspend = __pthread_wait_for_restart_signal;
  164. __pthread_timedsuspend = __pthread_timedsuspend_new;
  165. }
  166. rtsigs_initialized = 1;
  167. }
  168. #endif
  169. /* Initialize the pthread library.
  170. Initialization is split in two functions:
  171. - a constructor function that blocks the __pthread_sig_restart signal
  172. (must do this very early, since the program could capture the signal
  173. mask with e.g. sigsetjmp before creating the first thread);
  174. - a regular function called from pthread_create when needed. */
  175. static void pthread_initialize(void) __attribute__((constructor));
  176. #ifndef HAVE_Z_NODELETE
  177. extern void *__dso_handle __attribute__ ((weak));
  178. #endif
  179. #if defined USE_TLS && !defined SHARED
  180. extern void __libc_setup_tls (size_t tcbsize, size_t tcbalign);
  181. #endif
  182. struct pthread_functions __pthread_functions =
  183. {
  184. #if !(USE_TLS && HAVE___THREAD)
  185. .ptr_pthread_internal_tsd_set = __pthread_internal_tsd_set,
  186. .ptr_pthread_internal_tsd_get = __pthread_internal_tsd_get,
  187. .ptr_pthread_internal_tsd_address = __pthread_internal_tsd_address,
  188. #endif
  189. .ptr_pthread_fork = __pthread_fork,
  190. .ptr_pthread_attr_destroy = __pthread_attr_destroy,
  191. .ptr_pthread_attr_init = __pthread_attr_init,
  192. .ptr_pthread_attr_getdetachstate = __pthread_attr_getdetachstate,
  193. .ptr_pthread_attr_setdetachstate = __pthread_attr_setdetachstate,
  194. .ptr_pthread_attr_getinheritsched = __pthread_attr_getinheritsched,
  195. .ptr_pthread_attr_setinheritsched = __pthread_attr_setinheritsched,
  196. .ptr_pthread_attr_getschedparam = __pthread_attr_getschedparam,
  197. .ptr_pthread_attr_setschedparam = __pthread_attr_setschedparam,
  198. .ptr_pthread_attr_getschedpolicy = __pthread_attr_getschedpolicy,
  199. .ptr_pthread_attr_setschedpolicy = __pthread_attr_setschedpolicy,
  200. .ptr_pthread_attr_getscope = __pthread_attr_getscope,
  201. .ptr_pthread_attr_setscope = __pthread_attr_setscope,
  202. .ptr_pthread_condattr_destroy = __pthread_condattr_destroy,
  203. .ptr_pthread_condattr_init = __pthread_condattr_init,
  204. .ptr_pthread_cond_broadcast = __pthread_cond_broadcast,
  205. .ptr_pthread_cond_destroy = __pthread_cond_destroy,
  206. .ptr_pthread_cond_init = __pthread_cond_init,
  207. .ptr_pthread_cond_signal = __pthread_cond_signal,
  208. .ptr_pthread_cond_wait = __pthread_cond_wait,
  209. .ptr_pthread_cond_timedwait = __pthread_cond_timedwait,
  210. .ptr_pthread_equal = __pthread_equal,
  211. .ptr___pthread_exit = __pthread_exit,
  212. .ptr_pthread_getschedparam = __pthread_getschedparam,
  213. .ptr_pthread_setschedparam = __pthread_setschedparam,
  214. .ptr_pthread_mutex_destroy = __pthread_mutex_destroy,
  215. .ptr_pthread_mutex_init = __pthread_mutex_init,
  216. .ptr_pthread_mutex_lock = __pthread_mutex_lock,
  217. .ptr_pthread_mutex_trylock = __pthread_mutex_trylock,
  218. .ptr_pthread_mutex_unlock = __pthread_mutex_unlock,
  219. .ptr_pthread_self = __pthread_self,
  220. .ptr_pthread_setcancelstate = __pthread_setcancelstate,
  221. .ptr_pthread_setcanceltype = __pthread_setcanceltype,
  222. .ptr_pthread_do_exit = __pthread_do_exit,
  223. .ptr_pthread_thread_self = __pthread_thread_self,
  224. .ptr_pthread_cleanup_upto = __pthread_cleanup_upto,
  225. .ptr_pthread_sigaction = __pthread_sigaction,
  226. .ptr_pthread_sigwait = __pthread_sigwait,
  227. .ptr_pthread_raise = __pthread_raise,
  228. .ptr__pthread_cleanup_push = _pthread_cleanup_push,
  229. .ptr__pthread_cleanup_push_defer = _pthread_cleanup_push_defer,
  230. .ptr__pthread_cleanup_pop = _pthread_cleanup_pop,
  231. .ptr__pthread_cleanup_pop_restore = _pthread_cleanup_pop_restore,
  232. };
  233. #ifdef SHARED
  234. # define ptr_pthread_functions &__pthread_functions
  235. #else
  236. # define ptr_pthread_functions NULL
  237. #endif
  238. static int *__libc_multiple_threads_ptr;
  239. /* Do some minimal initialization which has to be done during the
  240. startup of the C library. */
  241. void
  242. __pthread_initialize_minimal(void)
  243. {
  244. #ifdef USE_TLS
  245. pthread_descr self;
  246. /* First of all init __pthread_handles[0] and [1] if needed. */
  247. # if __LT_SPINLOCK_INIT != 0
  248. __pthread_handles[0].h_lock = __LOCK_INITIALIZER;
  249. __pthread_handles[1].h_lock = __LOCK_INITIALIZER;
  250. # endif
  251. # ifndef SHARED
  252. /* Unlike in the dynamically linked case the dynamic linker has not
  253. taken care of initializing the TLS data structures. */
  254. __libc_setup_tls (TLS_TCB_SIZE, TLS_TCB_ALIGN);
  255. # elif !USE___THREAD
  256. if (__builtin_expect (GL(dl_tls_dtv_slotinfo_list) == NULL, 0))
  257. {
  258. tcbhead_t *tcbp;
  259. /* There is no actual TLS being used, so the thread register
  260. was not initialized in the dynamic linker. */
  261. /* We need to install special hooks so that the malloc and memalign
  262. calls in _dl_tls_setup and _dl_allocate_tls won't cause full
  263. malloc initialization that will try to set up its thread state. */
  264. extern void __libc_malloc_pthread_startup (bool first_time);
  265. __libc_malloc_pthread_startup (true);
  266. if (__builtin_expect (_dl_tls_setup (), 0)
  267. || __builtin_expect ((tcbp = _dl_allocate_tls (NULL)) == NULL, 0))
  268. {
  269. static const char msg[] = "\
  270. cannot allocate TLS data structures for initial thread\n";
  271. TEMP_FAILURE_RETRY (write_not_cancel (STDERR_FILENO,
  272. msg, sizeof msg - 1));
  273. abort ();
  274. }
  275. const char *lossage = TLS_INIT_TP (tcbp, 0);
  276. if (__builtin_expect (lossage != NULL, 0))
  277. {
  278. static const char msg[] = "cannot set up thread-local storage: ";
  279. const char nl = '\n';
  280. TEMP_FAILURE_RETRY (write_not_cancel (STDERR_FILENO,
  281. msg, sizeof msg - 1));
  282. TEMP_FAILURE_RETRY (write_not_cancel (STDERR_FILENO,
  283. lossage, strlen (lossage)));
  284. TEMP_FAILURE_RETRY (write_not_cancel (STDERR_FILENO, &nl, 1));
  285. }
  286. /* Though it was allocated with libc's malloc, that was done without
  287. the user's __malloc_hook installed. A later realloc that uses
  288. the hooks might not work with that block from the plain malloc.
  289. So we record this block as unfreeable just as the dynamic linker
  290. does when it allocates the DTV before the libc malloc exists. */
  291. GL(dl_initial_dtv) = GET_DTV (tcbp);
  292. __libc_malloc_pthread_startup (false);
  293. }
  294. # endif
  295. self = THREAD_SELF;
  296. /* The memory for the thread descriptor was allocated elsewhere as
  297. part of the TLS allocation. We have to initialize the data
  298. structure by hand. This initialization must mirror the struct
  299. definition above. */
  300. self->p_nextlive = self->p_prevlive = self;
  301. self->p_tid = PTHREAD_THREADS_MAX;
  302. self->p_lock = &__pthread_handles[0].h_lock;
  303. # ifndef HAVE___THREAD
  304. self->p_errnop = &_errno;
  305. self->p_h_errnop = &_h_errno;
  306. # endif
  307. /* self->p_start_args need not be initialized, it's all zero. */
  308. self->p_userstack = 1;
  309. # if __LT_SPINLOCK_INIT != 0
  310. self->p_resume_count = (struct pthread_atomic) __ATOMIC_INITIALIZER;
  311. # endif
  312. self->p_alloca_cutoff = __MAX_ALLOCA_CUTOFF;
  313. /* Another variable which points to the thread descriptor. */
  314. __pthread_main_thread = self;
  315. /* And fill in the pointer the the thread __pthread_handles array. */
  316. __pthread_handles[0].h_descr = self;
  317. #else /* USE_TLS */
  318. /* First of all init __pthread_handles[0] and [1]. */
  319. # if __LT_SPINLOCK_INIT != 0
  320. __pthread_handles[0].h_lock = __LOCK_INITIALIZER;
  321. __pthread_handles[1].h_lock = __LOCK_INITIALIZER;
  322. # endif
  323. __pthread_handles[0].h_descr = &__pthread_initial_thread;
  324. __pthread_handles[1].h_descr = &__pthread_manager_thread;
  325. /* If we have special thread_self processing, initialize that for the
  326. main thread now. */
  327. # ifdef INIT_THREAD_SELF
  328. INIT_THREAD_SELF(&__pthread_initial_thread, 0);
  329. # endif
  330. #endif
  331. #if HP_TIMING_AVAIL
  332. # ifdef USE_TLS
  333. self->p_cpuclock_offset = GL(dl_cpuclock_offset);
  334. # else
  335. __pthread_initial_thread.p_cpuclock_offset = GL(dl_cpuclock_offset);
  336. # endif
  337. #endif
  338. __libc_multiple_threads_ptr = __libc_pthread_init (ptr_pthread_functions);
  339. }
  340. void
  341. __pthread_init_max_stacksize(void)
  342. {
  343. struct rlimit limit;
  344. size_t max_stack;
  345. getrlimit(RLIMIT_STACK, &limit);
  346. #ifdef FLOATING_STACKS
  347. if (limit.rlim_cur == RLIM_INFINITY)
  348. limit.rlim_cur = ARCH_STACK_MAX_SIZE;
  349. # ifdef NEED_SEPARATE_REGISTER_STACK
  350. max_stack = limit.rlim_cur / 2;
  351. # else
  352. max_stack = limit.rlim_cur;
  353. # endif
  354. #else
  355. /* Play with the stack size limit to make sure that no stack ever grows
  356. beyond STACK_SIZE minus one page (to act as a guard page). */
  357. # ifdef NEED_SEPARATE_REGISTER_STACK
  358. /* STACK_SIZE bytes hold both the main stack and register backing
  359. store. The rlimit value applies to each individually. */
  360. max_stack = STACK_SIZE/2 - __getpagesize ();
  361. # else
  362. max_stack = STACK_SIZE - __getpagesize();
  363. # endif
  364. if (limit.rlim_cur > max_stack) {
  365. limit.rlim_cur = max_stack;
  366. setrlimit(RLIMIT_STACK, &limit);
  367. }
  368. #endif
  369. __pthread_max_stacksize = max_stack;
  370. if (max_stack / 4 < __MAX_ALLOCA_CUTOFF)
  371. {
  372. #ifdef USE_TLS
  373. pthread_descr self = THREAD_SELF;
  374. self->p_alloca_cutoff = max_stack / 4;
  375. #else
  376. __pthread_initial_thread.p_alloca_cutoff = max_stack / 4;
  377. #endif
  378. }
  379. }
  380. /* psm: we do not have any ld.so support yet
  381. * remove the USE_TLS guard if nptl is added */
  382. #if defined SHARED && defined USE_TLS
  383. # if USE___THREAD
  384. /* When using __thread for this, we do it in libc so as not
  385. to give libpthread its own TLS segment just for this. */
  386. extern void **__libc_dl_error_tsd (void) __attribute__ ((const));
  387. # else
  388. static void ** __attribute__ ((const))
  389. __libc_dl_error_tsd (void)
  390. {
  391. return &thread_self ()->p_libc_specific[_LIBC_TSD_KEY_DL_ERROR];
  392. }
  393. # endif
  394. #endif
  395. #ifdef USE_TLS
  396. static inline void __attribute__((always_inline))
  397. init_one_static_tls (pthread_descr descr, struct link_map *map)
  398. {
  399. # if TLS_TCB_AT_TP
  400. dtv_t *dtv = GET_DTV (descr);
  401. void *dest = (char *) descr - map->l_tls_offset;
  402. # elif TLS_DTV_AT_TP
  403. dtv_t *dtv = GET_DTV ((pthread_descr) ((char *) descr + TLS_PRE_TCB_SIZE));
  404. void *dest = (char *) descr + map->l_tls_offset + TLS_PRE_TCB_SIZE;
  405. # else
  406. # error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
  407. # endif
  408. /* Fill in the DTV slot so that a later LD/GD access will find it. */
  409. dtv[map->l_tls_modid].pointer.val = dest;
  410. dtv[map->l_tls_modid].pointer.is_static = true;
  411. /* Initialize the memory. */
  412. memset (__mempcpy (dest, map->l_tls_initimage, map->l_tls_initimage_size),
  413. '\0', map->l_tls_blocksize - map->l_tls_initimage_size);
  414. }
  415. static void
  416. __pthread_init_static_tls (struct link_map *map)
  417. {
  418. size_t i;
  419. for (i = 0; i < PTHREAD_THREADS_MAX; ++i)
  420. if (__pthread_handles[i].h_descr != NULL && i != 1)
  421. {
  422. __pthread_lock (&__pthread_handles[i].h_lock, NULL);
  423. if (__pthread_handles[i].h_descr != NULL)
  424. init_one_static_tls (__pthread_handles[i].h_descr, map);
  425. __pthread_unlock (&__pthread_handles[i].h_lock);
  426. }
  427. }
  428. #endif
  429. static void pthread_initialize(void)
  430. {
  431. struct sigaction sa;
  432. sigset_t mask;
  433. /* If already done (e.g. by a constructor called earlier!), bail out */
  434. if (__pthread_initial_thread_bos != NULL) return;
  435. #ifdef TEST_FOR_COMPARE_AND_SWAP
  436. /* Test if compare-and-swap is available */
  437. __pthread_has_cas = compare_and_swap_is_available();
  438. #endif
  439. #ifdef FLOATING_STACKS
  440. /* We don't need to know the bottom of the stack. Give the pointer some
  441. value to signal that initialization happened. */
  442. __pthread_initial_thread_bos = (void *) -1l;
  443. #else
  444. /* Determine stack size limits . */
  445. __pthread_init_max_stacksize ();
  446. # ifdef _STACK_GROWS_UP
  447. /* The initial thread already has all the stack it needs */
  448. __pthread_initial_thread_bos = (char *)
  449. ((long)CURRENT_STACK_FRAME &~ (STACK_SIZE - 1));
  450. # else
  451. /* For the initial stack, reserve at least STACK_SIZE bytes of stack
  452. below the current stack address, and align that on a
  453. STACK_SIZE boundary. */
  454. __pthread_initial_thread_bos =
  455. (char *)(((long)CURRENT_STACK_FRAME - 2 * STACK_SIZE) & ~(STACK_SIZE - 1));
  456. # endif
  457. #endif
  458. #ifdef USE_TLS
  459. /* Update the descriptor for the initial thread. */
  460. THREAD_SETMEM (((pthread_descr) NULL), p_pid, __getpid());
  461. # ifndef HAVE___THREAD
  462. /* Likewise for the resolver state _res. */
  463. THREAD_SETMEM (((pthread_descr) NULL), p_resp, &_res);
  464. # endif
  465. #else
  466. /* Update the descriptor for the initial thread. */
  467. __pthread_initial_thread.p_pid = __getpid();
  468. /* Likewise for the resolver state _res. */
  469. __pthread_initial_thread.p_resp = &_res;
  470. #endif
  471. #if !__ASSUME_REALTIME_SIGNALS
  472. /* Initialize real-time signals. */
  473. init_rtsigs ();
  474. #endif
  475. /* Setup signal handlers for the initial thread.
  476. Since signal handlers are shared between threads, these settings
  477. will be inherited by all other threads. */
  478. sa.sa_handler = pthread_handle_sigrestart;
  479. sigemptyset(&sa.sa_mask);
  480. sa.sa_flags = 0;
  481. __libc_sigaction(__pthread_sig_restart, &sa, NULL);
  482. sa.sa_handler = pthread_handle_sigcancel;
  483. sigaddset(&sa.sa_mask, __pthread_sig_restart);
  484. // sa.sa_flags = 0;
  485. __libc_sigaction(__pthread_sig_cancel, &sa, NULL);
  486. if (__pthread_sig_debug > 0) {
  487. sa.sa_handler = pthread_handle_sigdebug;
  488. sigemptyset(&sa.sa_mask);
  489. // sa.sa_flags = 0;
  490. __libc_sigaction(__pthread_sig_debug, &sa, NULL);
  491. }
  492. /* Initially, block __pthread_sig_restart. Will be unblocked on demand. */
  493. sigemptyset(&mask);
  494. sigaddset(&mask, __pthread_sig_restart);
  495. sigprocmask(SIG_BLOCK, &mask, NULL);
  496. /* And unblock __pthread_sig_cancel if it has been blocked. */
  497. sigdelset(&mask, __pthread_sig_restart);
  498. sigaddset(&mask, __pthread_sig_cancel);
  499. sigprocmask(SIG_UNBLOCK, &mask, NULL);
  500. /* Register an exit function to kill all other threads. */
  501. /* Do it early so that user-registered atexit functions are called
  502. before pthread_*exit_process. */
  503. #ifndef HAVE_Z_NODELETE
  504. if (__builtin_expect (&__dso_handle != NULL, 1))
  505. __cxa_atexit ((void (*) (void *)) pthread_atexit_process, NULL,
  506. __dso_handle);
  507. else
  508. #endif
  509. __on_exit (pthread_onexit_process, NULL);
  510. /* How many processors. */
  511. __pthread_smp_kernel = is_smp_system ();
  512. /* psm: we do not have any ld.so support yet
  513. * remove the USE_TLS guard if nptl is added */
  514. #if defined SHARED && defined USE_TLS
  515. /* Transfer the old value from the dynamic linker's internal location. */
  516. *__libc_dl_error_tsd () = *(*GL(dl_error_catch_tsd)) ();
  517. GL(dl_error_catch_tsd) = &__libc_dl_error_tsd;
  518. /* Make __rtld_lock_{,un}lock_recursive use pthread_mutex_{,un}lock,
  519. keep the lock count from the ld.so implementation. */
  520. GL(dl_rtld_lock_recursive) = (void *) __pthread_mutex_lock;
  521. GL(dl_rtld_unlock_recursive) = (void *) __pthread_mutex_unlock;
  522. unsigned int rtld_lock_count = GL(dl_load_lock).mutex.__m_count;
  523. GL(dl_load_lock).mutex.__m_count = 0;
  524. while (rtld_lock_count-- > 0)
  525. __pthread_mutex_lock (&GL(dl_load_lock).mutex);
  526. #endif
  527. #ifdef USE_TLS
  528. GL(dl_init_static_tls) = &__pthread_init_static_tls;
  529. #endif
  530. }
  531. void __pthread_initialize(void)
  532. {
  533. pthread_initialize();
  534. }
  535. int __pthread_initialize_manager(void)
  536. {
  537. int manager_pipe[2];
  538. int pid;
  539. struct pthread_request request;
  540. int report_events;
  541. pthread_descr mgr;
  542. #ifdef USE_TLS
  543. tcbhead_t *tcbp;
  544. #endif
  545. __pthread_multiple_threads = 1;
  546. #if TLS_MULTIPLE_THREADS_IN_TCB || !defined USE_TLS || !TLS_DTV_AT_TP
  547. __pthread_main_thread->p_multiple_threads = 1;
  548. #endif
  549. *__libc_multiple_threads_ptr = 1;
  550. #ifndef HAVE_Z_NODELETE
  551. if (__builtin_expect (&__dso_handle != NULL, 1))
  552. __cxa_atexit ((void (*) (void *)) pthread_atexit_retcode, NULL,
  553. __dso_handle);
  554. #endif
  555. if (__pthread_max_stacksize == 0)
  556. __pthread_init_max_stacksize ();
  557. /* If basic initialization not done yet (e.g. we're called from a
  558. constructor run before our constructor), do it now */
  559. if (__pthread_initial_thread_bos == NULL) pthread_initialize();
  560. /* Setup stack for thread manager */
  561. __pthread_manager_thread_bos = malloc(THREAD_MANAGER_STACK_SIZE);
  562. if (__pthread_manager_thread_bos == NULL) return -1;
  563. __pthread_manager_thread_tos =
  564. __pthread_manager_thread_bos + THREAD_MANAGER_STACK_SIZE;
  565. /* Setup pipe to communicate with thread manager */
  566. if (pipe(manager_pipe) == -1) {
  567. free(__pthread_manager_thread_bos);
  568. return -1;
  569. }
  570. #ifdef USE_TLS
  571. /* Allocate memory for the thread descriptor and the dtv. */
  572. tcbp = _dl_allocate_tls (NULL);
  573. if (tcbp == NULL) {
  574. free(__pthread_manager_thread_bos);
  575. close_not_cancel(manager_pipe[0]);
  576. close_not_cancel(manager_pipe[1]);
  577. return -1;
  578. }
  579. # if TLS_TCB_AT_TP
  580. mgr = (pthread_descr) tcbp;
  581. # elif TLS_DTV_AT_TP
  582. /* pthread_descr is located right below tcbhead_t which _dl_allocate_tls
  583. returns. */
  584. mgr = (pthread_descr) ((char *) tcbp - TLS_PRE_TCB_SIZE);
  585. # endif
  586. __pthread_handles[1].h_descr = manager_thread = mgr;
  587. /* Initialize the descriptor. */
  588. #if !defined USE_TLS || !TLS_DTV_AT_TP
  589. mgr->p_header.data.tcb = tcbp;
  590. mgr->p_header.data.self = mgr;
  591. mgr->p_header.data.multiple_threads = 1;
  592. #elif TLS_MULTIPLE_THREADS_IN_TCB
  593. mgr->p_multiple_threads = 1;
  594. #endif
  595. mgr->p_lock = &__pthread_handles[1].h_lock;
  596. # ifndef HAVE___THREAD
  597. mgr->p_errnop = &mgr->p_errno;
  598. # endif
  599. mgr->p_start_args = (struct pthread_start_args) PTHREAD_START_ARGS_INITIALIZER(__pthread_manager);
  600. mgr->p_nr = 1;
  601. # if __LT_SPINLOCK_INIT != 0
  602. self->p_resume_count = (struct pthread_atomic) __ATOMIC_INITIALIZER;
  603. # endif
  604. mgr->p_alloca_cutoff = PTHREAD_STACK_MIN / 4;
  605. #else
  606. mgr = &__pthread_manager_thread;
  607. #endif
  608. __pthread_manager_request = manager_pipe[1]; /* writing end */
  609. __pthread_manager_reader = manager_pipe[0]; /* reading end */
  610. /* Start the thread manager */
  611. pid = 0;
  612. #ifdef USE_TLS
  613. if (__linuxthreads_initial_report_events != 0)
  614. THREAD_SETMEM (((pthread_descr) NULL), p_report_events,
  615. __linuxthreads_initial_report_events);
  616. report_events = THREAD_GETMEM (((pthread_descr) NULL), p_report_events);
  617. #else
  618. if (__linuxthreads_initial_report_events != 0)
  619. __pthread_initial_thread.p_report_events
  620. = __linuxthreads_initial_report_events;
  621. report_events = __pthread_initial_thread.p_report_events;
  622. #endif
  623. if (__builtin_expect (report_events, 0))
  624. {
  625. /* It's a bit more complicated. We have to report the creation of
  626. the manager thread. */
  627. int idx = __td_eventword (TD_CREATE);
  628. uint32_t mask = __td_eventmask (TD_CREATE);
  629. uint32_t event_bits;
  630. #ifdef USE_TLS
  631. event_bits = THREAD_GETMEM_NC (((pthread_descr) NULL),
  632. p_eventbuf.eventmask.event_bits[idx]);
  633. #else
  634. event_bits = __pthread_initial_thread.p_eventbuf.eventmask.event_bits[idx];
  635. #endif
  636. if ((mask & (__pthread_threads_events.event_bits[idx] | event_bits))
  637. != 0)
  638. {
  639. __pthread_lock(mgr->p_lock, NULL);
  640. #ifdef NEED_SEPARATE_REGISTER_STACK
  641. pid = __clone2(__pthread_manager_event,
  642. (void **) __pthread_manager_thread_bos,
  643. THREAD_MANAGER_STACK_SIZE,
  644. CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND,
  645. mgr);
  646. #elif _STACK_GROWS_UP
  647. pid = __clone(__pthread_manager_event,
  648. (void **) __pthread_manager_thread_bos,
  649. CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND,
  650. mgr);
  651. #else
  652. pid = __clone(__pthread_manager_event,
  653. (void **) __pthread_manager_thread_tos,
  654. CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND,
  655. mgr);
  656. #endif
  657. if (pid != -1)
  658. {
  659. /* Now fill in the information about the new thread in
  660. the newly created thread's data structure. We cannot let
  661. the new thread do this since we don't know whether it was
  662. already scheduled when we send the event. */
  663. mgr->p_eventbuf.eventdata = mgr;
  664. mgr->p_eventbuf.eventnum = TD_CREATE;
  665. __pthread_last_event = mgr;
  666. mgr->p_tid = 2* PTHREAD_THREADS_MAX + 1;
  667. mgr->p_pid = pid;
  668. /* Now call the function which signals the event. */
  669. __linuxthreads_create_event ();
  670. }
  671. /* Now restart the thread. */
  672. __pthread_unlock(mgr->p_lock);
  673. }
  674. }
  675. if (__builtin_expect (pid, 0) == 0)
  676. {
  677. #ifdef NEED_SEPARATE_REGISTER_STACK
  678. pid = __clone2(__pthread_manager, (void **) __pthread_manager_thread_bos,
  679. THREAD_MANAGER_STACK_SIZE,
  680. CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND, mgr);
  681. #elif _STACK_GROWS_UP
  682. pid = __clone(__pthread_manager, (void **) __pthread_manager_thread_bos,
  683. CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND, mgr);
  684. #else
  685. pid = __clone(__pthread_manager, (void **) __pthread_manager_thread_tos,
  686. CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND, mgr);
  687. #endif
  688. }
  689. if (__builtin_expect (pid, 0) == -1) {
  690. #ifdef USE_TLS
  691. _dl_deallocate_tls (tcbp, true);
  692. #endif
  693. free(__pthread_manager_thread_bos);
  694. close_not_cancel(manager_pipe[0]);
  695. close_not_cancel(manager_pipe[1]);
  696. return -1;
  697. }
  698. mgr->p_tid = 2* PTHREAD_THREADS_MAX + 1;
  699. mgr->p_pid = pid;
  700. /* Make gdb aware of new thread manager */
  701. if (__builtin_expect (__pthread_threads_debug, 0) && __pthread_sig_debug > 0)
  702. {
  703. raise(__pthread_sig_debug);
  704. /* We suspend ourself and gdb will wake us up when it is
  705. ready to handle us. */
  706. __pthread_wait_for_restart_signal(thread_self());
  707. }
  708. /* Synchronize debugging of the thread manager */
  709. request.req_kind = REQ_DEBUG;
  710. TEMP_FAILURE_RETRY(write_not_cancel(__pthread_manager_request,
  711. (char *) &request, sizeof(request)));
  712. return 0;
  713. }
  714. /* Thread creation */
  715. int __pthread_create(pthread_t *thread, const pthread_attr_t *attr,
  716. void * (*start_routine)(void *), void *arg)
  717. {
  718. pthread_descr self = thread_self();
  719. struct pthread_request request;
  720. int retval;
  721. if (__builtin_expect (__pthread_manager_request, 0) < 0) {
  722. if (__pthread_initialize_manager() < 0) return EAGAIN;
  723. }
  724. request.req_thread = self;
  725. request.req_kind = REQ_CREATE;
  726. request.req_args.create.attr = attr;
  727. request.req_args.create.fn = start_routine;
  728. request.req_args.create.arg = arg;
  729. sigprocmask(SIG_SETMASK, (const sigset_t *) NULL,
  730. &request.req_args.create.mask);
  731. TEMP_FAILURE_RETRY(write_not_cancel(__pthread_manager_request,
  732. (char *) &request, sizeof(request)));
  733. suspend(self);
  734. retval = THREAD_GETMEM(self, p_retcode);
  735. if (__builtin_expect (retval, 0) == 0)
  736. *thread = (pthread_t) THREAD_GETMEM(self, p_retval);
  737. return retval;
  738. }
  739. strong_alias (__pthread_create, pthread_create)
  740. /* Simple operations on thread identifiers */
  741. pthread_descr __pthread_thread_self(void)
  742. {
  743. return thread_self();
  744. }
  745. pthread_t __pthread_self(void)
  746. {
  747. pthread_descr self = thread_self();
  748. return THREAD_GETMEM(self, p_tid);
  749. }
  750. strong_alias (__pthread_self, pthread_self)
  751. int __pthread_equal(pthread_t thread1, pthread_t thread2)
  752. {
  753. return thread1 == thread2;
  754. }
  755. strong_alias (__pthread_equal, pthread_equal)
  756. /* Helper function for thread_self in the case of user-provided stacks */
  757. #ifndef THREAD_SELF
  758. pthread_descr __pthread_find_self(void)
  759. {
  760. char * sp = CURRENT_STACK_FRAME;
  761. pthread_handle h;
  762. /* __pthread_handles[0] is the initial thread, __pthread_handles[1] is
  763. the manager threads handled specially in thread_self(), so start at 2 */
  764. h = __pthread_handles + 2;
  765. # ifdef _STACK_GROWS_UP
  766. while (! (sp >= (char *) h->h_descr && sp < (char *) h->h_descr->p_guardaddr)) h++;
  767. # else
  768. while (! (sp <= (char *) h->h_descr && sp >= h->h_bottom)) h++;
  769. # endif
  770. return h->h_descr;
  771. }
  772. #else
  773. pthread_descr __pthread_self_stack(void)
  774. {
  775. char *sp = CURRENT_STACK_FRAME;
  776. pthread_handle h;
  777. if (sp >= __pthread_manager_thread_bos && sp < __pthread_manager_thread_tos)
  778. return manager_thread;
  779. h = __pthread_handles + 2;
  780. # ifdef USE_TLS
  781. # ifdef _STACK_GROWS_UP
  782. while (h->h_descr == NULL
  783. || ! (sp >= h->h_descr->p_stackaddr && sp < h->h_descr->p_guardaddr))
  784. h++;
  785. # else
  786. while (h->h_descr == NULL
  787. || ! (sp <= (char *) h->h_descr->p_stackaddr && sp >= h->h_bottom))
  788. h++;
  789. # endif
  790. # else
  791. # ifdef _STACK_GROWS_UP
  792. while (! (sp >= (char *) h->h_descr && sp < h->h_descr->p_guardaddr))
  793. h++;
  794. # else
  795. while (! (sp <= (char *) h->h_descr && sp >= h->h_bottom))
  796. h++;
  797. # endif
  798. # endif
  799. return h->h_descr;
  800. }
  801. #endif
  802. /* Thread scheduling */
  803. int __pthread_setschedparam(pthread_t thread, int policy,
  804. const struct sched_param *param)
  805. {
  806. pthread_handle handle = thread_handle(thread);
  807. pthread_descr th;
  808. __pthread_lock(&handle->h_lock, NULL);
  809. if (__builtin_expect (invalid_handle(handle, thread), 0)) {
  810. __pthread_unlock(&handle->h_lock);
  811. return ESRCH;
  812. }
  813. th = handle->h_descr;
  814. if (__builtin_expect (__sched_setscheduler(th->p_pid, policy, param) == -1,
  815. 0)) {
  816. __pthread_unlock(&handle->h_lock);
  817. return errno;
  818. }
  819. th->p_priority = policy == SCHED_OTHER ? 0 : param->sched_priority;
  820. __pthread_unlock(&handle->h_lock);
  821. if (__pthread_manager_request >= 0)
  822. __pthread_manager_adjust_prio(th->p_priority);
  823. return 0;
  824. }
  825. strong_alias (__pthread_setschedparam, pthread_setschedparam)
  826. int __pthread_getschedparam(pthread_t thread, int *policy,
  827. struct sched_param *param)
  828. {
  829. pthread_handle handle = thread_handle(thread);
  830. int pid, pol;
  831. __pthread_lock(&handle->h_lock, NULL);
  832. if (__builtin_expect (invalid_handle(handle, thread), 0)) {
  833. __pthread_unlock(&handle->h_lock);
  834. return ESRCH;
  835. }
  836. pid = handle->h_descr->p_pid;
  837. __pthread_unlock(&handle->h_lock);
  838. pol = __sched_getscheduler(pid);
  839. if (__builtin_expect (pol, 0) == -1) return errno;
  840. if (__sched_getparam(pid, param) == -1) return errno;
  841. *policy = pol;
  842. return 0;
  843. }
  844. strong_alias (__pthread_getschedparam, pthread_getschedparam)
  845. /* Process-wide exit() request */
  846. static void pthread_onexit_process(int retcode, void *arg)
  847. {
  848. if (__builtin_expect (__pthread_manager_request, 0) >= 0) {
  849. struct pthread_request request;
  850. pthread_descr self = thread_self();
  851. request.req_thread = self;
  852. request.req_kind = REQ_PROCESS_EXIT;
  853. request.req_args.exit.code = retcode;
  854. TEMP_FAILURE_RETRY(write_not_cancel(__pthread_manager_request,
  855. (char *) &request, sizeof(request)));
  856. suspend(self);
  857. /* Main thread should accumulate times for thread manager and its
  858. children, so that timings for main thread account for all threads. */
  859. if (self == __pthread_main_thread)
  860. {
  861. #ifdef USE_TLS
  862. waitpid(manager_thread->p_pid, NULL, __WCLONE);
  863. #else
  864. waitpid(__pthread_manager_thread.p_pid, NULL, __WCLONE);
  865. #endif
  866. /* Since all threads have been asynchronously terminated
  867. (possibly holding locks), free cannot be used any more.
  868. For mtrace, we'd like to print something though. */
  869. /* #ifdef USE_TLS
  870. tcbhead_t *tcbp = (tcbhead_t *) manager_thread;
  871. # if TLS_DTV_AT_TP
  872. tcbp = (tcbhead_t) ((char *) tcbp + TLS_PRE_TCB_SIZE);
  873. # endif
  874. _dl_deallocate_tls (tcbp, true);
  875. #endif
  876. free (__pthread_manager_thread_bos); */
  877. __pthread_manager_thread_bos = __pthread_manager_thread_tos = NULL;
  878. }
  879. }
  880. }
  881. #ifndef HAVE_Z_NODELETE
  882. static int __pthread_atexit_retcode;
  883. static void pthread_atexit_process(void *arg, int retcode)
  884. {
  885. pthread_onexit_process (retcode ?: __pthread_atexit_retcode, arg);
  886. }
  887. static void pthread_atexit_retcode(void *arg, int retcode)
  888. {
  889. __pthread_atexit_retcode = retcode;
  890. }
  891. #endif
  892. /* The handler for the RESTART signal just records the signal received
  893. in the thread descriptor, and optionally performs a siglongjmp
  894. (for pthread_cond_timedwait). */
  895. static void pthread_handle_sigrestart(int sig)
  896. {
  897. pthread_descr self = check_thread_self();
  898. THREAD_SETMEM(self, p_signal, sig);
  899. if (THREAD_GETMEM(self, p_signal_jmp) != NULL)
  900. siglongjmp(*THREAD_GETMEM(self, p_signal_jmp), 1);
  901. }
  902. /* The handler for the CANCEL signal checks for cancellation
  903. (in asynchronous mode), for process-wide exit and exec requests.
  904. For the thread manager thread, redirect the signal to
  905. __pthread_manager_sighandler. */
  906. static void pthread_handle_sigcancel(int sig)
  907. {
  908. pthread_descr self = check_thread_self();
  909. sigjmp_buf * jmpbuf;
  910. if (self == manager_thread)
  911. {
  912. __pthread_manager_sighandler(sig);
  913. return;
  914. }
  915. if (__builtin_expect (__pthread_exit_requested, 0)) {
  916. /* Main thread should accumulate times for thread manager and its
  917. children, so that timings for main thread account for all threads. */
  918. if (self == __pthread_main_thread) {
  919. #ifdef USE_TLS
  920. waitpid(manager_thread->p_pid, NULL, __WCLONE);
  921. #else
  922. waitpid(__pthread_manager_thread.p_pid, NULL, __WCLONE);
  923. #endif
  924. }
  925. _exit(__pthread_exit_code);
  926. }
  927. if (__builtin_expect (THREAD_GETMEM(self, p_canceled), 0)
  928. && THREAD_GETMEM(self, p_cancelstate) == PTHREAD_CANCEL_ENABLE) {
  929. if (THREAD_GETMEM(self, p_canceltype) == PTHREAD_CANCEL_ASYNCHRONOUS)
  930. __pthread_do_exit(PTHREAD_CANCELED, CURRENT_STACK_FRAME);
  931. jmpbuf = THREAD_GETMEM(self, p_cancel_jmp);
  932. if (jmpbuf != NULL) {
  933. THREAD_SETMEM(self, p_cancel_jmp, NULL);
  934. siglongjmp(*jmpbuf, 1);
  935. }
  936. }
  937. }
  938. /* Handler for the DEBUG signal.
  939. The debugging strategy is as follows:
  940. On reception of a REQ_DEBUG request (sent by new threads created to
  941. the thread manager under debugging mode), the thread manager throws
  942. __pthread_sig_debug to itself. The debugger (if active) intercepts
  943. this signal, takes into account new threads and continue execution
  944. of the thread manager by propagating the signal because it doesn't
  945. know what it is specifically done for. In the current implementation,
  946. the thread manager simply discards it. */
  947. static void pthread_handle_sigdebug(int sig)
  948. {
  949. /* Nothing */
  950. }
  951. /* Reset the state of the thread machinery after a fork().
  952. Close the pipe used for requests and set the main thread to the forked
  953. thread.
  954. Notice that we can't free the stack segments, as the forked thread
  955. may hold pointers into them. */
  956. void __pthread_reset_main_thread(void)
  957. {
  958. pthread_descr self = thread_self();
  959. if (__pthread_manager_request != -1) {
  960. /* Free the thread manager stack */
  961. free(__pthread_manager_thread_bos);
  962. __pthread_manager_thread_bos = __pthread_manager_thread_tos = NULL;
  963. /* Close the two ends of the pipe */
  964. close_not_cancel(__pthread_manager_request);
  965. close_not_cancel(__pthread_manager_reader);
  966. __pthread_manager_request = __pthread_manager_reader = -1;
  967. }
  968. /* Update the pid of the main thread */
  969. THREAD_SETMEM(self, p_pid, __getpid());
  970. /* Make the forked thread the main thread */
  971. __pthread_main_thread = self;
  972. THREAD_SETMEM(self, p_nextlive, self);
  973. THREAD_SETMEM(self, p_prevlive, self);
  974. #if !(USE_TLS && HAVE___THREAD)
  975. /* Now this thread modifies the global variables. */
  976. THREAD_SETMEM(self, p_errnop, &_errno);
  977. THREAD_SETMEM(self, p_h_errnop, &_h_errno);
  978. THREAD_SETMEM(self, p_resp, &_res);
  979. #endif
  980. #ifndef FLOATING_STACKS
  981. /* This is to undo the setrlimit call in __pthread_init_max_stacksize.
  982. XXX This can be wrong if the user set the limit during the run. */
  983. {
  984. struct rlimit limit;
  985. if (getrlimit (RLIMIT_STACK, &limit) == 0
  986. && limit.rlim_cur != limit.rlim_max)
  987. {
  988. limit.rlim_cur = limit.rlim_max;
  989. setrlimit(RLIMIT_STACK, &limit);
  990. }
  991. }
  992. #endif
  993. }
  994. /* Process-wide exec() request */
  995. void __pthread_kill_other_threads_np(void)
  996. {
  997. struct sigaction sa;
  998. /* Terminate all other threads and thread manager */
  999. pthread_onexit_process(0, NULL);
  1000. /* Make current thread the main thread in case the calling thread
  1001. changes its mind, does not exec(), and creates new threads instead. */
  1002. __pthread_reset_main_thread();
  1003. /* Reset the signal handlers behaviour for the signals the
  1004. implementation uses since this would be passed to the new
  1005. process. */
  1006. sigemptyset(&sa.sa_mask);
  1007. sa.sa_flags = 0;
  1008. sa.sa_handler = SIG_DFL;
  1009. __libc_sigaction(__pthread_sig_restart, &sa, NULL);
  1010. __libc_sigaction(__pthread_sig_cancel, &sa, NULL);
  1011. if (__pthread_sig_debug > 0)
  1012. __libc_sigaction(__pthread_sig_debug, &sa, NULL);
  1013. }
  1014. weak_alias (__pthread_kill_other_threads_np, pthread_kill_other_threads_np)
  1015. /* Concurrency symbol level. */
  1016. static int current_level;
  1017. int __pthread_setconcurrency(int level)
  1018. {
  1019. /* We don't do anything unless we have found a useful interpretation. */
  1020. current_level = level;
  1021. return 0;
  1022. }
  1023. weak_alias (__pthread_setconcurrency, pthread_setconcurrency)
  1024. int __pthread_getconcurrency(void)
  1025. {
  1026. return current_level;
  1027. }
  1028. weak_alias (__pthread_getconcurrency, pthread_getconcurrency)
  1029. /* Primitives for controlling thread execution */
  1030. void __pthread_wait_for_restart_signal(pthread_descr self)
  1031. {
  1032. sigset_t mask;
  1033. sigprocmask(SIG_SETMASK, NULL, &mask); /* Get current signal mask */
  1034. sigdelset(&mask, __pthread_sig_restart); /* Unblock the restart signal */
  1035. THREAD_SETMEM(self, p_signal, 0);
  1036. do {
  1037. __pthread_sigsuspend(&mask); /* Wait for signal. Must not be a
  1038. cancellation point. */
  1039. } while (THREAD_GETMEM(self, p_signal) !=__pthread_sig_restart);
  1040. READ_MEMORY_BARRIER(); /* See comment in __pthread_restart_new */
  1041. }
  1042. #if !__ASSUME_REALTIME_SIGNALS
  1043. /* The _old variants are for 2.0 and early 2.1 kernels which don't have RT
  1044. signals.
  1045. On these kernels, we use SIGUSR1 and SIGUSR2 for restart and cancellation.
  1046. Since the restart signal does not queue, we use an atomic counter to create
  1047. queuing semantics. This is needed to resolve a rare race condition in
  1048. pthread_cond_timedwait_relative. */
  1049. void __pthread_restart_old(pthread_descr th)
  1050. {
  1051. if (atomic_increment(&th->p_resume_count) == -1)
  1052. kill(th->p_pid, __pthread_sig_restart);
  1053. }
  1054. void __pthread_suspend_old(pthread_descr self)
  1055. {
  1056. if (atomic_decrement(&self->p_resume_count) <= 0)
  1057. __pthread_wait_for_restart_signal(self);
  1058. }
  1059. int
  1060. __pthread_timedsuspend_old(pthread_descr self, const struct timespec *abstime)
  1061. {
  1062. sigset_t unblock, initial_mask;
  1063. int was_signalled = 0;
  1064. sigjmp_buf jmpbuf;
  1065. if (atomic_decrement(&self->p_resume_count) == 0) {
  1066. /* Set up a longjmp handler for the restart signal, unblock
  1067. the signal and sleep. */
  1068. if (sigsetjmp(jmpbuf, 1) == 0) {
  1069. THREAD_SETMEM(self, p_signal_jmp, &jmpbuf);
  1070. THREAD_SETMEM(self, p_signal, 0);
  1071. /* Unblock the restart signal */
  1072. sigemptyset(&unblock);
  1073. sigaddset(&unblock, __pthread_sig_restart);
  1074. sigprocmask(SIG_UNBLOCK, &unblock, &initial_mask);
  1075. while (1) {
  1076. struct timeval now;
  1077. struct timespec reltime;
  1078. /* Compute a time offset relative to now. */
  1079. __gettimeofday (&now, NULL);
  1080. reltime.tv_nsec = abstime->tv_nsec - now.tv_usec * 1000;
  1081. reltime.tv_sec = abstime->tv_sec - now.tv_sec;
  1082. if (reltime.tv_nsec < 0) {
  1083. reltime.tv_nsec += 1000000000;
  1084. reltime.tv_sec -= 1;
  1085. }
  1086. /* Sleep for the required duration. If woken by a signal,
  1087. resume waiting as required by Single Unix Specification. */
  1088. if (reltime.tv_sec < 0 || __libc_nanosleep(&reltime, NULL) == 0)
  1089. break;
  1090. }
  1091. /* Block the restart signal again */
  1092. sigprocmask(SIG_SETMASK, &initial_mask, NULL);
  1093. was_signalled = 0;
  1094. } else {
  1095. was_signalled = 1;
  1096. }
  1097. THREAD_SETMEM(self, p_signal_jmp, NULL);
  1098. }
  1099. /* Now was_signalled is true if we exited the above code
  1100. due to the delivery of a restart signal. In that case,
  1101. we know we have been dequeued and resumed and that the
  1102. resume count is balanced. Otherwise, there are some
  1103. cases to consider. First, try to bump up the resume count
  1104. back to zero. If it goes to 1, it means restart() was
  1105. invoked on this thread. The signal must be consumed
  1106. and the count bumped down and everything is cool. We
  1107. can return a 1 to the caller.
  1108. Otherwise, no restart was delivered yet, so a potential
  1109. race exists; we return a 0 to the caller which must deal
  1110. with this race in an appropriate way; for example by
  1111. atomically removing the thread from consideration for a
  1112. wakeup---if such a thing fails, it means a restart is
  1113. being delivered. */
  1114. if (!was_signalled) {
  1115. if (atomic_increment(&self->p_resume_count) != -1) {
  1116. __pthread_wait_for_restart_signal(self);
  1117. atomic_decrement(&self->p_resume_count); /* should be zero now! */
  1118. /* woke spontaneously and consumed restart signal */
  1119. return 1;
  1120. }
  1121. /* woke spontaneously but did not consume restart---caller must resolve */
  1122. return 0;
  1123. }
  1124. /* woken due to restart signal */
  1125. return 1;
  1126. }
  1127. #endif /* __ASSUME_REALTIME_SIGNALS */
  1128. void __pthread_restart_new(pthread_descr th)
  1129. {
  1130. /* The barrier is proabably not needed, in which case it still documents
  1131. our assumptions. The intent is to commit previous writes to shared
  1132. memory so the woken thread will have a consistent view. Complementary
  1133. read barriers are present to the suspend functions. */
  1134. WRITE_MEMORY_BARRIER();
  1135. kill(th->p_pid, __pthread_sig_restart);
  1136. }
  1137. /* There is no __pthread_suspend_new because it would just
  1138. be a wasteful wrapper for __pthread_wait_for_restart_signal */
  1139. int
  1140. __pthread_timedsuspend_new(pthread_descr self, const struct timespec *abstime)
  1141. {
  1142. sigset_t unblock, initial_mask;
  1143. int was_signalled = 0;
  1144. sigjmp_buf jmpbuf;
  1145. if (sigsetjmp(jmpbuf, 1) == 0) {
  1146. THREAD_SETMEM(self, p_signal_jmp, &jmpbuf);
  1147. THREAD_SETMEM(self, p_signal, 0);
  1148. /* Unblock the restart signal */
  1149. sigemptyset(&unblock);
  1150. sigaddset(&unblock, __pthread_sig_restart);
  1151. sigprocmask(SIG_UNBLOCK, &unblock, &initial_mask);
  1152. while (1) {
  1153. struct timeval now;
  1154. struct timespec reltime;
  1155. /* Compute a time offset relative to now. */
  1156. __gettimeofday (&now, NULL);
  1157. reltime.tv_nsec = abstime->tv_nsec - now.tv_usec * 1000;
  1158. reltime.tv_sec = abstime->tv_sec - now.tv_sec;
  1159. if (reltime.tv_nsec < 0) {
  1160. reltime.tv_nsec += 1000000000;
  1161. reltime.tv_sec -= 1;
  1162. }
  1163. /* Sleep for the required duration. If woken by a signal,
  1164. resume waiting as required by Single Unix Specification. */
  1165. if (reltime.tv_sec < 0 || __libc_nanosleep(&reltime, NULL) == 0)
  1166. break;
  1167. }
  1168. /* Block the restart signal again */
  1169. sigprocmask(SIG_SETMASK, &initial_mask, NULL);
  1170. was_signalled = 0;
  1171. } else {
  1172. was_signalled = 1;
  1173. }
  1174. THREAD_SETMEM(self, p_signal_jmp, NULL);
  1175. /* Now was_signalled is true if we exited the above code
  1176. due to the delivery of a restart signal. In that case,
  1177. everything is cool. We have been removed from whatever
  1178. we were waiting on by the other thread, and consumed its signal.
  1179. Otherwise we this thread woke up spontaneously, or due to a signal other
  1180. than restart. This is an ambiguous case that must be resolved by
  1181. the caller; the thread is still eligible for a restart wakeup
  1182. so there is a race. */
  1183. READ_MEMORY_BARRIER(); /* See comment in __pthread_restart_new */
  1184. return was_signalled;
  1185. }
  1186. /* Debugging aid */
  1187. #ifdef DEBUG
  1188. #include <stdarg.h>
  1189. void __pthread_message(const char * fmt, ...)
  1190. {
  1191. char buffer[1024];
  1192. va_list args;
  1193. sprintf(buffer, "%05d : ", __getpid());
  1194. va_start(args, fmt);
  1195. vsnprintf(buffer + 8, sizeof(buffer) - 8, fmt, args);
  1196. va_end(args);
  1197. TEMP_FAILURE_RETRY(write_not_cancel(2, buffer, strlen(buffer)));
  1198. }
  1199. #endif