use a single libc and deduplicate threading code
[uclibc-ng.git] / libpthread / nptl / init.c
blob0e1c60cdac138c88cc4667bad27fe52e8fa8fe71
1 /* Copyright (C) 2002-2007, 2008, 2009 Free Software Foundation, Inc.
2 This file is part of the GNU C Library.
3 Contributed by Ulrich Drepper <drepper@redhat.com>, 2002.
5 The GNU C Library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
10 The GNU C Library 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 GNU
13 Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public
16 License along with the GNU C Library; if not, see
17 <http://www.gnu.org/licenses/>. */
19 #include <assert.h>
20 #include <errno.h>
21 #include <limits.h>
22 #include <signal.h>
23 #include <stdlib.h>
24 #include <unistd.h>
25 #include <sys/param.h>
26 #include <sys/resource.h>
27 #include <pthreadP.h>
28 #include <atomic.h>
29 #include <ldsodefs.h>
30 #include <tls.h>
31 #include <fork.h>
32 #include <version.h>
33 #include <smp.h>
34 #include <lowlevellock.h>
35 #include <bits/kernel-features.h>
36 #include <stdio.h>
38 /* Size and alignment of static TLS block. */
39 size_t __static_tls_size;
40 size_t __static_tls_align_m1;
42 #ifndef __ASSUME_SET_ROBUST_LIST
43 /* Negative if we do not have the system call and we can use it. */
44 int __set_robust_list_avail;
45 # define set_robust_list_not_avail() \
46 __set_robust_list_avail = -1
47 #else
48 # define set_robust_list_not_avail() do { } while (0)
49 #endif
51 #ifndef __ASSUME_FUTEX_CLOCK_REALTIME
52 /* Nonzero if we do not have FUTEX_CLOCK_REALTIME. */
53 int __have_futex_clock_realtime;
54 # define __set_futex_clock_realtime() \
55 __have_futex_clock_realtime = 1
56 #else
57 #define __set_futex_clock_realtime() do { } while (0)
58 #endif
60 /* Version of the library, used in libthread_db to detect mismatches. */
61 static const char nptl_version[] __attribute_used__ = VERSION;
63 /* For asynchronous cancellation we use a signal. This is the handler. */
64 static void
65 sigcancel_handler (int sig, siginfo_t *si, void *ctx)
67 #ifdef __ASSUME_CORRECT_SI_PID
68 /* Determine the process ID. It might be negative if the thread is
69 in the middle of a fork() call. */
70 pid_t pid = THREAD_GETMEM (THREAD_SELF, pid);
71 if (__builtin_expect (pid < 0, 0))
72 pid = -pid;
73 #endif
75 /* Safety check. It would be possible to call this function for
76 other signals and send a signal from another process. This is not
77 correct and might even be a security problem. Try to catch as
78 many incorrect invocations as possible. */
79 if (sig != SIGCANCEL
80 #ifdef __ASSUME_CORRECT_SI_PID
81 /* Kernels before 2.5.75 stored the thread ID and not the process
82 ID in si_pid so we skip this test. */
83 || si->si_pid != pid
84 #endif
85 || si->si_code != SI_TKILL)
86 return;
88 struct pthread *self = THREAD_SELF;
90 int oldval = THREAD_GETMEM (self, cancelhandling);
91 while (1)
93 /* We are canceled now. When canceled by another thread this flag
94 is already set but if the signal is directly send (internally or
95 from another process) is has to be done here. */
96 int newval = oldval | CANCELING_BITMASK | CANCELED_BITMASK;
98 if (oldval == newval || (oldval & EXITING_BITMASK) != 0)
99 /* Already canceled or exiting. */
100 break;
102 int curval = THREAD_ATOMIC_CMPXCHG_VAL (self, cancelhandling, newval,
103 oldval);
104 if (curval == oldval)
106 /* Set the return value. */
107 THREAD_SETMEM (self, result, PTHREAD_CANCELED);
109 /* Make sure asynchronous cancellation is still enabled. */
110 if ((newval & CANCELTYPE_BITMASK) != 0)
111 /* Run the registered destructors and terminate the thread. */
112 __do_cancel ();
114 break;
117 oldval = curval;
122 struct xid_command *__xidcmd attribute_hidden;
124 /* For asynchronous cancellation we use a signal. This is the handler. */
125 static void
126 sighandler_setxid (int sig, siginfo_t *si, void *ctx)
128 #ifdef __ASSUME_CORRECT_SI_PID
129 /* Determine the process ID. It might be negative if the thread is
130 in the middle of a fork() call. */
131 pid_t pid = THREAD_GETMEM (THREAD_SELF, pid);
132 if (__builtin_expect (pid < 0, 0))
133 pid = -pid;
134 #endif
136 /* Safety check. It would be possible to call this function for
137 other signals and send a signal from another process. This is not
138 correct and might even be a security problem. Try to catch as
139 many incorrect invocations as possible. */
140 if (sig != SIGSETXID
141 #ifdef __ASSUME_CORRECT_SI_PID
142 /* Kernels before 2.5.75 stored the thread ID and not the process
143 ID in si_pid so we skip this test. */
144 || si->si_pid != pid
145 #endif
146 || si->si_code != SI_TKILL)
147 return;
149 INTERNAL_SYSCALL_DECL (err);
150 INTERNAL_SYSCALL_NCS (__xidcmd->syscall_no, err, 3, __xidcmd->id[0],
151 __xidcmd->id[1], __xidcmd->id[2]);
153 /* Reset the SETXID flag. */
154 struct pthread *self = THREAD_SELF;
155 int flags, newval;
158 flags = THREAD_GETMEM (self, cancelhandling);
159 newval = THREAD_ATOMIC_CMPXCHG_VAL (self, cancelhandling,
160 flags & ~SETXID_BITMASK, flags);
162 while (flags != newval);
164 /* And release the futex. */
165 self->setxid_futex = 1;
166 lll_futex_wake (&self->setxid_futex, 1, LLL_PRIVATE);
168 if (atomic_decrement_val (&__xidcmd->cntr) == 0)
169 lll_futex_wake (&__xidcmd->cntr, 1, LLL_PRIVATE);
173 /* When using __thread for this, we do it in libc so as not
174 to give libpthread its own TLS segment just for this. */
175 extern void **__libc_dl_error_tsd (void) __attribute__ ((const));
178 /* This can be set by the debugger before initialization is complete. */
179 static bool __nptl_initial_report_events __attribute_used__;
181 void __pthread_initialize_minimal_internal (void) attribute_hidden;
182 void
183 __pthread_initialize_minimal_internal (void)
185 static int initialized = 0;
187 if (initialized)
188 return;
189 initialized = 1;
191 /* Minimal initialization of the thread descriptor. */
192 struct pthread *pd = THREAD_SELF;
193 INTERNAL_SYSCALL_DECL (err);
194 pd->pid = pd->tid = INTERNAL_SYSCALL (set_tid_address, err, 1, &pd->tid);
195 THREAD_SETMEM (pd, specific[0], &pd->specific_1stblock[0]);
196 THREAD_SETMEM (pd, user_stack, true);
197 if (LLL_LOCK_INITIALIZER != 0)
198 THREAD_SETMEM (pd, lock, LLL_LOCK_INITIALIZER);
199 #if HP_TIMING_AVAIL
200 THREAD_SETMEM (pd, cpuclock_offset, GL(dl_cpuclock_offset));
201 #endif
203 /* Initialize the robust mutex data. */
204 #ifdef __PTHREAD_MUTEX_HAVE_PREV
205 pd->robust_prev = &pd->robust_head;
206 #endif
207 pd->robust_head.list = &pd->robust_head;
208 #ifdef __NR_set_robust_list
209 pd->robust_head.futex_offset = (offsetof (pthread_mutex_t, __data.__lock)
210 - offsetof (pthread_mutex_t,
211 __data.__list.__next));
212 int res = INTERNAL_SYSCALL (set_robust_list, err, 2, &pd->robust_head,
213 sizeof (struct robust_list_head));
214 if (INTERNAL_SYSCALL_ERROR_P (res, err))
215 #endif
216 set_robust_list_not_avail ();
218 #ifndef __ASSUME_PRIVATE_FUTEX
219 /* Private futexes are always used (at least internally) so that
220 doing the test once this early is beneficial. */
222 int word = 0;
223 word = INTERNAL_SYSCALL (futex, err, 3, &word,
224 FUTEX_WAKE | FUTEX_PRIVATE_FLAG, 1);
225 if (!INTERNAL_SYSCALL_ERROR_P (word, err))
226 THREAD_SETMEM (pd, header.private_futex, FUTEX_PRIVATE_FLAG);
229 /* Private futexes have been introduced earlier than the
230 FUTEX_CLOCK_REALTIME flag. We don't have to run the test if we
231 know the former are not supported. This also means we know the
232 kernel will return ENOSYS for unknown operations. */
233 if (THREAD_GETMEM (pd, header.private_futex) != 0)
234 #endif
235 #ifndef __ASSUME_FUTEX_CLOCK_REALTIME
237 int word = 0;
238 /* NB: the syscall actually takes six parameters. The last is the
239 bit mask. But since we will not actually wait at all the value
240 is irrelevant. Given that passing six parameters is difficult
241 on some architectures we just pass whatever random value the
242 calling convention calls for to the kernel. It causes no harm. */
243 word = INTERNAL_SYSCALL (futex, err, 5, &word,
244 FUTEX_WAIT_BITSET | FUTEX_CLOCK_REALTIME
245 | FUTEX_PRIVATE_FLAG, 1, NULL, 0);
246 assert (INTERNAL_SYSCALL_ERROR_P (word, err));
247 if (INTERNAL_SYSCALL_ERRNO (word, err) != ENOSYS)
248 __set_futex_clock_realtime ();
250 #endif
252 /* Set initial thread's stack block from 0 up to __libc_stack_end.
253 It will be bigger than it actually is, but for unwind.c/pt-longjmp.c
254 purposes this is good enough. */
255 THREAD_SETMEM (pd, stackblock_size, (size_t) __libc_stack_end);
257 /* Initialize the list of all running threads with the main thread. */
258 INIT_LIST_HEAD (&__stack_user);
259 list_add (&pd->list, &__stack_user);
261 /* Before initializing __stack_user, the debugger could not find us and
262 had to set __nptl_initial_report_events. Propagate its setting. */
263 THREAD_SETMEM (pd, report_events, __nptl_initial_report_events);
265 /* Install the cancellation signal handler. If for some reason we
266 cannot install the handler we do not abort. Maybe we should, but
267 it is only asynchronous cancellation which is affected. */
268 struct sigaction sa;
269 sa.sa_sigaction = sigcancel_handler;
270 sa.sa_flags = SA_SIGINFO;
271 __sigemptyset (&sa.sa_mask);
273 (void) __libc_sigaction (SIGCANCEL, &sa, NULL);
275 /* Install the handle to change the threads' uid/gid. */
276 sa.sa_sigaction = sighandler_setxid;
277 sa.sa_flags = SA_SIGINFO | SA_RESTART;
279 (void) __libc_sigaction (SIGSETXID, &sa, NULL);
281 /* The parent process might have left the signals blocked. Just in
282 case, unblock it. We reuse the signal mask in the sigaction
283 structure. It is already cleared. */
284 __sigaddset (&sa.sa_mask, SIGCANCEL);
285 __sigaddset (&sa.sa_mask, SIGSETXID);
286 (void) INTERNAL_SYSCALL (rt_sigprocmask, err, 4, SIG_UNBLOCK, &sa.sa_mask,
287 NULL, _NSIG / 8);
289 /* Get the size of the static and alignment requirements for the TLS
290 block. */
291 size_t static_tls_align;
292 _dl_get_tls_static_info (&__static_tls_size, &static_tls_align);
294 /* Make sure the size takes all the alignments into account. */
295 if (STACK_ALIGN > static_tls_align)
296 static_tls_align = STACK_ALIGN;
297 __static_tls_align_m1 = static_tls_align - 1;
299 __static_tls_size = roundup (__static_tls_size, static_tls_align);
301 /* Determine the default allowed stack size. This is the size used
302 in case the user does not specify one. */
303 struct rlimit limit;
304 if (getrlimit (RLIMIT_STACK, &limit) != 0
305 || limit.rlim_cur == RLIM_INFINITY)
306 /* The system limit is not usable. Use an architecture-specific
307 default. */
308 limit.rlim_cur = ARCH_STACK_DEFAULT_SIZE;
309 else if (limit.rlim_cur < PTHREAD_STACK_MIN)
310 /* The system limit is unusably small.
311 Use the minimal size acceptable. */
312 limit.rlim_cur = PTHREAD_STACK_MIN;
314 /* Do not exceed architecture specific default */
315 if (limit.rlim_cur > ARCH_STACK_DEFAULT_SIZE)
316 limit.rlim_cur = ARCH_STACK_DEFAULT_SIZE;
318 /* Make sure it meets the minimum size that allocate_stack
319 (allocatestack.c) will demand, which depends on the page size. */
320 const uintptr_t pagesz = sysconf (_SC_PAGESIZE);
321 const size_t minstack = pagesz + __static_tls_size + MINIMAL_REST_STACK;
322 if (limit.rlim_cur < minstack)
323 limit.rlim_cur = minstack;
325 /* Round the resource limit up to page size. */
326 limit.rlim_cur = (limit.rlim_cur + pagesz - 1) & -pagesz;
327 __default_stacksize = limit.rlim_cur;
329 #ifdef SHARED
330 /* Transfer the old value from the dynamic linker's internal location. */
331 *__libc_dl_error_tsd () = *(*GL(dl_error_catch_tsd)) ();
332 GL(dl_error_catch_tsd) = &__libc_dl_error_tsd;
334 #endif
336 GL(dl_init_static_tls) = &__pthread_init_static_tls;
338 /* Register the fork generation counter with the libc. */
339 #ifndef TLS_MULTIPLE_THREADS_IN_TCB
340 __libc_multiple_threads_ptr =
341 #endif
342 __libc_pthread_init (&__fork_generation, __reclaim_stacks);
344 /* Determine whether the machine is SMP or not. */
345 __is_smp = is_smp_system ();
347 /* uClibc-specific stdio initialization for threads. */
349 FILE *fp;
350 _stdio_user_locking = 0; /* 2 if threading not initialized */
351 for (fp = _stdio_openlist; fp != NULL; fp = fp->__nextopen) {
352 if (fp->__user_locking != 1) {
353 fp->__user_locking = 0;
358 strong_alias (__pthread_initialize_minimal_internal,
359 __pthread_initialize_minimal)