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