pthread.c 45 KB

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