pthread.c 45 KB

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