pthread.c 44 KB

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