Commit 2f35ddb8 authored by jan.koester's avatar jan.koester
Browse files

ld: dlopen(RTLD_LOCAL) keeps the object out of the global scope

Every loaded object was in the global symbol scope, so two RTLD_LOCAL
libraries defining the same names interposed each other. Firefox loads
its bundled ffvpx (libmozavutil) and the system libavutil this way: the
system libavcodec called libmozavutil's av_frame_unref() and the RDD
media decoder crashed (YouTube: "Es ist ein Fehler aufgetreten").

Objects loaded by dlopen() without RTLD_GLOBAL are now local: their
relocations search the global scope, then the dependency tree of the
dlopen()ed object (glibc's local scope); RTLD_DEFAULT doesn't see them;
dlopen(RTLD_GLOBAL) promotes an already loaded tree.

Co-Authored-By: default avatarClaude Opus 5.5 <noreply@anthropic.com>
parent 97856ac3
Loading
Loading
Loading
Loading
+24 −13
Changes for src/linux/dlfcn.cpp: 24 added lines, 13 removed lines.
Original line number Diff line number Diff line
@@ -68,19 +68,7 @@ extern "C" {
        } else {
            /* a dlopen()ed object: the object and its dependencies, breadth
             * first ("dependency order") */
            sys::ld::dso* queue[256];
            size_t head = 0, tail = 0;
            queue[tail++] = (sys::ld::dso*)handle;
            const uint32_t hash = sys::ld::sysv_hash(name);
            while (head < tail && !s) {
                sys::ld::dso* d = queue[head++];
                if ((s = sys::ld::find_in_dso(d, name, hash))) { owner = d; break; }
                for (size_t i = 0; i < d->depcount; ++i) {
                    bool seen = false;
                    for (size_t j = 0; j < tail && !seen; ++j) seen = queue[j] == d->deps[i];
                    if (!seen && tail < sizeof(queue) / sizeof(queue[0])) queue[tail++] = d->deps[i];
                }
            }
            s = sys::ld::find_in_tree((sys::ld::dso*)handle, name, sys::ld::sysv_hash(name), &owner);
        }
        if (!s) { error = (char*)"dlsym: symbol not found"; return nullptr; }
        error = nullptr;
@@ -118,6 +106,29 @@ extern "C" {

        sys::ld::dso* start = mark ? mark->next : sys::ld::list_head();

        /* Symbol scope: what this call loaded is local to d's tree unless
         * RTLD_GLOBAL; RTLD_GLOBAL also promotes an already loaded local
         * tree (glibc). Set before relocating, which looks it up. */
        if (flag & RTLD_GLOBAL) {
            sys::ld::dso* queue[256];
            size_t head = 0, tail = 0;
            queue[tail++] = d;
            while (head < tail) {
                sys::ld::dso* n = queue[head++];
                n->local = false;
                for (size_t i = 0; i < n->depcount; ++i) {
                    bool seen = false;
                    for (size_t j = 0; j < tail && !seen; ++j) seen = queue[j] == n->deps[i];
                    if (!seen && tail < sizeof(queue) / sizeof(queue[0])) queue[tail++] = n->deps[i];
                }
            }
        } else {
            for (sys::ld::dso* n = start; n; n = n->next) {
                n->local = true;
                n->scope_root = d;
            }
        }

        for (sys::ld::dso* n = start; n; n = n->next) {
            if (n->has_tls && !n->tls_id) {
                /* Static TLS only: a module loaded now gets its TLS from
+37 −5
Changes for src/linux/ld/dynlink.cpp: 37 added lines, 5 removed lines.
Original line number Diff line number Diff line
@@ -192,11 +192,43 @@ template <class F> static dso* for_each_in_search_order(F f) {
ElfW(Sym)* global_find_sym(const char* name, dso** owner_out) {
    uint32_t h = sysv_hash(name);
    ElfW(Sym)* found = nullptr;
    dso* owner = for_each_in_search_order([&](dso* d) { return (found = find_in_dso(d, name, h)) != nullptr; });
    dso* owner = for_each_in_search_order([&](dso* d) {
        return !d->local && (found = find_in_dso(d, name, h)) != nullptr;
    });
    if (found && owner_out) *owner_out = owner;
    return found;
}

ElfW(Sym)* find_in_tree(dso* root, const char* name, uint32_t hash, dso** owner_out) {
    dso* queue[256];
    size_t head = 0, tail = 0;
    queue[tail++] = root;
    while (head < tail) {
        dso* d = queue[head++];
        if (ElfW(Sym)* s = find_in_dso(d, name, hash)) {
            if (owner_out) *owner_out = d;
            return s;
        }
        for (size_t i = 0; i < d->depcount; ++i) {
            bool seen = false;
            for (size_t j = 0; j < tail && !seen; ++j) seen = queue[j] == d->deps[i];
            if (!seen && tail < sizeof(queue) / sizeof(queue[0])) queue[tail++] = d->deps[i];
        }
    }
    return nullptr;
}

/* Objects loaded with dlopen(RTLD_LOCAL) stay out of the global scope:
 * two of them may define the same names (Firefox loads its bundled
 * libmozavutil and the system libavutil), and each must bind to its own
 * dependencies. Before, every loaded object was global and the system
 * libavcodec called libmozavutil's av_frame_unref() -- crash. */
ElfW(Sym)* scope_find_sym(dso* d, const char* name, dso** owner_out) {
    if (ElfW(Sym)* s = global_find_sym(name, owner_out)) return s;
    if (!d->local) return nullptr;
    return find_in_tree(d->scope_root ? d->scope_root : d, name, sysv_hash(name), owner_out);
}

/* Symbol lookup for R_X86_64_COPY only: it must find the ORIGINAL
 * definition to copy from (typically in libc.so), never `skip` (the
 * object currently being relocated) -- `skip` only has a placeholder
@@ -639,7 +671,7 @@ static bool apply_one_rela(dso* d, ElfW(Rela)* r) {
        ElfW(Sym)* local = &d->syms[symidx];
        const char* symname = d->strings + local->st_name;
        dso* owner = nullptr;
        ElfW(Sym)* sym = global_find_sym(symname, &owner);
        ElfW(Sym)* sym = scope_find_sym(d, symname, &owner);
        if (!sym) {
            if (ELFW_ST_BIND(local->st_info) == STB_WEAK) {
                *addr = (type == REL_SYMBOLIC || type == REL_USYMBOLIC_OR_SYMBOLIC) ? (size_t)r->r_addend : 0;
@@ -676,7 +708,7 @@ static bool apply_one_rela(dso* d, ElfW(Rela)* r) {
        dso* owner = d;
        if (symidx) {
            const char* symname = d->strings + d->syms[symidx].st_name;
            if (!global_find_sym(symname, &owner)) return false;
            if (!scope_find_sym(d, symname, &owner)) return false;
        }
        *addr = owner->tls_id;
        return true;
@@ -687,7 +719,7 @@ static bool apply_one_rela(dso* d, ElfW(Rela)* r) {
        if (symidx) {
            const char* symname = d->strings + d->syms[symidx].st_name;
            dso* owner = nullptr;
            ElfW(Sym)* sym = global_find_sym(symname, &owner);
            ElfW(Sym)* sym = scope_find_sym(d, symname, &owner);
            if (!sym) return false;
            value = sym->st_value;
        }
@@ -702,7 +734,7 @@ static bool apply_one_rela(dso* d, ElfW(Rela)* r) {
        size_t symvalue = 0;
        if (symidx) {
            const char* symname = d->strings + d->syms[symidx].st_name;
            ElfW(Sym)* sym = global_find_sym(symname, &owner);
            ElfW(Sym)* sym = scope_find_sym(d, symname, &owner);
            if (!sym) return false;
            symvalue = sym->st_value;
        }
+15 −0
Changes for src/linux/ld/dynlink.h: 15 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -64,6 +64,14 @@ struct dso {
    dso* deps[16];       /* direct DT_NEEDED dependencies, in load order */
    size_t depcount;

    /* Symbol scope (ELF gABI / glibc): objects loaded at startup and by
     * dlopen(RTLD_GLOBAL) are in the global scope; one loaded by
     * dlopen(RTLD_LOCAL) is not (local), and its relocations search the
     * global scope and then the dependency tree of `scope_root`, the
     * dlopen()ed object that brought it in. */
    bool local;
    dso* scope_root;

    unsigned refcount;
    bool inited;
    bool finid;          /* DT_FINI_ARRAY/DT_FINI ran (run_fini is idempotent) */
@@ -116,6 +124,13 @@ ElfW(Sym)* find_in_dso(dso* d, const char* name, uint32_t hash);
 * load order), returning the first defined match. */
ElfW(Sym)* global_find_sym(const char* name, dso** owner_out);

/* Symbol lookup for a relocation of `d`: the global scope, then (for an
 * object loaded with RTLD_LOCAL) its dlopen root's dependency tree. */
ElfW(Sym)* scope_find_sym(dso* d, const char* name, dso** owner_out);

/* Breadth-first dependency search from root (dlsym on a handle). */
ElfW(Sym)* find_in_tree(dso* root, const char* name, uint32_t hash, dso** owner_out);

/* RTLD_NEXT: the first definition in an object after `after` in the global
 * search order (main, LD_PRELOAD objects, then load order). */
ElfW(Sym)* find_sym_after(dso* after, const char* name, dso** owner_out);
+55 −0
Changes for src/test/e2e/CMakeLists.txt: 55 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -4212,3 +4212,58 @@ target_link_libraries(e2e_cxx_node_handle PRIVATE
add_dependencies(e2e_cxx_node_handle crti Scrt1 crtbeginS crtn systempp)

add_test(NAME e2e_cxx_node_handle COMMAND e2e_cxx_node_handle)

# dlopen(RTLD_LOCAL) symbol scopes: two codec/util library pairs defining
# the same symbol (Firefox's bundled ffvpx next to the system ffmpeg).
foreach(_s a b)
    add_library(e2e_scope_util_${_s} SHARED libscope_util.cpp)
    set_target_properties(e2e_scope_util_${_s} PROPERTIES OUTPUT_NAME "scope_util_${_s}" PREFIX "lib")
    target_compile_options(e2e_scope_util_${_s} PRIVATE -fPIC)
    target_compile_definitions(e2e_scope_util_${_s} PRIVATE SCOPE_NAME="util-${_s}")
    target_link_options(e2e_scope_util_${_s} PRIVATE -nostdlib -Wl,--hash-style=sysv -Wl,-soname,libscope_util_${_s}.so)
    target_link_libraries(e2e_scope_util_${_s} PRIVATE
        $<TARGET_OBJECTS:crti>
        $<TARGET_OBJECTS:crtbeginS>
        $<TARGET_OBJECTS:crtn>
        systempp
    )
    add_dependencies(e2e_scope_util_${_s} crti crtbeginS crtn systempp)

    add_library(e2e_scope_codec_${_s} SHARED libscope_codec.cpp)
    set_target_properties(e2e_scope_codec_${_s} PROPERTIES OUTPUT_NAME "scope_codec_${_s}" PREFIX "lib")
    target_compile_options(e2e_scope_codec_${_s} PRIVATE -fPIC)
    target_compile_definitions(e2e_scope_codec_${_s} PRIVATE SCOPE_ENTRY=scope_codec_${_s})
    target_link_options(e2e_scope_codec_${_s} PRIVATE -nostdlib -Wl,--hash-style=sysv -Wl,-soname,libscope_codec_${_s}.so
        -Wl,-rpath,$<TARGET_FILE_DIR:e2e_scope_util_${_s}>)
    target_link_libraries(e2e_scope_codec_${_s} PRIVATE
        $<TARGET_OBJECTS:crti>
        $<TARGET_OBJECTS:crtbeginS>
        $<TARGET_OBJECTS:crtn>
        e2e_scope_util_${_s}
        systempp
    )
    add_dependencies(e2e_scope_codec_${_s} crti crtbeginS crtn systempp e2e_scope_util_${_s})
endforeach()

add_executable(e2e_dlopen_scope dlopen_scope_test.cpp)
set_target_properties(e2e_dlopen_scope PROPERTIES OUTPUT_NAME "dlopen_scope_test")
target_compile_options(e2e_dlopen_scope PRIVATE -fPIE)
target_compile_definitions(e2e_dlopen_scope PRIVATE
    SCOPE_CODEC_A="$<TARGET_FILE:e2e_scope_codec_a>"
    SCOPE_CODEC_B="$<TARGET_FILE:e2e_scope_codec_b>")
target_link_options(e2e_dlopen_scope 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_dlopen_scope PRIVATE
    $<TARGET_OBJECTS:crti>
    $<TARGET_OBJECTS:Scrt1>
    $<TARGET_OBJECTS:crtbeginS>
    $<TARGET_OBJECTS:crtn>
    systempp
)
add_dependencies(e2e_dlopen_scope crti Scrt1 crtbeginS crtn systempp e2e_scope_codec_a e2e_scope_codec_b)

add_test(NAME e2e_dlopen_scope COMMAND e2e_dlopen_scope)
+50 −0
Changes for src/test/e2e/dlopen_scope_test.cpp: 50 added lines, 0 removed lines.
Original line number Diff line number Diff line
/* dlopen(RTLD_LOCAL) keeps an object's symbols out of the global scope:
 * libscope_codec_a needs libscope_util_a and libscope_codec_b needs
 * libscope_util_b, both defining scope_who(). Each codec must bind to its
 * own util. Firefox loads its bundled ffvpx (libmozavutil) and the system
 * libavutil this way; when every object was global, the system libavcodec
 * called libmozavutil's av_frame_unref() and the media decoder crashed.
 */

#include <dlfcn.h>
#include <stdio.h>
#include <string.h>

static int g_fail = 0;
#define CHECK(c, ...) do { if (!(c)) { printf("FAIL %s:%d: ", __FILE__, __LINE__); printf(__VA_ARGS__); printf("\n"); g_fail++; } } while (0)

typedef const char* (*fn)();

int main() {
    void* a = dlopen(SCOPE_CODEC_A, RTLD_NOW | RTLD_LOCAL);
    void* b = dlopen(SCOPE_CODEC_B, RTLD_NOW | RTLD_LOCAL);
    CHECK(a && b, "dlopen: %s", dlerror());
    if (!a || !b) return 1;
    fn fa = (fn)dlsym(a, "scope_codec_a");
    fn fb = (fn)dlsym(b, "scope_codec_b");
    CHECK(fa && fb, "dlsym codec entry");
    if (!fa || !fb) return 1;
    CHECK(!strcmp(fa(), "util-a"), "codec a bound to %s", fa());
    CHECK(!strcmp(fb(), "util-b"), "codec b bound to %s", fb());

    // dlsym on a handle searches that handle's tree
    fn wa = (fn)dlsym(a, "scope_who");
    fn wb = (fn)dlsym(b, "scope_who");
    CHECK(wa && !strcmp(wa(), "util-a"), "dlsym(a, scope_who)");
    CHECK(wb && !strcmp(wb(), "util-b"), "dlsym(b, scope_who)");

    // local objects are not in the global scope
    CHECK(dlsym(RTLD_DEFAULT, "scope_who") == nullptr, "RTLD_LOCAL symbol visible through RTLD_DEFAULT");

    // RTLD_GLOBAL promotes an already loaded local tree
    void* b2 = dlopen(SCOPE_CODEC_B, RTLD_NOW | RTLD_GLOBAL);
    CHECK(b2 == b, "second dlopen returns another handle");
    fn g = (fn)dlsym(RTLD_DEFAULT, "scope_who");
    CHECK(g && !strcmp(g(), "util-b"), "RTLD_GLOBAL did not promote the tree");
    // codec a keeps its binding
    CHECK(!strcmp(fa(), "util-a"), "codec a rebound to %s", fa());

    if (g_fail) { printf("%d failures\n", g_fail); return 1; }
    printf("dlopen scope: ok\n");
    return 0;
}
Loading