xref: /freebsd/lib/libthr/thread/thr_init.c (revision 263d6a7ece4f357d01b3152c39e5d36043f877bb)
1 /*
2  * Copyright (c) 2003 Daniel M. Eischen <deischen@freebsd.org>
3  * Copyright (c) 1995-1998 John Birrell <jb@cimlogic.com.au>
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  * 3. All advertising materials mentioning features or use of this software
15  *    must display the following acknowledgement:
16  *	This product includes software developed by John Birrell.
17  * 4. Neither the name of the author nor the names of any co-contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY JOHN BIRRELL AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  * $FreeBSD$
34  */
35 
36 /* Allocate space for global thread variables here: */
37 #define GLOBAL_PTHREAD_PRIVATE
38 
39 #include "namespace.h"
40 #include <sys/param.h>
41 #include <sys/types.h>
42 #include <sys/signalvar.h>
43 #include <machine/reg.h>
44 
45 #include <sys/ioctl.h>
46 #include <sys/mount.h>
47 #include <sys/uio.h>
48 #include <sys/socket.h>
49 #include <sys/event.h>
50 #include <sys/stat.h>
51 #include <sys/sysctl.h>
52 #include <sys/time.h>
53 #include <sys/ttycom.h>
54 #include <sys/wait.h>
55 #include <sys/mman.h>
56 #include <dirent.h>
57 #include <errno.h>
58 #include <fcntl.h>
59 #include <paths.h>
60 #include <pthread.h>
61 #include <pthread_np.h>
62 #include <signal.h>
63 #include <stdio.h>
64 #include <stdlib.h>
65 #include <string.h>
66 #include <unistd.h>
67 #include "un-namespace.h"
68 
69 #include "libc_private.h"
70 #include "thr_private.h"
71 
72 int	__pthread_cond_wait(pthread_cond_t *, pthread_mutex_t *);
73 int	__pthread_mutex_lock(pthread_mutex_t *);
74 int	__pthread_mutex_trylock(pthread_mutex_t *);
75 void	_thread_init_hack(void) __attribute__ ((constructor));
76 
77 static void init_private(void);
78 static void init_main_thread(struct pthread *thread);
79 
80 /*
81  * All weak references used within libc should be in this table.
82  * This is so that static libraries will work.
83  */
84 static void *references[] = {
85 	&_accept,
86 	&_bind,
87 	&_close,
88 	&_connect,
89 	&_dup,
90 	&_dup2,
91 	&_execve,
92 	&_fcntl,
93 	&_flock,
94 	&_flockfile,
95 	&_fstat,
96 	&_fstatfs,
97 	&_fsync,
98 	&_funlockfile,
99 	&_getdirentries,
100 	&_getlogin,
101 	&_getpeername,
102 	&_getsockname,
103 	&_getsockopt,
104 	&_ioctl,
105 	&_kevent,
106 	&_listen,
107 	&_nanosleep,
108 	&_open,
109 	&_pthread_getspecific,
110 	&_pthread_key_create,
111 	&_pthread_key_delete,
112 	&_pthread_mutex_destroy,
113 	&_pthread_mutex_init,
114 	&_pthread_mutex_lock,
115 	&_pthread_mutex_trylock,
116 	&_pthread_mutex_unlock,
117 	&_pthread_mutexattr_init,
118 	&_pthread_mutexattr_destroy,
119 	&_pthread_mutexattr_settype,
120 	&_pthread_once,
121 	&_pthread_setspecific,
122 	&_read,
123 	&_readv,
124 	&_recvfrom,
125 	&_recvmsg,
126 	&_select,
127 	&_sendmsg,
128 	&_sendto,
129 	&_setsockopt,
130 	&_sigaction,
131 	&_sigprocmask,
132 	&_sigsuspend,
133 	&_socket,
134 	&_socketpair,
135 	&_thread_init_hack,
136 	&_wait4,
137 	&_write,
138 	&_writev
139 };
140 
141 /*
142  * These are needed when linking statically.  All references within
143  * libgcc (and in the future libc) to these routines are weak, but
144  * if they are not (strongly) referenced by the application or other
145  * libraries, then the actual functions will not be loaded.
146  */
147 static void *libgcc_references[] = {
148 	&_pthread_once,
149 	&_pthread_key_create,
150 	&_pthread_key_delete,
151 	&_pthread_getspecific,
152 	&_pthread_setspecific,
153 	&_pthread_mutex_init,
154 	&_pthread_mutex_destroy,
155 	&_pthread_mutex_lock,
156 	&_pthread_mutex_trylock,
157 	&_pthread_mutex_unlock,
158 	&_pthread_create
159 };
160 
161 #define	DUAL_ENTRY(entry)	\
162 	(pthread_func_t)entry, (pthread_func_t)entry
163 
164 static pthread_func_t jmp_table[][2] = {
165 	{DUAL_ENTRY(_pthread_cond_broadcast)},	/* PJT_COND_BROADCAST */
166 	{DUAL_ENTRY(_pthread_cond_destroy)},	/* PJT_COND_DESTROY */
167 	{DUAL_ENTRY(_pthread_cond_init)},	/* PJT_COND_INIT */
168 	{DUAL_ENTRY(_pthread_cond_signal)},	/* PJT_COND_SIGNAL */
169 	{(pthread_func_t)__pthread_cond_wait,
170 	 (pthread_func_t)_pthread_cond_wait},	/* PJT_COND_WAIT */
171 	{DUAL_ENTRY(_pthread_getspecific)},	/* PJT_GETSPECIFIC */
172 	{DUAL_ENTRY(_pthread_key_create)},	/* PJT_KEY_CREATE */
173 	{DUAL_ENTRY(_pthread_key_delete)},	/* PJT_KEY_DELETE*/
174 	{DUAL_ENTRY(_pthread_main_np)},		/* PJT_MAIN_NP */
175 	{DUAL_ENTRY(_pthread_mutex_destroy)},	/* PJT_MUTEX_DESTROY */
176 	{DUAL_ENTRY(_pthread_mutex_init)},	/* PJT_MUTEX_INIT */
177 	{(pthread_func_t)__pthread_mutex_lock,
178 	 (pthread_func_t)_pthread_mutex_lock},	/* PJT_MUTEX_LOCK */
179 	{(pthread_func_t)__pthread_mutex_trylock,
180 	 (pthread_func_t)_pthread_mutex_trylock},/* PJT_MUTEX_TRYLOCK */
181 	{DUAL_ENTRY(_pthread_mutex_unlock)},	/* PJT_MUTEX_UNLOCK */
182 	{DUAL_ENTRY(_pthread_mutexattr_destroy)}, /* PJT_MUTEXATTR_DESTROY */
183 	{DUAL_ENTRY(_pthread_mutexattr_init)},	/* PJT_MUTEXATTR_INIT */
184 	{DUAL_ENTRY(_pthread_mutexattr_settype)}, /* PJT_MUTEXATTR_SETTYPE */
185 	{DUAL_ENTRY(_pthread_once)},		/* PJT_ONCE */
186 	{DUAL_ENTRY(_pthread_rwlock_destroy)},	/* PJT_RWLOCK_DESTROY */
187 	{DUAL_ENTRY(_pthread_rwlock_init)},	/* PJT_RWLOCK_INIT */
188 	{DUAL_ENTRY(_pthread_rwlock_rdlock)},	/* PJT_RWLOCK_RDLOCK */
189 	{DUAL_ENTRY(_pthread_rwlock_tryrdlock)},/* PJT_RWLOCK_TRYRDLOCK */
190 	{DUAL_ENTRY(_pthread_rwlock_trywrlock)},/* PJT_RWLOCK_TRYWRLOCK */
191 	{DUAL_ENTRY(_pthread_rwlock_unlock)},	/* PJT_RWLOCK_UNLOCK */
192 	{DUAL_ENTRY(_pthread_rwlock_wrlock)},	/* PJT_RWLOCK_WRLOCK */
193 	{DUAL_ENTRY(_pthread_self)},		/* PJT_SELF */
194 	{DUAL_ENTRY(_pthread_setspecific)},	/* PJT_SETSPECIFIC */
195 	{DUAL_ENTRY(_pthread_sigmask)}		/* PJT_SIGMASK */
196 };
197 
198 extern int _thread_state_running;
199 static int init_once = 0;
200 
201 /*
202  * For the shared version of the threads library, the above is sufficient.
203  * But for the archive version of the library, we need a little bit more.
204  * Namely, we must arrange for this particular module to be pulled in from
205  * the archive library at link time.  To accomplish that, we define and
206  * initialize a variable, "_thread_autoinit_dummy_decl".  This variable is
207  * referenced (as an extern) from libc/stdlib/exit.c. This will always
208  * create a need for this module, ensuring that it is present in the
209  * executable.
210  */
211 extern int _thread_autoinit_dummy_decl;
212 int _thread_autoinit_dummy_decl = 0;
213 
214 void
215 _thread_init_hack(void)
216 {
217 
218 	_libpthread_init(NULL);
219 }
220 
221 
222 /*
223  * Threaded process initialization.
224  *
225  * This is only called under two conditions:
226  *
227  *   1) Some thread routines have detected that the library hasn't yet
228  *      been initialized (_thr_initial == NULL && curthread == NULL), or
229  *
230  *   2) An explicit call to reinitialize after a fork (indicated
231  *      by curthread != NULL)
232  */
233 void
234 _libpthread_init(struct pthread *curthread)
235 {
236 	int fd, first = 0;
237 	sigset_t sigset, oldset;
238 
239 	/* Check if this function has already been called: */
240 	if ((_thr_initial != NULL) && (curthread == NULL))
241 		/* Only initialize the threaded application once. */
242 		return;
243 
244 	/*
245 	 * Make gcc quiescent about {,libgcc_}references not being
246 	 * referenced:
247 	 */
248 	if ((references[0] == NULL) || (libgcc_references[0] == NULL))
249 		PANIC("Failed loading mandatory references in _thread_init");
250 
251 	/* Pull debug symbols in for static binary */
252 	_thread_state_running = PS_RUNNING;
253 
254 	/*
255 	 * Check the size of the jump table to make sure it is preset
256 	 * with the correct number of entries.
257 	 */
258 	if (sizeof(jmp_table) != (sizeof(pthread_func_t) * PJT_MAX * 2))
259 		PANIC("Thread jump table not properly initialized");
260 	memcpy(__thr_jtable, jmp_table, sizeof(jmp_table));
261 
262 	/*
263 	 * Check for the special case of this process running as
264 	 * or in place of init as pid = 1:
265 	 */
266 	if ((_thr_pid = getpid()) == 1) {
267 		/*
268 		 * Setup a new session for this process which is
269 		 * assumed to be running as root.
270 		 */
271 		if (setsid() == -1)
272 			PANIC("Can't set session ID");
273 		if (revoke(_PATH_CONSOLE) != 0)
274 			PANIC("Can't revoke console");
275 		if ((fd = __sys_open(_PATH_CONSOLE, O_RDWR)) < 0)
276 			PANIC("Can't open console");
277 		if (setlogin("root") == -1)
278 			PANIC("Can't set login to root");
279 		if (__sys_ioctl(fd, TIOCSCTTY, (char *) NULL) == -1)
280 			PANIC("Can't set controlling terminal");
281 	}
282 
283 	/* Initialize pthread private data. */
284 	init_private();
285 
286 	/* Set the initial thread. */
287 	if (curthread == NULL) {
288 		first = 1;
289 		/* Create and initialize the initial thread. */
290 		curthread = _thr_alloc(NULL);
291 		if (curthread == NULL)
292 			PANIC("Can't allocate initial thread");
293 		init_main_thread(curthread);
294 	}
295 	/*
296 	 * Add the thread to the thread list queue.
297 	 */
298 	THR_LIST_ADD(curthread);
299 	_thread_active_threads = 1;
300 
301 	/* Setup the thread specific data */
302 	_tcb_set(curthread->tcb);
303 
304 	if (first) {
305 		SIGFILLSET(sigset);
306 		SIGDELSET(sigset, SIGTRAP);
307 		__sys_sigprocmask(SIG_SETMASK, &sigset, &oldset);
308 		_thr_signal_init();
309 		_thr_initial = curthread;
310 		SIGDELSET(oldset, SIGCANCEL);
311 		__sys_sigprocmask(SIG_SETMASK, &oldset, NULL);
312 		if (_thread_event_mask & TD_CREATE)
313 			_thr_report_creation(curthread, curthread);
314 	}
315 }
316 
317 /*
318  * This function and pthread_create() do a lot of the same things.
319  * It'd be nice to consolidate the common stuff in one place.
320  */
321 static void
322 init_main_thread(struct pthread *thread)
323 {
324 	/* Setup the thread attributes. */
325 	thr_self(&thread->tid);
326 	thread->attr = _pthread_attr_default;
327 	/*
328 	 * Set up the thread stack.
329 	 *
330 	 * Create a red zone below the main stack.  All other stacks
331 	 * are constrained to a maximum size by the parameters
332 	 * passed to mmap(), but this stack is only limited by
333 	 * resource limits, so this stack needs an explicitly mapped
334 	 * red zone to protect the thread stack that is just beyond.
335 	 */
336 	if (mmap((void *)_usrstack - _thr_stack_initial -
337 	    _thr_guard_default, _thr_guard_default, 0, MAP_ANON,
338 	    -1, 0) == MAP_FAILED)
339 		PANIC("Cannot allocate red zone for initial thread");
340 
341 	/*
342 	 * Mark the stack as an application supplied stack so that it
343 	 * isn't deallocated.
344 	 *
345 	 * XXX - I'm not sure it would hurt anything to deallocate
346 	 *       the main thread stack because deallocation doesn't
347 	 *       actually free() it; it just puts it in the free
348 	 *       stack queue for later reuse.
349 	 */
350 	thread->attr.stackaddr_attr = (void *)_usrstack - _thr_stack_initial;
351 	thread->attr.stacksize_attr = _thr_stack_initial;
352 	thread->attr.guardsize_attr = _thr_guard_default;
353 	thread->attr.flags |= THR_STACK_USER;
354 
355 	/*
356 	 * Write a magic value to the thread structure
357 	 * to help identify valid ones:
358 	 */
359 	thread->magic = THR_MAGIC;
360 
361 	thread->cancelflags = PTHREAD_CANCEL_ENABLE | PTHREAD_CANCEL_DEFERRED;
362 	thread->name = strdup("initial thread");
363 
364 	/* Default the priority of the initial thread: */
365 	thread->base_priority = THR_DEFAULT_PRIORITY;
366 	thread->active_priority = THR_DEFAULT_PRIORITY;
367 	thread->inherited_priority = 0;
368 
369 	/* Initialize the mutex queue: */
370 	TAILQ_INIT(&thread->mutexq);
371 	TAILQ_INIT(&thread->pri_mutexq);
372 
373 	thread->state = PS_RUNNING;
374 
375 	/* Others cleared to zero by thr_alloc() */
376 }
377 
378 static void
379 init_private(void)
380 {
381 	size_t len;
382 	int mib[2];
383 
384 	_thr_umtx_init(&_mutex_static_lock);
385 	_thr_umtx_init(&_cond_static_lock);
386 	_thr_umtx_init(&_rwlock_static_lock);
387 	_thr_umtx_init(&_keytable_lock);
388 	_thr_umtx_init(&_thr_atfork_lock);
389 	_thr_umtx_init(&_thr_event_lock);
390 	_thr_spinlock_init();
391 	_thr_list_init();
392 
393 	/*
394 	 * Avoid reinitializing some things if they don't need to be,
395 	 * e.g. after a fork().
396 	 */
397 	if (init_once == 0) {
398 		/* Find the stack top */
399 		mib[0] = CTL_KERN;
400 		mib[1] = KERN_USRSTACK;
401 		len = sizeof (_usrstack);
402 		if (sysctl(mib, 2, &_usrstack, &len, NULL, 0) == -1)
403 			PANIC("Cannot get kern.usrstack from sysctl");
404 		_thr_page_size = getpagesize();
405 		_thr_guard_default = _thr_page_size;
406 		_pthread_attr_default.guardsize_attr = _thr_guard_default;
407 		_pthread_attr_default.stacksize_attr = _thr_stack_default;
408 
409 		TAILQ_INIT(&_thr_atfork_list);
410 #ifdef SYSTEM_SCOPE_ONLY
411 		_thr_scope_system = 1;
412 #else
413 		if (getenv("LIBPTHREAD_SYSTEM_SCOPE") != NULL)
414 			_thr_scope_system = 1;
415 		else if (getenv("LIBPTHREAD_PROCESS_SCOPE") != NULL)
416 			_thr_scope_system = -1;
417 #endif
418 	}
419 	init_once = 1;
420 }
421