Commit 0b550c5b authored by jan.koester's avatar jan.koester
Browse files

pthread: a new key is NULL, also in a deleted key's slot

pthread_key_create() reused the slot of a deleted key and every thread
still saw the value it had set for the old one. createrepo_c calls
xmlCleanupParser() and then goes on using libxml2: the re-initialization
got the same key and with it the main thread's freed state, so --update
wrote an unindented repomd.xml and crashed freeing that state again in
exit().

Each value now records the key's seq; get and the key destructors ignore
it when that differs, as in glibc.

e2e_pthread_key_reuse tests main, worker threads and pthread_exit().

Co-Authored-By: default avatarClaude Opus 5.5 <noreply@anthropic.com>
parent 0101aceb
Loading
Loading
Loading
Loading
+23 −11
Changes for src/linux/thread.cpp: 23 added lines, 11 removed lines.
Original line number Diff line number Diff line
@@ -67,7 +67,18 @@ extern "C" {
     * alongside pthread_key_create/pthread_getspecific/setspecific) --
     * forward-declared here since sys::thread::runKeyDestructors() below
     * needs it before that point in the file. */
    void __run_key_destructors(void** specific);
    void __run_key_destructors(sys::__internal::keyvalue* specific);
}

static uintptr_t key_seq(size_t key) {
    return __atomic_load_n(&sys::__internal::__pthread_keys[key].seq, __ATOMIC_ACQUIRE);
}

/* nullptr unless set since the key was created (POSIX: a new key is NULL in
 * every thread). Was the bare slot: libxml2 re-initializing got back the
 * state it had freed (createrepo_c --update crashed in exit()). */
static void* key_value(const sys::__internal::keyvalue& slot, size_t key) {
    return slot.seq == key_seq(key) ? slot.value : nullptr;
}
   
/* Never destroyed: threads still get joined (and so removed from the
@@ -218,7 +229,7 @@ sys::thread::thread(void *args,threadattr *attr){
    _ParentPid=0;
    _ThreadPid=1;

    for (size_t i = 0; i < PTHREAD_KEYS_MAX; i++) _specific[i] = nullptr;
    for (size_t i = 0; i < PTHREAD_KEYS_MAX; i++) _specific[i] = {};

    _tls = sys::ld::acquire_tls_block(this);
    if (!_tls) {
@@ -402,11 +413,11 @@ int sys::thread::getPid(){
}

void* sys::thread::getSpecific(size_t key) const {
    return key < PTHREAD_KEYS_MAX ? _specific[key] : nullptr;
    return key < PTHREAD_KEYS_MAX ? key_value(_specific[key], key) : nullptr;
}

void sys::thread::setSpecific(size_t key, void* v) {
    if (key < PTHREAD_KEYS_MAX) _specific[key] = v;
    if (key < PTHREAD_KEYS_MAX) _specific[key] = {v, key_seq(key)};
}

void sys::thread::runKeyDestructors() {
@@ -624,16 +635,17 @@ extern "C" {
     * itself set a new non-null value (for another key, or even the
     * one just cleared) that also needs a destructor call before the
     * thread/process is allowed to finish exiting. */
    void __run_key_destructors(void** specific) {
    void __run_key_destructors(sys::__internal::keyvalue* specific) {
        for (int iter = 0; iter < PTHREAD_DESTRUCTOR_ITERATIONS; iter++) {
            bool ran_any = false;
            for (size_t k = 0; k < PTHREAD_KEYS_MAX; k++) {
                uintptr_t seq = sys::__internal::__pthread_keys[k].seq;
                uintptr_t seq = key_seq(k);
                if ((seq & 1) == 0) continue; /* key not currently allocated */
                if (specific[k].seq != seq) continue; /* a deleted key's value */
                void (*destr)(void*) = sys::__internal::__pthread_keys[k].destr;
                void* val = specific[k];
                void* val = specific[k].value;
                if (val && destr) {
                    specific[k] = nullptr;
                    specific[k].value = nullptr;
                    destr(val);
                    ran_any = true;
                }
@@ -693,12 +705,12 @@ extern "C" {
     * is exactly one main thread per process, so this fallback array
     * IS that thread's real storage, not a shared/aliased slot the way
     * the old specific_1stblock was for every OTHER thread too. */
    static void* g_main_thread_specific[PTHREAD_KEYS_MAX];
    static sys::__internal::keyvalue g_main_thread_specific[PTHREAD_KEYS_MAX];

    void* pthread_getspecific(pthread_key_t key) {
        if (key >= PTHREAD_KEYS_MAX) return nullptr;
        sys::thread* self = sys::__internal::thread::getins().self();
        return self ? self->getSpecific(key) : g_main_thread_specific[key];
        return self ? self->getSpecific(key) : key_value(g_main_thread_specific[key], key);
    }

    /* Real gap, and a real, severe pre-existing bug: this had a
@@ -806,7 +818,7 @@ extern "C" {
             * the key destructors from atexit() (as this used to) freed
             * it a second time (real bug: createrepo_c --update aborted
             * with "double free() detected" in exit()). */
            g_main_thread_specific[key] = (void*)tls;
            g_main_thread_specific[key] = {(void*)tls, key_seq(key)};
        }
        return 0;
    }
+20 −0
Changes for src/test/e2e/CMakeLists.txt: 20 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -4151,6 +4151,26 @@ target_link_libraries(e2e_pthread_exit PRIVATE
add_dependencies(e2e_pthread_exit crti Scrt1 crtbeginS crtn systempp)

add_test(NAME e2e_pthread_exit COMMAND e2e_pthread_exit)

# A new key is NULL, also in the slot of a deleted one (createrepo_c --update)
add_executable(e2e_pthread_key_reuse pthread_key_reuse_test.cpp)
set_target_properties(e2e_pthread_key_reuse PROPERTIES OUTPUT_NAME "pthread_key_reuse_test")
target_compile_options(e2e_pthread_key_reuse PRIVATE -fPIE)
target_link_options(e2e_pthread_key_reuse PRIVATE
    -nostdlib -pie
    -Wl,--hash-style=sysv
    -Wl,--dynamic-linker,$<TARGET_FILE_DIR:systempp>/ld-linux-${CMAKE_SYSTEM_PROCESSOR}.so
    -Wl,-rpath,$<TARGET_FILE_DIR:systempp>
)
target_link_libraries(e2e_pthread_key_reuse PRIVATE
    $<TARGET_OBJECTS:crti>
    $<TARGET_OBJECTS:Scrt1>
    $<TARGET_OBJECTS:crtbeginS>
    $<TARGET_OBJECTS:crtn>
    systempp
)
add_dependencies(e2e_pthread_key_reuse crti Scrt1 crtbeginS crtn systempp)
add_test(NAME e2e_pthread_key_reuse COMMAND e2e_pthread_key_reuse)
# the old pthread_exit ended the whole process with status 0 -- that must
# not count as a pass
set_tests_properties(e2e_pthread_exit PROPERTIES PASS_REGULAR_EXPRESSION "OK: pthread_exit")
+96 −0
Changes for src/test/e2e/pthread_key_reuse_test.cpp: 96 added lines, 0 removed lines.
Original line number Diff line number Diff line
/* A key from pthread_key_create() is NULL in every thread, also when it
 * takes the slot of a deleted key that still had values there, and those
 * values never reach the new key's destructor. Was: the old value came
 * back. libxml2's xmlCleanupParser() frees the main thread's state and
 * deletes its key; on re-initialization it got the freed state again and
 * createrepo_c --update crashed freeing it once more in exit(). */
#include <pthread.h>
#include <stdio.h>
#include <sys/wait.h>
#include <unistd.h>

#define CHECK(cond, ...) do { if (!(cond)) { printf("FAIL: " __VA_ARGS__); printf("\n"); return 1; } } while (0)

static pthread_key_t g_key;
static pthread_barrier_t g_step;
static int g_old, g_new;
static int g_old_dtor, g_new_dtor, g_new_dtor_wrong;

static void old_dtor(void*) { __atomic_add_fetch(&g_old_dtor, 1, __ATOMIC_SEQ_CST); }
static void new_dtor(void* v) {
    __atomic_add_fetch(v == &g_new ? &g_new_dtor : &g_new_dtor_wrong, 1, __ATOMIC_SEQ_CST);
}

/* arg: null = never looks at the new key, else reads and then sets it */
static void* worker(void* arg) {
    pthread_setspecific(g_key, &g_old);
    pthread_barrier_wait(&g_step); /* the value is there */
    pthread_barrier_wait(&g_step); /* the key was deleted and created again */
    if (!arg) return nullptr;
    void* stale = pthread_getspecific(g_key);
    pthread_setspecific(g_key, &g_new);
    if (pthread_getspecific(g_key) != &g_new) return (void*)1;
    return stale;
}

static int main_thread_reuse() {
    CHECK(pthread_key_create(&g_key, old_dtor) == 0, "key_create");
    for (int i = 0; i < 3; i++) {
        CHECK(pthread_getspecific(g_key) == nullptr, "main: new key not NULL (round %d)", i);
        CHECK(pthread_setspecific(g_key, &g_old) == 0, "setspecific");
        CHECK(pthread_getspecific(g_key) == &g_old, "main: value lost");
        CHECK(pthread_key_delete(g_key) == 0, "key_delete");
        CHECK(pthread_key_create(&g_key, old_dtor) == 0, "key_create again");
    }
    CHECK(pthread_getspecific(g_key) == nullptr, "main: new key not NULL");
    CHECK(pthread_key_delete(g_key) == 0, "key_delete");
    return 0;
}

static int worker_reuse() {
    CHECK(pthread_barrier_init(&g_step, nullptr, 3) == 0, "barrier_init");
    CHECK(pthread_key_create(&g_key, old_dtor) == 0, "key_create");
    pthread_t idle, user;
    CHECK(pthread_create(&idle, nullptr, worker, nullptr) == 0, "create idle");
    CHECK(pthread_create(&user, nullptr, worker, &g_key) == 0, "create user");
    pthread_barrier_wait(&g_step);
    CHECK(pthread_key_delete(g_key) == 0, "key_delete");
    CHECK(pthread_key_create(&g_key, new_dtor) == 0, "key_create again");
    pthread_barrier_wait(&g_step);

    void *idle_ret, *user_ret;
    CHECK(pthread_join(idle, &idle_ret) == 0, "join idle");
    CHECK(pthread_join(user, &user_ret) == 0, "join user");
    CHECK(user_ret == nullptr, "worker: new key not NULL, or lost its value (%p)", user_ret);
    CHECK(g_old_dtor == 0, "deleted key's destructor ran %d times", g_old_dtor);
    CHECK(g_new_dtor_wrong == 0, "new key's destructor got the deleted key's value");
    CHECK(g_new_dtor == 1, "new key's destructor ran %d times, want 1", g_new_dtor);
    return 0;
}

/* pthread_exit() from main runs the destructors: not on a stale value */
static int main_exit_reuse() {
    pid_t pid = fork();
    CHECK(pid >= 0, "fork");
    if (pid == 0) {
        pthread_key_create(&g_key, nullptr);
        pthread_setspecific(g_key, &g_old);
        pthread_key_delete(g_key);
        pthread_key_create(&g_key, [](void*) { _exit(9); });
        pthread_exit(nullptr);
    }
    int st = 0;
    CHECK(waitpid(pid, &st, 0) == pid, "waitpid");
    CHECK(WIFEXITED(st) && WEXITSTATUS(st) == 0, "main's pthread_exit: stale value destroyed (0x%x)", st);
    return 0;
}

int main() {
    /* each on its own, so one failure does not hide the next */
    int failed = main_thread_reuse();
    failed |= worker_reuse();
    failed |= main_exit_reuse();
    if (failed) return 1;
    printf("pthread key reuse ok\n");
    return 0;
}
+12 −1
Changes for src/thread.h: 12 added lines, 1 removed line.
Original line number Diff line number Diff line
@@ -26,12 +26,23 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*******************************************************************************/

#include <stddef.h>
#include <stdint.h>
#include <limits.h>

#pragma once

namespace sys {

    namespace __internal {
        /* A thread's value for a pthread key, and the key's seq when it was
         * set: key create/delete each change the seq, so a value left from a
         * deleted key is void in every thread without visiting them. */
        struct keyvalue {
            void* value;
            uintptr_t seq;
        };
    };

    class threadattr {
    public:
        threadattr();
@@ -177,7 +188,7 @@ namespace sys {
        bool _joinable;
        bool _detached;
        int _reclaim;
        void* _specific[PTHREAD_KEYS_MAX];
        __internal::keyvalue _specific[PTHREAD_KEYS_MAX];
    };

};