1 /* Copyright (C) 2002-2020 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 <https://www.gnu.org/licenses/>. */
26 #include <hp-timing.h>
29 #include <libc-internal.h>
31 #include <kernel-features.h>
32 #include <exit-thread.h>
33 #include <default-sched.h>
34 #include <futex-internal.h>
35 #include <tls-setup.h>
37 #include <sys/single_threaded.h>
39 #include <shlib-compat.h>
41 #include <stap-probe.h>
44 /* Nozero if debugging mode is enabled. */
47 /* Globally enabled events. */
48 static td_thr_events_t __nptl_threads_events __attribute_used__
;
50 /* Pointer to descriptor with the last event. */
51 static struct pthread
*__nptl_last_event __attribute_used__
;
53 /* Number of threads running. */
54 unsigned int __nptl_nthreads
= 1;
57 /* Code to allocate and deallocate a stack. */
58 #include "allocatestack.c"
62 Understanding who is the owner of the 'struct pthread' or 'PD'
63 (refers to the value of the 'struct pthread *pd' function argument)
64 is critically important in determining exactly which operations are
65 allowed and which are not and when, particularly when it comes to the
66 implementation of pthread_create, pthread_join, pthread_detach, and
67 other functions which all operate on PD.
69 The owner of PD is responsible for freeing the final resources
70 associated with PD, and may examine the memory underlying PD at any
71 point in time until it frees it back to the OS or to reuse by the
74 The thread which calls pthread_create is called the creating thread.
75 The creating thread begins as the owner of PD.
77 During startup the new thread may examine PD in coordination with the
78 owner thread (which may be itself).
80 The four cases of ownership transfer are:
82 (1) Ownership of PD is released to the process (all threads may use it)
83 after the new thread starts in a joinable state
84 i.e. pthread_create returns a usable pthread_t.
86 (2) Ownership of PD is released to the new thread starting in a detached
89 (3) Ownership of PD is dynamically released to a running thread via
92 (4) Ownership of PD is acquired by the thread which calls pthread_join.
96 The PD->stopped_start and thread_ran variables are used to determine
97 exactly which of the four ownership states we are in and therefore
98 what actions can be taken. For example after (2) we cannot read or
99 write from PD anymore since the thread may no longer exist and the
100 memory may be unmapped.
102 It is important to point out that PD->lock is being used both
103 similar to a one-shot semaphore and subsequently as a mutex. The
104 lock is taken in the parent to force the child to wait, and then the
105 child releases the lock. However, this semaphore-like effect is used
106 only for synchronizing the parent and child. After startup the lock
107 is used like a mutex to create a critical section during which a
108 single owner modifies the thread parameters.
110 The most complicated cases happen during thread startup:
112 (a) If the created thread is in a detached (PTHREAD_CREATE_DETACHED),
113 or joinable (default PTHREAD_CREATE_JOINABLE) state and
114 STOPPED_START is true, then the creating thread has ownership of
115 PD until the PD->lock is released by pthread_create. If any
116 errors occur we are in states (c), (d), or (e) below.
118 (b) If the created thread is in a detached state
119 (PTHREAD_CREATED_DETACHED), and STOPPED_START is false, then the
120 creating thread has ownership of PD until it invokes the OS
121 kernel's thread creation routine. If this routine returns
122 without error, then the created thread owns PD; otherwise, see
125 (c) If the detached thread setup failed and THREAD_RAN is true, then
126 the creating thread releases ownership to the new thread by
127 sending a cancellation signal. All threads set THREAD_RAN to
128 true as quickly as possible after returning from the OS kernel's
129 thread creation routine.
131 (d) If the joinable thread setup failed and THREAD_RAN is true, then
132 then the creating thread retains ownership of PD and must cleanup
133 state. Ownership cannot be released to the process via the
134 return of pthread_create since a non-zero result entails PD is
135 undefined and therefore cannot be joined to free the resources.
136 We privately call pthread_join on the thread to finish handling
137 the resource shutdown (Or at least we should, see bug 19511).
139 (e) If the thread creation failed and THREAD_RAN is false, then the
140 creating thread retains ownership of PD and must cleanup state.
141 No waiting for the new thread is required because it never
144 The nptl_db interface:
146 The interface with nptl_db requires that we enqueue PD into a linked
147 list and then call a function which the debugger will trap. The PD
148 will then be dequeued and control returned to the thread. The caller
149 at the time must have ownership of PD and such ownership remains
150 after control returns to thread. The enqueued PD is removed from the
151 linked list by the nptl_db callback td_thr_event_getmsg. The debugger
152 must ensure that the thread does not resume execution, otherwise
153 ownership of PD may be lost and examining PD will not be possible.
155 Note that the GNU Debugger as of (December 10th 2015) commit
156 c2c2a31fdb228d41ce3db62b268efea04bd39c18 no longer uses
157 td_thr_event_getmsg and several other related nptl_db interfaces. The
158 principal reason for this is that nptl_db does not support non-stop
159 mode where other threads can run concurrently and modify runtime
160 structures currently in use by the debugger and the nptl_db
165 * The create_thread function can never set stopped_start to false.
166 * The created thread can read stopped_start but never write to it.
167 * The variable thread_ran is set some time after the OS thread
168 creation routine returns, how much time after the thread is created
169 is unspecified, but it should be as quickly as possible.
173 /* CREATE THREAD NOTES:
175 createthread.c defines the create_thread function, and two macros:
176 START_THREAD_DEFN and START_THREAD_SELF (see below).
178 create_thread must initialize PD->stopped_start. It should be true
179 if the STOPPED_START parameter is true, or if create_thread needs the
180 new thread to synchronize at startup for some other implementation
181 reason. If STOPPED_START will be true, then create_thread is obliged
182 to lock PD->lock before starting the thread. Then pthread_create
183 unlocks PD->lock which synchronizes-with START_THREAD_DEFN in the
184 child thread which does an acquire/release of PD->lock as the last
185 action before calling the user entry point. The goal of all of this
186 is to ensure that the required initial thread attributes are applied
187 (by the creating thread) before the new thread runs user code. Note
188 that the the functions pthread_getschedparam, pthread_setschedparam,
189 pthread_setschedprio, __pthread_tpp_change_priority, and
190 __pthread_current_priority reuse the same lock, PD->lock, for a
191 similar purpose e.g. synchronizing the setting of similar thread
192 attributes. These functions are never called before the thread is
193 created, so don't participate in startup syncronization, but given
194 that the lock is present already and in the unlocked state, reusing
197 The return value is zero for success or an errno code for failure.
198 If the return value is ENOMEM, that will be translated to EAGAIN,
199 so create_thread need not do that. On failure, *THREAD_RAN should
200 be set to true iff the thread actually started up and then got
201 canceled before calling user code (*PD->start_routine). */
202 static int create_thread (struct pthread
*pd
, const struct pthread_attr
*attr
,
203 bool *stopped_start
, STACK_VARIABLES_PARMS
,
206 #include <createthread.c>
210 __find_in_stack_list (struct pthread
*pd
)
213 struct pthread
*result
= NULL
;
215 lll_lock (stack_cache_lock
, LLL_PRIVATE
);
217 list_for_each (entry
, &stack_used
)
219 struct pthread
*curp
;
221 curp
= list_entry (entry
, struct pthread
, list
);
230 list_for_each (entry
, &__stack_user
)
232 struct pthread
*curp
;
234 curp
= list_entry (entry
, struct pthread
, list
);
242 lll_unlock (stack_cache_lock
, LLL_PRIVATE
);
248 /* Deallocate POSIX thread-local-storage. */
251 __nptl_deallocate_tsd (void)
253 struct pthread
*self
= THREAD_SELF
;
255 /* Maybe no data was ever allocated. This happens often so we have
257 if (THREAD_GETMEM (self
, specific_used
))
267 /* So far no new nonzero data entry. */
268 THREAD_SETMEM (self
, specific_used
, false);
270 for (cnt
= idx
= 0; cnt
< PTHREAD_KEY_1STLEVEL_SIZE
; ++cnt
)
272 struct pthread_key_data
*level2
;
274 level2
= THREAD_GETMEM_NC (self
, specific
, cnt
);
280 for (inner
= 0; inner
< PTHREAD_KEY_2NDLEVEL_SIZE
;
283 void *data
= level2
[inner
].data
;
287 /* Always clear the data. */
288 level2
[inner
].data
= NULL
;
290 /* Make sure the data corresponds to a valid
291 key. This test fails if the key was
292 deallocated and also if it was
293 re-allocated. It is the user's
294 responsibility to free the memory in this
296 if (level2
[inner
].seq
297 == __pthread_keys
[idx
].seq
298 /* It is not necessary to register a destructor
300 && __pthread_keys
[idx
].destr
!= NULL
)
301 /* Call the user-provided destructor. */
302 __pthread_keys
[idx
].destr (data
);
307 idx
+= PTHREAD_KEY_1STLEVEL_SIZE
;
310 if (THREAD_GETMEM (self
, specific_used
) == 0)
311 /* No data has been modified. */
314 /* We only repeat the process a fixed number of times. */
315 while (__builtin_expect (++round
< PTHREAD_DESTRUCTOR_ITERATIONS
, 0));
317 /* Just clear the memory of the first block for reuse. */
318 memset (&THREAD_SELF
->specific_1stblock
, '\0',
319 sizeof (self
->specific_1stblock
));
322 /* Free the memory for the other blocks. */
323 for (cnt
= 1; cnt
< PTHREAD_KEY_1STLEVEL_SIZE
; ++cnt
)
325 struct pthread_key_data
*level2
;
327 level2
= THREAD_GETMEM_NC (self
, specific
, cnt
);
330 /* The first block is allocated as part of the thread
333 THREAD_SETMEM_NC (self
, specific
, cnt
, NULL
);
337 THREAD_SETMEM (self
, specific_used
, false);
342 /* Deallocate a thread's stack after optionally making sure the thread
343 descriptor is still valid. */
345 __free_tcb (struct pthread
*pd
)
347 /* The thread is exiting now. */
348 if (__builtin_expect (atomic_bit_test_set (&pd
->cancelhandling
,
349 TERMINATED_BIT
) == 0, 1))
351 /* Remove the descriptor from the list. */
352 if (DEBUGGING_P
&& __find_in_stack_list (pd
) == NULL
)
353 /* Something is really wrong. The descriptor for a still
354 running thread is gone. */
358 if (__glibc_unlikely (pd
->tpp
!= NULL
))
360 struct priority_protection_data
*tpp
= pd
->tpp
;
366 /* Queue the stack memory block for reuse and exit the process. The
367 kernel will signal via writing to the address returned by
368 QUEUE-STACK when the stack is available. */
369 __deallocate_stack (pd
);
373 /* Local function to start thread and handle cleanup.
374 createthread.c defines the macro START_THREAD_DEFN to the
375 declaration that its create_thread function will refer to, and
376 START_THREAD_SELF to the expression to optimally deliver the new
377 thread's THREAD_SELF value. */
380 struct pthread
*pd
= START_THREAD_SELF
;
382 /* Initialize resolver state pointer. */
385 /* Initialize pointers to locale data. */
388 #ifndef __ASSUME_SET_ROBUST_LIST
389 if (__set_robust_list_avail
>= 0)
392 /* This call should never fail because the initial call in init.c
394 INTERNAL_SYSCALL_CALL (set_robust_list
, &pd
->robust_head
,
395 sizeof (struct robust_list_head
));
398 /* This is where the try/finally block should be created. For
399 compilers without that support we do use setjmp. */
400 struct pthread_unwind_buf unwind_buf
;
403 not_first_call
= setjmp ((struct __jmp_buf_tag
*) unwind_buf
.cancel_jmp_buf
);
405 /* No previous handlers. NB: This must be done after setjmp since the
406 private space in the unwind jump buffer may overlap space used by
407 setjmp to store extra architecture-specific information which is
408 never used by the cancellation-specific __libc_unwind_longjmp.
410 The private space is allowed to overlap because the unwinder never
411 has to return through any of the jumped-to call frames, and thus
412 only a minimum amount of saved data need be stored, and for example,
413 need not include the process signal mask information. This is all
414 an optimization to reduce stack usage when pushing cancellation
416 unwind_buf
.priv
.data
.prev
= NULL
;
417 unwind_buf
.priv
.data
.cleanup
= NULL
;
419 __libc_signal_restore_set (&pd
->sigmask
);
421 /* Allow setxid from now onwards. */
422 if (__glibc_unlikely (atomic_exchange_acq (&pd
->setxid_futex
, 0) == -2))
423 futex_wake (&pd
->setxid_futex
, 1, FUTEX_PRIVATE
);
425 if (__glibc_likely (! not_first_call
))
427 /* Store the new cleanup handler info. */
428 THREAD_SETMEM (pd
, cleanup_jmp_buf
, &unwind_buf
);
430 /* We are either in (a) or (b), and in either case we either own
431 PD already (2) or are about to own PD (1), and so our only
432 restriction would be that we can't free PD until we know we
433 have ownership (see CONCURRENCY NOTES above). */
434 if (__glibc_unlikely (pd
->stopped_start
))
436 int oldtype
= CANCEL_ASYNC ();
438 /* Get the lock the parent locked to force synchronization. */
439 lll_lock (pd
->lock
, LLL_PRIVATE
);
441 /* We have ownership of PD now. */
443 /* And give it up right away. */
444 lll_unlock (pd
->lock
, LLL_PRIVATE
);
446 CANCEL_RESET (oldtype
);
449 LIBC_PROBE (pthread_start
, 3, (pthread_t
) pd
, pd
->start_routine
, pd
->arg
);
451 /* Run the code the user provided. */
455 /* The function pointer of the c11 thread start is cast to an incorrect
456 type on __pthread_create_2_1 call, however it is casted back to correct
457 one so the call behavior is well-defined (it is assumed that pointers
458 to void are able to represent all values of int. */
459 int (*start
)(void*) = (int (*) (void*)) pd
->start_routine
;
460 ret
= (void*) (uintptr_t) start (pd
->arg
);
463 ret
= pd
->start_routine (pd
->arg
);
464 THREAD_SETMEM (pd
, result
, ret
);
467 /* Call destructors for the thread_local TLS variables. */
469 if (&__call_tls_dtors
!= NULL
)
473 /* Run the destructor for the thread-local data. */
474 __nptl_deallocate_tsd ();
476 /* Clean up any state libc stored in thread-local variables. */
477 __libc_thread_freeres ();
479 /* If this is the last thread we terminate the process now. We
480 do not notify the debugger, it might just irritate it if there
481 is no thread left. */
482 if (__glibc_unlikely (atomic_decrement_and_test (&__nptl_nthreads
)))
483 /* This was the last thread. */
486 /* Report the death of the thread if this is wanted. */
487 if (__glibc_unlikely (pd
->report_events
))
489 /* See whether TD_DEATH is in any of the mask. */
490 const int idx
= __td_eventword (TD_DEATH
);
491 const uint32_t mask
= __td_eventmask (TD_DEATH
);
493 if ((mask
& (__nptl_threads_events
.event_bits
[idx
]
494 | pd
->eventbuf
.eventmask
.event_bits
[idx
])) != 0)
496 /* Yep, we have to signal the death. Add the descriptor to
497 the list but only if it is not already on it. */
498 if (pd
->nextevent
== NULL
)
500 pd
->eventbuf
.eventnum
= TD_DEATH
;
501 pd
->eventbuf
.eventdata
= pd
;
504 pd
->nextevent
= __nptl_last_event
;
505 while (atomic_compare_and_exchange_bool_acq (&__nptl_last_event
,
509 /* Now call the function which signals the event. See
510 CONCURRENCY NOTES for the nptl_db interface comments. */
511 __nptl_death_event ();
515 /* The thread is exiting now. Don't set this bit until after we've hit
516 the event-reporting breakpoint, so that td_thr_get_info on us while at
517 the breakpoint reports TD_THR_RUN state rather than TD_THR_ZOMBIE. */
518 atomic_bit_set (&pd
->cancelhandling
, EXITING_BIT
);
520 #ifndef __ASSUME_SET_ROBUST_LIST
521 /* If this thread has any robust mutexes locked, handle them now. */
522 # if __PTHREAD_MUTEX_HAVE_PREV
523 void *robust
= pd
->robust_head
.list
;
525 __pthread_slist_t
*robust
= pd
->robust_list
.__next
;
527 /* We let the kernel do the notification if it is able to do so.
528 If we have to do it here there for sure are no PI mutexes involved
529 since the kernel support for them is even more recent. */
530 if (__set_robust_list_avail
< 0
531 && __builtin_expect (robust
!= (void *) &pd
->robust_head
, 0))
535 struct __pthread_mutex_s
*this = (struct __pthread_mutex_s
*)
536 ((char *) robust
- offsetof (struct __pthread_mutex_s
,
538 robust
= *((void **) robust
);
540 # if __PTHREAD_MUTEX_HAVE_PREV
541 this->__list
.__prev
= NULL
;
543 this->__list
.__next
= NULL
;
545 atomic_or (&this->__lock
, FUTEX_OWNER_DIED
);
546 futex_wake ((unsigned int *) &this->__lock
, 1,
547 /* XYZ */ FUTEX_SHARED
);
549 while (robust
!= (void *) &pd
->robust_head
);
554 advise_stack_range (pd
->stackblock
, pd
->stackblock_size
, (uintptr_t) pd
,
557 if (__glibc_unlikely (pd
->cancelhandling
& SETXID_BITMASK
))
559 /* Some other thread might call any of the setXid functions and expect
560 us to reply. In this case wait until we did that. */
562 /* XXX This differs from the typical futex_wait_simple pattern in that
563 the futex_wait condition (setxid_futex) is different from the
564 condition used in the surrounding loop (cancelhandling). We need
565 to check and document why this is correct. */
566 futex_wait_simple (&pd
->setxid_futex
, 0, FUTEX_PRIVATE
);
567 while (pd
->cancelhandling
& SETXID_BITMASK
);
569 /* Reset the value so that the stack can be reused. */
570 pd
->setxid_futex
= 0;
573 /* If the thread is detached free the TCB. */
574 if (IS_DETACHED (pd
))
578 /* We cannot call '_exit' here. '_exit' will terminate the process.
580 The 'exit' implementation in the kernel will signal when the
581 process is really dead since 'clone' got passed the CLONE_CHILD_CLEARTID
582 flag. The 'tid' field in the TCB will be set to zero.
584 The exit code is zero since in case all threads exit by calling
585 'pthread_exit' the exit status must be 0 (zero). */
592 /* Return true iff obliged to report TD_CREATE events. */
594 report_thread_creation (struct pthread
*pd
)
596 if (__glibc_unlikely (THREAD_GETMEM (THREAD_SELF
, report_events
)))
598 /* The parent thread is supposed to report events.
599 Check whether the TD_CREATE event is needed, too. */
600 const size_t idx
= __td_eventword (TD_CREATE
);
601 const uint32_t mask
= __td_eventmask (TD_CREATE
);
603 return ((mask
& (__nptl_threads_events
.event_bits
[idx
]
604 | pd
->eventbuf
.eventmask
.event_bits
[idx
])) != 0);
611 __pthread_create_2_1 (pthread_t
*newthread
, const pthread_attr_t
*attr
,
612 void *(*start_routine
) (void *), void *arg
)
616 /* Avoid a data race in the multi-threaded case. */
617 if (__libc_single_threaded
)
618 __libc_single_threaded
= 0;
620 const struct pthread_attr
*iattr
= (struct pthread_attr
*) attr
;
621 union pthread_attr_transparent default_attr
;
622 bool destroy_default_attr
= false;
623 bool c11
= (attr
== ATTR_C11_THREAD
);
624 if (iattr
== NULL
|| c11
)
626 int ret
= __pthread_getattr_default_np (&default_attr
.external
);
629 destroy_default_attr
= true;
630 iattr
= &default_attr
.internal
;
633 struct pthread
*pd
= NULL
;
634 int err
= ALLOCATE_STACK (iattr
, &pd
);
637 if (__glibc_unlikely (err
!= 0))
638 /* Something went wrong. Maybe a parameter of the attributes is
639 invalid or we could not allocate memory. Note we have to
640 translate error codes. */
642 retval
= err
== ENOMEM
? EAGAIN
: err
;
647 /* Initialize the TCB. All initializations with zero should be
648 performed in 'get_cached_stack'. This way we avoid doing this if
649 the stack freshly allocated with 'mmap'. */
652 /* Reference to the TCB itself. */
653 pd
->header
.self
= pd
;
655 /* Self-reference for TLS. */
659 /* Store the address of the start routine and the parameter. Since
660 we do not start the function directly the stillborn thread will
661 get the information from its thread descriptor. */
662 pd
->start_routine
= start_routine
;
666 /* Copy the thread attribute flags. */
667 struct pthread
*self
= THREAD_SELF
;
668 pd
->flags
= ((iattr
->flags
& ~(ATTR_FLAG_SCHED_SET
| ATTR_FLAG_POLICY_SET
))
669 | (self
->flags
& (ATTR_FLAG_SCHED_SET
| ATTR_FLAG_POLICY_SET
)));
671 /* Initialize the field for the ID of the thread which is waiting
672 for us. This is a self-reference in case the thread is created
674 pd
->joinid
= iattr
->flags
& ATTR_FLAG_DETACHSTATE
? pd
: NULL
;
676 /* The debug events are inherited from the parent. */
677 pd
->eventbuf
= self
->eventbuf
;
680 /* Copy the parent's scheduling parameters. The flags will say what
681 is valid and what is not. */
682 pd
->schedpolicy
= self
->schedpolicy
;
683 pd
->schedparam
= self
->schedparam
;
685 /* Copy the stack guard canary. */
686 #ifdef THREAD_COPY_STACK_GUARD
687 THREAD_COPY_STACK_GUARD (pd
);
690 /* Copy the pointer guard value. */
691 #ifdef THREAD_COPY_POINTER_GUARD
692 THREAD_COPY_POINTER_GUARD (pd
);
696 tls_setup_tcbhead (pd
);
698 /* Verify the sysinfo bits were copied in allocate_stack if needed. */
699 #ifdef NEED_DL_SYSINFO
700 CHECK_THREAD_SYSINFO (pd
);
703 /* Determine scheduling parameters for the thread. */
704 if (__builtin_expect ((iattr
->flags
& ATTR_FLAG_NOTINHERITSCHED
) != 0, 0)
705 && (iattr
->flags
& (ATTR_FLAG_SCHED_SET
| ATTR_FLAG_POLICY_SET
)) != 0)
707 /* Use the scheduling parameters the user provided. */
708 if (iattr
->flags
& ATTR_FLAG_POLICY_SET
)
710 pd
->schedpolicy
= iattr
->schedpolicy
;
711 pd
->flags
|= ATTR_FLAG_POLICY_SET
;
713 if (iattr
->flags
& ATTR_FLAG_SCHED_SET
)
715 /* The values were validated in pthread_attr_setschedparam. */
716 pd
->schedparam
= iattr
->schedparam
;
717 pd
->flags
|= ATTR_FLAG_SCHED_SET
;
720 if ((pd
->flags
& (ATTR_FLAG_SCHED_SET
| ATTR_FLAG_POLICY_SET
))
721 != (ATTR_FLAG_SCHED_SET
| ATTR_FLAG_POLICY_SET
))
722 collect_default_sched (pd
);
725 if (__glibc_unlikely (__nptl_nthreads
== 1))
728 /* Pass the descriptor to the caller. */
729 *newthread
= (pthread_t
) pd
;
731 LIBC_PROBE (pthread_create
, 4, newthread
, attr
, start_routine
, arg
);
733 /* One more thread. We cannot have the thread do this itself, since it
734 might exist but not have been scheduled yet by the time we've returned
735 and need to check the value to behave correctly. We must do it before
736 creating the thread, in case it does get scheduled first and then
737 might mistakenly think it was the only thread. In the failure case,
738 we momentarily store a false value; this doesn't matter because there
739 is no kosher thing a signal handler interrupting us right here can do
740 that cares whether the thread count is correct. */
741 atomic_increment (&__nptl_nthreads
);
743 /* Our local value of stopped_start and thread_ran can be accessed at
744 any time. The PD->stopped_start may only be accessed if we have
745 ownership of PD (see CONCURRENCY NOTES above). */
746 bool stopped_start
= false; bool thread_ran
= false;
748 /* Block all signals, so that the new thread starts out with
749 signals disabled. This avoids race conditions in the thread
751 sigset_t original_sigmask
;
752 __libc_signal_block_all (&original_sigmask
);
754 if (iattr
->extension
!= NULL
&& iattr
->extension
->sigmask_set
)
755 /* Use the signal mask in the attribute. The internal signals
756 have already been filtered by the public
757 pthread_attr_setsigmask_np interface. */
758 pd
->sigmask
= iattr
->extension
->sigmask
;
761 /* Conceptually, the new thread needs to inherit the signal mask
762 of this thread. Therefore, it needs to restore the saved
763 signal mask of this thread, so save it in the startup
765 pd
->sigmask
= original_sigmask
;
767 /* Reset the cancellation signal mask in case this thread is
768 running cancellation. */
769 __sigdelset (&pd
->sigmask
, SIGCANCEL
);
772 /* Start the thread. */
773 if (__glibc_unlikely (report_thread_creation (pd
)))
775 stopped_start
= true;
777 /* We always create the thread stopped at startup so we can
778 notify the debugger. */
779 retval
= create_thread (pd
, iattr
, &stopped_start
,
780 STACK_VARIABLES_ARGS
, &thread_ran
);
783 /* We retain ownership of PD until (a) (see CONCURRENCY NOTES
786 /* Assert stopped_start is true in both our local copy and the
788 assert (stopped_start
);
789 assert (pd
->stopped_start
);
791 /* Now fill in the information about the new thread in
792 the newly created thread's data structure. We cannot let
793 the new thread do this since we don't know whether it was
794 already scheduled when we send the event. */
795 pd
->eventbuf
.eventnum
= TD_CREATE
;
796 pd
->eventbuf
.eventdata
= pd
;
798 /* Enqueue the descriptor. */
800 pd
->nextevent
= __nptl_last_event
;
801 while (atomic_compare_and_exchange_bool_acq (&__nptl_last_event
,
805 /* Now call the function which signals the event. See
806 CONCURRENCY NOTES for the nptl_db interface comments. */
807 __nptl_create_event ();
811 retval
= create_thread (pd
, iattr
, &stopped_start
,
812 STACK_VARIABLES_ARGS
, &thread_ran
);
814 /* Return to the previous signal mask, after creating the new
816 __libc_signal_restore_set (&original_sigmask
);
818 if (__glibc_unlikely (retval
!= 0))
821 /* State (c) or (d) and we may not have PD ownership (see
822 CONCURRENCY NOTES above). We can assert that STOPPED_START
823 must have been true because thread creation didn't fail, but
824 thread attribute setting did. */
825 /* See bug 19511 which explains why doing nothing here is a
826 resource leak for a joinable thread. */
827 assert (stopped_start
);
830 /* State (e) and we have ownership of PD (see CONCURRENCY
833 /* Oops, we lied for a second. */
834 atomic_decrement (&__nptl_nthreads
);
836 /* Perhaps a thread wants to change the IDs and is waiting for this
838 if (__glibc_unlikely (atomic_exchange_acq (&pd
->setxid_futex
, 0)
840 futex_wake (&pd
->setxid_futex
, 1, FUTEX_PRIVATE
);
842 /* Free the resources. */
843 __deallocate_stack (pd
);
846 /* We have to translate error codes. */
847 if (retval
== ENOMEM
)
852 /* We don't know if we have PD ownership. Once we check the local
853 stopped_start we'll know if we're in state (a) or (b) (see
854 CONCURRENCY NOTES above). */
856 /* State (a), we own PD. The thread blocked on this lock either
857 because we're doing TD_CREATE event reporting, or for some
858 other reason that create_thread chose. Now let it run
860 lll_unlock (pd
->lock
, LLL_PRIVATE
);
862 /* We now have for sure more than one thread. The main thread might
863 not yet have the flag set. No need to set the global variable
864 again if this is what we use. */
865 THREAD_SETMEM (THREAD_SELF
, header
.multiple_threads
, 1);
869 if (destroy_default_attr
)
870 __pthread_attr_destroy (&default_attr
.external
);
874 versioned_symbol (libpthread
, __pthread_create_2_1
, pthread_create
, GLIBC_2_1
);
877 #if SHLIB_COMPAT(libpthread, GLIBC_2_0, GLIBC_2_1)
879 __pthread_create_2_0 (pthread_t
*newthread
, const pthread_attr_t
*attr
,
880 void *(*start_routine
) (void *), void *arg
)
882 /* The ATTR attribute is not really of type `pthread_attr_t *'. It has
883 the old size and access to the new members might crash the program.
884 We convert the struct now. */
885 struct pthread_attr new_attr
;
889 struct pthread_attr
*iattr
= (struct pthread_attr
*) attr
;
890 size_t ps
= __getpagesize ();
892 /* Copy values from the user-provided attributes. */
893 new_attr
.schedparam
= iattr
->schedparam
;
894 new_attr
.schedpolicy
= iattr
->schedpolicy
;
895 new_attr
.flags
= iattr
->flags
;
897 /* Fill in default values for the fields not present in the old
899 new_attr
.guardsize
= ps
;
900 new_attr
.stackaddr
= NULL
;
901 new_attr
.stacksize
= 0;
902 new_attr
.extension
= NULL
;
904 /* We will pass this value on to the real implementation. */
905 attr
= (pthread_attr_t
*) &new_attr
;
908 return __pthread_create_2_1 (newthread
, attr
, start_routine
, arg
);
910 compat_symbol (libpthread
, __pthread_create_2_0
, pthread_create
,
914 /* Information for libthread_db. */
916 #include "../nptl_db/db_info.c"
918 /* If pthread_create is present, libgcc_eh.a and libsupc++.a expects some other POSIX thread
919 functions to be present as well. */
920 PTHREAD_STATIC_FN_REQUIRE (__pthread_mutex_lock
)
921 PTHREAD_STATIC_FN_REQUIRE (__pthread_mutex_trylock
)
922 PTHREAD_STATIC_FN_REQUIRE (__pthread_mutex_unlock
)
924 PTHREAD_STATIC_FN_REQUIRE (__pthread_once
)
925 PTHREAD_STATIC_FN_REQUIRE (__pthread_cancel
)
927 PTHREAD_STATIC_FN_REQUIRE (__pthread_key_create
)
928 PTHREAD_STATIC_FN_REQUIRE (__pthread_key_delete
)
929 PTHREAD_STATIC_FN_REQUIRE (__pthread_setspecific
)
930 PTHREAD_STATIC_FN_REQUIRE (__pthread_getspecific
)