pthread.c 45 KB

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