Skip to content

Clang Thread Safety: False positive warning generated in C code when accessing fields of a struct #161854

@DobroSun

Description

@DobroSun
// Compiling with: clang -Wthread-safety main.c
struct __attribute__((lockable)) Mutex {};
struct Foo {
    struct Mutex mu;
    int value __attribute__((guarded_by(mu)));
};

void mutex_lock(struct Mutex* mu)   __attribute__((exclusive_lock_function(mu)));
void mutex_unlock(struct Mutex* mu) __attribute__((unlock_function(mu)));

struct Mutex mu;
int value __attribute__((guarded_by(mu)));

int main() {
    {
        mutex_lock(&mu);
        value = 123;      // Works!
        mutex_unlock(&mu);
    }

    {
        struct Foo foo = {};
        mutex_lock(&foo.mu);
        foo.value = 123;     // warning: writing variable 'value' requires holding mutex 'mu' exclusively [-Wthread-safety-analysis]
        mutex_unlock(&foo.mu);
    }
    return 0;
}

Compiled on Fedora 42 with clang 20.1.8, although I tried clang 21.1.2 and the issue still persists.
Renaming file to main.cpp and compiling with clang++ doesn't generate this kind of error. Maybe I'm doing something here incorrectly or is this actually a compiler bug? Can't tell myself...

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions