Fix for CVE-2017-1000366 in glibc
[AGL/meta-agl.git] / meta-agl-bsp / meta-core / recipes-core / glibc / files / 0028-Bug-20116-Fix-use-after-free-in-pthread_create.patch
1 From e7ba24f05d86acf7072e066ea6d7b235a106688c Mon Sep 17 00:00:00 2001
2 From: Carlos O'Donell <carlos@redhat.com>
3 Date: Sat, 28 Jan 2017 19:13:34 -0500
4 Subject: [PATCH] Bug 20116: Fix use after free in pthread_create()
5
6 The commit documents the ownership rules around 'struct pthread' and
7 when a thread can read or write to the descriptor. With those ownership
8 rules in place it becomes obvious that pd->stopped_start should not be
9 touched in several of the paths during thread startup, particularly so
10 for detached threads. In the case of detached threads, between the time
11 the thread is created by the OS kernel and the creating thread checks
12 pd->stopped_start, the detached thread might have already exited and the
13 memory for pd unmapped. As a regression test we add a simple test which
14 exercises this exact case by quickly creating detached threads with
15 large enough stacks to ensure the thread stack cache is bypassed and the
16 stacks are unmapped. Before the fix the testcase segfaults, after the
17 fix it works correctly and completes without issue.
18
19 For a detailed discussion see:
20 https://www.sourceware.org/ml/libc-alpha/2017-01/msg00505.html
21
22 (cherry-picked from commit f8bf15febcaf137bbec5a61101e88cd5a9d56ca8)
23
24 Upstream-Status: Backport [master]
25 Signed-off-by: Yuanjie Huang <yuanjie.huang@windriver.com>
26 ---
27  ChangeLog                              |  23 ++++
28  nptl/Makefile                          |   3 +-
29  nptl/createthread.c                    |  10 +-
30  nptl/pthread_create.c                  | 207 +++++++++++++++++++++++++++------
31  nptl/pthread_getschedparam.c           |   1 +
32  nptl/pthread_setschedparam.c           |   1 +
33  nptl/pthread_setschedprio.c            |   1 +
34  nptl/tpp.c                             |   2 +
35  nptl/tst-create-detached.c             | 137 ++++++++++++++++++++++
36  sysdeps/nacl/createthread.c            |  10 +-
37  sysdeps/unix/sysv/linux/createthread.c |  16 ++-
38  11 files changed, 356 insertions(+), 55 deletions(-)
39  create mode 100644 nptl/tst-create-detached.c
40
41 diff --git a/nptl/Makefile b/nptl/Makefile
42 index 0d8aadebed..7dec4edb53 100644
43 --- a/nptl/Makefile
44 +++ b/nptl/Makefile
45 @@ -290,7 +290,8 @@ tests = tst-typesizes \
46         tst-initializers1 $(addprefix tst-initializers1-,\
47                             c89 gnu89 c99 gnu99 c11 gnu11) \
48         tst-bad-schedattr \
49 -       tst-thread_local1 tst-mutex-errorcheck tst-robust10
50 +       tst-thread_local1 tst-mutex-errorcheck tst-robust10 \
51 +       tst-create-detached \
52  xtests = tst-setuid1 tst-setuid1-static tst-setuid2 \
53         tst-mutexpp1 tst-mutexpp6 tst-mutexpp10
54  test-srcs = tst-oddstacklimit
55 diff --git a/nptl/createthread.c b/nptl/createthread.c
56 index ba2f9c7167..328f85865d 100644
57 --- a/nptl/createthread.c
58 +++ b/nptl/createthread.c
59 @@ -25,16 +25,14 @@
60  
61  static int
62  create_thread (struct pthread *pd, const struct pthread_attr *attr,
63 -              bool stopped_start, STACK_VARIABLES_PARMS, bool *thread_ran)
64 +              bool *stopped_start, STACK_VARIABLES_PARMS, bool *thread_ran)
65  {
66    /* If the implementation needs to do some tweaks to the thread after
67       it has been created at the OS level, it can set STOPPED_START here.  */
68  
69 -  pd->stopped_start = stopped_start;
70 -  if (__glibc_unlikely (stopped_start))
71 -    /* We make sure the thread does not run far by forcing it to get a
72 -       lock.  We lock it here too so that the new thread cannot continue
73 -       until we tell it to.  */
74 +  pd->stopped_start = *stopped_start;
75 +  if (__glibc_unlikely (*stopped_start))
76 +    /* See CONCURRENCY NOTES in nptl/pthread_create.c.  */
77      lll_lock (pd->lock, LLL_PRIVATE);
78  
79    return ENOSYS;
80 diff --git a/nptl/pthread_create.c b/nptl/pthread_create.c
81 index a834063ad5..44b17bec86 100644
82 --- a/nptl/pthread_create.c
83 +++ b/nptl/pthread_create.c
84 @@ -54,25 +54,141 @@ unsigned int __nptl_nthreads = 1;
85  /* Code to allocate and deallocate a stack.  */
86  #include "allocatestack.c"
87  
88 -/* createthread.c defines this function, and two macros:
89 +/* CONCURRENCY NOTES:
90 +
91 +   Understanding who is the owner of the 'struct pthread' or 'PD'
92 +   (refers to the value of the 'struct pthread *pd' function argument)
93 +   is critically important in determining exactly which operations are
94 +   allowed and which are not and when, particularly when it comes to the
95 +   implementation of pthread_create, pthread_join, pthread_detach, and
96 +   other functions which all operate on PD.
97 +
98 +   The owner of PD is responsible for freeing the final resources
99 +   associated with PD, and may examine the memory underlying PD at any
100 +   point in time until it frees it back to the OS or to reuse by the
101 +   runtime.
102 +
103 +   The thread which calls pthread_create is called the creating thread.
104 +   The creating thread begins as the owner of PD.
105 +
106 +   During startup the new thread may examine PD in coordination with the
107 +   owner thread (which may be itself).
108 +
109 +   The four cases of ownership transfer are:
110 +
111 +   (1) Ownership of PD is released to the process (all threads may use it)
112 +       after the new thread starts in a joinable state
113 +       i.e. pthread_create returns a usable pthread_t.
114 +
115 +   (2) Ownership of PD is released to the new thread starting in a detached
116 +       state.
117 +
118 +   (3) Ownership of PD is dynamically released to a running thread via
119 +       pthread_detach.
120 +
121 +   (4) Ownership of PD is acquired by the thread which calls pthread_join.
122 +
123 +   Implementation notes:
124 +
125 +   The PD->stopped_start and thread_ran variables are used to determine
126 +   exactly which of the four ownership states we are in and therefore
127 +   what actions can be taken.  For example after (2) we cannot read or
128 +   write from PD anymore since the thread may no longer exist and the
129 +   memory may be unmapped.  The most complicated cases happen during
130 +   thread startup:
131 +
132 +   (a) If the created thread is in a detached (PTHREAD_CREATE_DETACHED),
133 +       or joinable (default PTHREAD_CREATE_JOINABLE) state and
134 +       STOPPED_START is true, then the creating thread has ownership of
135 +       PD until the PD->lock is released by pthread_create.  If any
136 +       errors occur we are in states (c), (d), or (e) below.
137 +
138 +   (b) If the created thread is in a detached state
139 +       (PTHREAD_CREATED_DETACHED), and STOPPED_START is false, then the
140 +       creating thread has ownership of PD until it invokes the OS
141 +       kernel's thread creation routine.  If this routine returns
142 +       without error, then the created thread owns PD; otherwise, see
143 +       (c) and (e) below.
144 +
145 +   (c) If the detached thread setup failed and THREAD_RAN is true, then
146 +       the creating thread releases ownership to the new thread by
147 +       sending a cancellation signal.  All threads set THREAD_RAN to
148 +       true as quickly as possible after returning from the OS kernel's
149 +       thread creation routine.
150 +
151 +   (d) If the joinable thread setup failed and THREAD_RAN is true, then
152 +       then the creating thread retains ownership of PD and must cleanup
153 +       state.  Ownership cannot be released to the process via the
154 +       return of pthread_create since a non-zero result entails PD is
155 +       undefined and therefore cannot be joined to free the resources.
156 +       We privately call pthread_join on the thread to finish handling
157 +       the resource shutdown (Or at least we should, see bug 19511).
158 +
159 +   (e) If the thread creation failed and THREAD_RAN is false, then the
160 +       creating thread retains ownership of PD and must cleanup state.
161 +       No waiting for the new thread is required because it never
162 +       started.
163 +
164 +   The nptl_db interface:
165 +
166 +   The interface with nptl_db requires that we enqueue PD into a linked
167 +   list and then call a function which the debugger will trap.  The PD
168 +   will then be dequeued and control returned to the thread.  The caller
169 +   at the time must have ownership of PD and such ownership remains
170 +   after control returns to thread. The enqueued PD is removed from the
171 +   linked list by the nptl_db callback td_thr_event_getmsg.  The debugger
172 +   must ensure that the thread does not resume execution, otherwise
173 +   ownership of PD may be lost and examining PD will not be possible.
174 +
175 +   Note that the GNU Debugger as of (December 10th 2015) commit
176 +   c2c2a31fdb228d41ce3db62b268efea04bd39c18 no longer uses
177 +   td_thr_event_getmsg and several other related nptl_db interfaces. The
178 +   principal reason for this is that nptl_db does not support non-stop
179 +   mode where other threads can run concurrently and modify runtime
180 +   structures currently in use by the debugger and the nptl_db
181 +   interface.
182 +
183 +   Axioms:
184 +
185 +   * The create_thread function can never set stopped_start to false.
186 +   * The created thread can read stopped_start but never write to it.
187 +   * The variable thread_ran is set some time after the OS thread
188 +     creation routine returns, how much time after the thread is created
189 +     is unspecified, but it should be as quickly as possible.
190 +
191 +*/
192 +
193 +/* CREATE THREAD NOTES:
194 +
195 +   createthread.c defines the create_thread function, and two macros:
196     START_THREAD_DEFN and START_THREAD_SELF (see below).
197  
198 -   create_thread is obliged to initialize PD->stopped_start.  It
199 -   should be true if the STOPPED_START parameter is true, or if
200 -   create_thread needs the new thread to synchronize at startup for
201 -   some other implementation reason.  If PD->stopped_start will be
202 -   true, then create_thread is obliged to perform the operation
203 -   "lll_lock (PD->lock, LLL_PRIVATE)" before starting the thread.
204 +   create_thread must initialize PD->stopped_start.  It should be true
205 +   if the STOPPED_START parameter is true, or if create_thread needs the
206 +   new thread to synchronize at startup for some other implementation
207 +   reason.  If STOPPED_START will be true, then create_thread is obliged
208 +   to lock PD->lock before starting the thread.  Then pthread_create
209 +   unlocks PD->lock which synchronizes-with START_THREAD_DEFN in the
210 +   child thread which does an acquire/release of PD->lock as the last
211 +   action before calling the user entry point.  The goal of all of this
212 +   is to ensure that the required initial thread attributes are applied
213 +   (by the creating thread) before the new thread runs user code.  Note
214 +   that the the functions pthread_getschedparam, pthread_setschedparam,
215 +   pthread_setschedprio, __pthread_tpp_change_priority, and
216 +   __pthread_current_priority reuse the same lock, PD->lock, for a
217 +   similar purpose e.g. synchronizing the setting of similar thread
218 +   attributes.  These functions are never called before the thread is
219 +   created, so don't participate in startup syncronization, but given
220 +   that the lock is present already and in the unlocked state, reusing
221 +   it saves space.
222  
223     The return value is zero for success or an errno code for failure.
224     If the return value is ENOMEM, that will be translated to EAGAIN,
225     so create_thread need not do that.  On failure, *THREAD_RAN should
226     be set to true iff the thread actually started up and then got
227 -   cancelled before calling user code (*PD->start_routine), in which
228 -   case it is responsible for doing its own cleanup.  */
229 -
230 +   canceled before calling user code (*PD->start_routine).  */
231  static int create_thread (struct pthread *pd, const struct pthread_attr *attr,
232 -                         bool stopped_start, STACK_VARIABLES_PARMS,
233 +                         bool *stopped_start, STACK_VARIABLES_PARMS,
234                           bool *thread_ran);
235  
236  #include <createthread.c>
237 @@ -314,12 +430,19 @@ START_THREAD_DEFN
238        /* Store the new cleanup handler info.  */
239        THREAD_SETMEM (pd, cleanup_jmp_buf, &unwind_buf);
240  
241 +      /* We are either in (a) or (b), and in either case we either own
242 +         PD already (2) or are about to own PD (1), and so our only
243 +        restriction would be that we can't free PD until we know we
244 +        have ownership (see CONCURRENCY NOTES above).  */
245        if (__glibc_unlikely (pd->stopped_start))
246         {
247           int oldtype = CANCEL_ASYNC ();
248  
249           /* Get the lock the parent locked to force synchronization.  */
250           lll_lock (pd->lock, LLL_PRIVATE);
251 +
252 +         /* We have ownership of PD now.  */
253 +
254           /* And give it up right away.  */
255           lll_unlock (pd->lock, LLL_PRIVATE);
256  
257 @@ -378,7 +501,8 @@ START_THREAD_DEFN
258                                                            pd, pd->nextevent));
259             }
260  
261 -         /* Now call the function to signal the event.  */
262 +         /* Now call the function which signals the event.  See
263 +            CONCURRENCY NOTES for the nptl_db interface comments.  */
264           __nptl_death_event ();
265         }
266      }
267 @@ -642,19 +766,28 @@ __pthread_create_2_1 (pthread_t *newthread, const pthread_attr_t *attr,
268       that cares whether the thread count is correct.  */
269    atomic_increment (&__nptl_nthreads);
270  
271 -  bool thread_ran = false;
272 +  /* Our local value of stopped_start and thread_ran can be accessed at
273 +     any time. The PD->stopped_start may only be accessed if we have
274 +     ownership of PD (see CONCURRENCY NOTES above).  */
275 +  bool stopped_start = false; bool thread_ran = false;
276  
277    /* Start the thread.  */
278    if (__glibc_unlikely (report_thread_creation (pd)))
279      {
280 -      /* Create the thread.  We always create the thread stopped
281 -        so that it does not get far before we tell the debugger.  */
282 -      retval = create_thread (pd, iattr, true, STACK_VARIABLES_ARGS,
283 -                             &thread_ran);
284 +      stopped_start = true;
285 +
286 +      /* We always create the thread stopped at startup so we can
287 +        notify the debugger.  */
288 +      retval = create_thread (pd, iattr, &stopped_start,
289 +                             STACK_VARIABLES_ARGS, &thread_ran);
290        if (retval == 0)
291         {
292 -         /* create_thread should have set this so that the logic below can
293 -            test it.  */
294 +         /* We retain ownership of PD until (a) (see CONCURRENCY NOTES
295 +            above).  */
296 +
297 +         /* Assert stopped_start is true in both our local copy and the
298 +            PD copy.  */
299 +         assert (stopped_start);
300           assert (pd->stopped_start);
301  
302           /* Now fill in the information about the new thread in
303 @@ -671,26 +804,30 @@ __pthread_create_2_1 (pthread_t *newthread, const pthread_attr_t *attr,
304                                                        pd, pd->nextevent)
305                  != 0);
306  
307 -         /* Now call the function which signals the event.  */
308 +         /* Now call the function which signals the event.  See
309 +            CONCURRENCY NOTES for the nptl_db interface comments.  */
310           __nptl_create_event ();
311         }
312      }
313    else
314 -    retval = create_thread (pd, iattr, false, STACK_VARIABLES_ARGS,
315 -                           &thread_ran);
316 +    retval = create_thread (pd, iattr, &stopped_start,
317 +                           STACK_VARIABLES_ARGS, &thread_ran);
318  
319    if (__glibc_unlikely (retval != 0))
320      {
321 -      /* If thread creation "failed", that might mean that the thread got
322 -        created and ran a little--short of running user code--but then
323 -        create_thread cancelled it.  In that case, the thread will do all
324 -        its own cleanup just like a normal thread exit after a successful
325 -        creation would do.  */
326 -
327        if (thread_ran)
328 -       assert (pd->stopped_start);
329 +       /* State (c) or (d) and we may not have PD ownership (see
330 +          CONCURRENCY NOTES above).  We can assert that STOPPED_START
331 +          must have been true because thread creation didn't fail, but
332 +          thread attribute setting did.  */
333 +       /* See bug 19511 which explains why doing nothing here is a
334 +          resource leak for a joinable thread.  */
335 +       assert (stopped_start);
336        else
337         {
338 +         /* State (e) and we have ownership of PD (see CONCURRENCY
339 +            NOTES above).  */
340 +
341           /* Oops, we lied for a second.  */
342           atomic_decrement (&__nptl_nthreads);
343  
344 @@ -710,10 +847,14 @@ __pthread_create_2_1 (pthread_t *newthread, const pthread_attr_t *attr,
345      }
346    else
347      {
348 -      if (pd->stopped_start)
349 -       /* The thread blocked on this lock either because we're doing TD_CREATE
350 -          event reporting, or for some other reason that create_thread chose.
351 -          Now let it run free.  */
352 +      /* We don't know if we have PD ownership.  Once we check the local
353 +         stopped_start we'll know if we're in state (a) or (b) (see
354 +        CONCURRENCY NOTES above).  */
355 +      if (stopped_start)
356 +       /* State (a), we own PD. The thread blocked on this lock either
357 +          because we're doing TD_CREATE event reporting, or for some
358 +          other reason that create_thread chose.  Now let it run
359 +          free.  */
360         lll_unlock (pd->lock, LLL_PRIVATE);
361  
362        /* We now have for sure more than one thread.  The main thread might
363 diff --git a/nptl/pthread_getschedparam.c b/nptl/pthread_getschedparam.c
364 index b887881baf..de71171a08 100644
365 --- a/nptl/pthread_getschedparam.c
366 +++ b/nptl/pthread_getschedparam.c
367 @@ -35,6 +35,7 @@ __pthread_getschedparam (pthread_t threadid, int *policy,
368  
369    int result = 0;
370  
371 +  /* See CREATE THREAD NOTES in nptl/pthread_create.c.  */
372    lll_lock (pd->lock, LLL_PRIVATE);
373  
374    /* The library is responsible for maintaining the values at all
375 diff --git a/nptl/pthread_setschedparam.c b/nptl/pthread_setschedparam.c
376 index dfb52b9dbf..dcb520f1c8 100644
377 --- a/nptl/pthread_setschedparam.c
378 +++ b/nptl/pthread_setschedparam.c
379 @@ -36,6 +36,7 @@ __pthread_setschedparam (pthread_t threadid, int policy,
380  
381    int result = 0;
382  
383 +  /* See CREATE THREAD NOTES in nptl/pthread_create.c.  */
384    lll_lock (pd->lock, LLL_PRIVATE);
385  
386    struct sched_param p;
387 diff --git a/nptl/pthread_setschedprio.c b/nptl/pthread_setschedprio.c
388 index cefc6481d6..8134b50560 100644
389 --- a/nptl/pthread_setschedprio.c
390 +++ b/nptl/pthread_setschedprio.c
391 @@ -38,6 +38,7 @@ pthread_setschedprio (pthread_t threadid, int prio)
392    struct sched_param param;
393    param.sched_priority = prio;
394  
395 +  /* See CREATE THREAD NOTES in nptl/pthread_create.c.  */
396    lll_lock (pd->lock, LLL_PRIVATE);
397  
398    /* If the thread should have higher priority because of some
399 diff --git a/nptl/tpp.c b/nptl/tpp.c
400 index e175bf4d53..223bd6bbee 100644
401 --- a/nptl/tpp.c
402 +++ b/nptl/tpp.c
403 @@ -114,6 +114,7 @@ __pthread_tpp_change_priority (int previous_prio, int new_prio)
404    if (priomax == newpriomax)
405      return 0;
406  
407 +  /* See CREATE THREAD NOTES in nptl/pthread_create.c.  */
408    lll_lock (self->lock, LLL_PRIVATE);
409  
410    tpp->priomax = newpriomax;
411 @@ -165,6 +166,7 @@ __pthread_current_priority (void)
412  
413    int result = 0;
414  
415 +  /* See CREATE THREAD NOTES in nptl/pthread_create.c.  */
416    lll_lock (self->lock, LLL_PRIVATE);
417  
418    if ((self->flags & ATTR_FLAG_SCHED_SET) == 0)
419 diff --git a/nptl/tst-create-detached.c b/nptl/tst-create-detached.c
420 new file mode 100644
421 index 0000000000..ea93e441c7
422 --- /dev/null
423 +++ b/nptl/tst-create-detached.c
424 @@ -0,0 +1,137 @@
425 +/* Bug 20116: Test rapid creation of detached threads.
426 +   Copyright (C) 2017 Free Software Foundation, Inc.
427 +   This file is part of the GNU C Library.
428 +
429 +   The GNU C Library is free software; you can redistribute it and/or
430 +   modify it under the terms of the GNU Lesser General Public
431 +   License as published by the Free Software Foundation; either
432 +   version 2.1 of the License, or (at your option) any later version.
433 +
434 +   The GNU C Library is distributed in the hope that it will be useful,
435 +   but WITHOUT ANY WARRANTY; without even the implied warranty of
436 +   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
437 +   Lesser General Public License for more details.
438 +
439 +   You should have received a copy of the GNU Lesser General Public
440 +   License along with the GNU C Library; see the file COPYING.LIB.  If
441 +   not, see <http://www.gnu.org/licenses/>.  */
442 +
443 +/* The goal of the test is to trigger a failure if the parent touches
444 +   any part of the thread descriptor after the detached thread has
445 +   exited.  We test this by creating many detached threads with large
446 +   stacks.  The stacks quickly fill the the stack cache and subsequent
447 +   threads will start to cause the thread stacks to be immediately
448 +   unmapped to satisfy the stack cache max.  With the stacks being
449 +   unmapped the parent's read of any part of the thread descriptor will
450 +   trigger a segfault.  That segfault is what we are trying to cause,
451 +   since any segfault is a defect in the implementation.  */
452 +
453 +#include <pthread.h>
454 +#include <stdio.h>
455 +#include <errno.h>
456 +#include <unistd.h>
457 +#include <stdbool.h>
458 +#include <sys/resource.h>
459 +#include <support/xthread.h>
460 +
461 +/* Number of threads to create.  */
462 +enum { threads_to_create = 100000 };
463 +
464 +/* Number of threads which should spawn other threads.  */
465 +enum { creator_threads  = 2 };
466 +
467 +/* Counter of threads created so far.  This is incremented by all the
468 +   running creator threads.  */
469 +static unsigned threads_created;
470 +
471 +/* Thread callback which does nothing, so that the thread exits
472 +   immediatedly.  */
473 +static void *
474 +do_nothing (void *arg)
475 +{
476 +  return NULL;
477 +}
478 +
479 +/* Attribute indicating that the thread should be created in a detached
480 +   fashion.  */
481 +static pthread_attr_t detached;
482 +
483 +/* Barrier to synchronize initialization.  */
484 +static pthread_barrier_t barrier;
485 +
486 +static void *
487 +creator_thread (void *arg)
488 +{
489 +  int ret;
490 +  xpthread_barrier_wait (&barrier);
491 +
492 +  while (true)
493 +    {
494 +      pthread_t thr;
495 +      /* Thread creation will fail if the kernel does not free old
496 +        threads quickly enough, so we do not report errors.  */
497 +      ret = pthread_create (&thr, &detached, do_nothing, NULL);
498 +      if (ret == 0 && __atomic_add_fetch (&threads_created, 1, __ATOMIC_SEQ_CST)
499 +          >= threads_to_create)
500 +        break;
501 +    }
502 +
503 +  return NULL;
504 +}
505 +
506 +static int
507 +do_test (void)
508 +{
509 +  /* Limit the size of the process, so that memory allocation will
510 +     fail without impacting the entire system.  */
511 +  {
512 +    struct rlimit limit;
513 +    if (getrlimit (RLIMIT_AS, &limit) != 0)
514 +      {
515 +        printf ("FAIL: getrlimit (RLIMIT_AS) failed: %m\n");
516 +        return 1;
517 +      }
518 +    /* This limit, 800MB, is just a heuristic. Any value can be
519 +       picked.  */
520 +    long target = 800 * 1024 * 1024;
521 +    if (limit.rlim_cur == RLIM_INFINITY || limit.rlim_cur > target)
522 +      {
523 +        limit.rlim_cur = target;
524 +        if (setrlimit (RLIMIT_AS, &limit) != 0)
525 +          {
526 +            printf ("FAIL: setrlimit (RLIMIT_AS) failed: %m\n");
527 +            return 1;
528 +          }
529 +      }
530 +  }
531 +
532 +  xpthread_attr_init (&detached);
533 +
534 +  xpthread_attr_setdetachstate (&detached, PTHREAD_CREATE_DETACHED);
535 +
536 +  /* A large thread stack seems beneficial for reproducing a race
537 +     condition in detached thread creation.  The goal is to reach the
538 +     limit of the runtime thread stack cache such that the detached
539 +     thread's stack is unmapped after exit and causes a segfault when
540 +     the parent reads the thread descriptor data stored on the the
541 +     unmapped stack.  */
542 +  xpthread_attr_setstacksize (&detached, 16 * 1024 * 1024);
543 +
544 +  xpthread_barrier_init (&barrier, NULL, creator_threads);
545 +
546 +  pthread_t threads[creator_threads];
547 +
548 +  for (int i = 0; i < creator_threads; ++i)
549 +    threads[i] = xpthread_create (NULL, creator_thread, NULL);
550 +
551 +  for (int i = 0; i < creator_threads; ++i)
552 +    xpthread_join (threads[i]);
553 +
554 +  xpthread_attr_destroy (&detached);
555 +
556 +  xpthread_barrier_destroy (&barrier);
557 +
558 +  return 0;
559 +}
560 +
561 +#include <support/test-driver.c>
562 diff --git a/sysdeps/nacl/createthread.c b/sysdeps/nacl/createthread.c
563 index 7b571c34e2..5465558cc1 100644
564 --- a/sysdeps/nacl/createthread.c
565 +++ b/sysdeps/nacl/createthread.c
566 @@ -32,15 +32,13 @@ static void start_thread (void) __attribute__ ((noreturn));
567  
568  static int
569  create_thread (struct pthread *pd, const struct pthread_attr *attr,
570 -              bool stopped_start, STACK_VARIABLES_PARMS, bool *thread_ran)
571 +              bool *stopped_start, STACK_VARIABLES_PARMS, bool *thread_ran)
572  {
573    pd->tid = __nacl_get_tid (pd);
574  
575 -  pd->stopped_start = stopped_start;
576 -  if (__glibc_unlikely (stopped_start))
577 -    /* We make sure the thread does not run far by forcing it to get a
578 -       lock.  We lock it here too so that the new thread cannot continue
579 -       until we tell it to.  */
580 +  pd->stopped_start = *stopped_start;
581 +  if (__glibc_unlikely (*stopped_start))
582 +    /* See CONCURRENCY NOTES in nptl/pthread_create.c.  */
583      lll_lock (pd->lock, LLL_PRIVATE);
584  
585    TLS_DEFINE_INIT_TP (tp, pd);
586 diff --git a/sysdeps/unix/sysv/linux/createthread.c b/sysdeps/unix/sysv/linux/createthread.c
587 index 6d32cece48..66ddae61d4 100644
588 --- a/sysdeps/unix/sysv/linux/createthread.c
589 +++ b/sysdeps/unix/sysv/linux/createthread.c
590 @@ -46,7 +46,7 @@ static int start_thread (void *arg) __attribute__ ((noreturn));
591  
592  static int
593  create_thread (struct pthread *pd, const struct pthread_attr *attr,
594 -              bool stopped_start, STACK_VARIABLES_PARMS, bool *thread_ran)
595 +              bool *stopped_start, STACK_VARIABLES_PARMS, bool *thread_ran)
596  {
597    /* Determine whether the newly created threads has to be started
598       stopped since we have to set the scheduling parameters or set the
599 @@ -54,13 +54,11 @@ create_thread (struct pthread *pd, const struct pthread_attr *attr,
600    if (attr != NULL
601        && (__glibc_unlikely (attr->cpuset != NULL)
602           || __glibc_unlikely ((attr->flags & ATTR_FLAG_NOTINHERITSCHED) != 0)))
603 -    stopped_start = true;
604 +    *stopped_start = true;
605  
606 -  pd->stopped_start = stopped_start;
607 -  if (__glibc_unlikely (stopped_start))
608 -    /* We make sure the thread does not run far by forcing it to get a
609 -       lock.  We lock it here too so that the new thread cannot continue
610 -       until we tell it to.  */
611 +  pd->stopped_start = *stopped_start;
612 +  if (__glibc_unlikely (*stopped_start))
613 +    /* See CONCURRENCY NOTES in nptl/pthread_creat.c.  */
614      lll_lock (pd->lock, LLL_PRIVATE);
615  
616    /* We rely heavily on various flags the CLONE function understands:
617 @@ -117,7 +115,7 @@ create_thread (struct pthread *pd, const struct pthread_attr *attr,
618        /* Set the affinity mask if necessary.  */
619        if (attr->cpuset != NULL)
620         {
621 -         assert (stopped_start);
622 +         assert (*stopped_start);
623  
624           res = INTERNAL_SYSCALL (sched_setaffinity, err, 3, pd->tid,
625                                   attr->cpusetsize, attr->cpuset);
626 @@ -140,7 +138,7 @@ create_thread (struct pthread *pd, const struct pthread_attr *attr,
627        /* Set the scheduling parameters.  */
628        if ((attr->flags & ATTR_FLAG_NOTINHERITSCHED) != 0)
629         {
630 -         assert (stopped_start);
631 +         assert (*stopped_start);
632  
633           res = INTERNAL_SYSCALL (sched_setscheduler, err, 3, pd->tid,
634                                   pd->schedpolicy, &pd->schedparam);
635 -- 
636 2.11.0
637