musl/src/thread/pthread_key_create.c
Rich Felker a6adb2bcd8 work around constant folding bug 61144 in gcc 4.9.0 and 4.9.1
previously we detected this bug in configure and issued advice for a
workaround, but this turned out not to work. since then gcc 4.9.0 has
appeared in several distributions, and now 4.9.1 has been released
without a fix despite this being a wrong code generation bug which is
supposed to be a release-blocker, per gcc policy.

since the scope of the bug seems to affect only data objects (rather
than functions) whose definitions are overridable, and there are only
a very small number of these in musl, I am just changing them from
const to volatile for the time being. simply removing the const would
be sufficient to make gcc 4.9.1 work (the non-const case was
inadvertently fixed as part of another change in gcc), and this would
also be sufficient with 4.9.0 if we forced -O0 on the affected files
or on the whole build. however it's cleaner to just remove all the
broken compiler detection and use volatile, which will ensure that
they are never constant-folded. the quality of a non-broken compiler's
output should not be affected except for the fact that these objects
are no longer const and thus possibly add a few bytes to data/bss.

this change can be reconsidered and possibly reverted at some point in
the future when the broken gcc versions are no longer relevant.
2014-07-16 21:32:06 -04:00

55 lines
1.2 KiB
C

#include "pthread_impl.h"
volatile size_t __pthread_tsd_size = sizeof(void *) * PTHREAD_KEYS_MAX;
void *__pthread_tsd_main[PTHREAD_KEYS_MAX] = { 0 };
static void (*keys[PTHREAD_KEYS_MAX])(void *);
static void nodtor(void *dummy)
{
}
int pthread_key_create(pthread_key_t *k, void (*dtor)(void *))
{
unsigned i = (uintptr_t)&k / 16 % PTHREAD_KEYS_MAX;
unsigned j = i;
if (libc.has_thread_pointer) {
pthread_t self = __pthread_self();
/* This can only happen in the main thread before
* pthread_create has been called. */
if (!self->tsd) self->tsd = __pthread_tsd_main;
}
if (!dtor) dtor = nodtor;
do {
if (!a_cas_p(keys+j, 0, (void *)dtor)) {
*k = j;
return 0;
}
} while ((j=(j+1)%PTHREAD_KEYS_MAX) != i);
return EAGAIN;
}
int pthread_key_delete(pthread_key_t k)
{
keys[k] = 0;
return 0;
}
void __pthread_tsd_run_dtors()
{
pthread_t self = __pthread_self();
int i, j, not_finished = self->tsd_used;
for (j=0; not_finished && j<PTHREAD_DESTRUCTOR_ITERATIONS; j++) {
not_finished = 0;
for (i=0; i<PTHREAD_KEYS_MAX; i++) {
if (self->tsd[i] && keys[i]) {
void *tmp = self->tsd[i];
self->tsd[i] = 0;
keys[i](tmp);
not_finished = 1;
}
}
}
}