Skip to content

Lock analysis doesn't work with static locks that are member variables #135437

@afoxley

Description

@afoxley

Little standalone example showing the issue: https://godbolt.org/z/6EvMbrvsr

Given:

struct B {
    int resource GUARDED_BY(mutex) = 0;
    static inline std::mutex mutex;
};

struct A {
   
    void acquire() {
        std::lock_guard lock(b.mutex);
        b.resource++;
    }
    B b;
};

int main() {
    A a;
    a.acquire();
}

We get a lock analysis failure:

<source>:17:11: warning: writing variable 'resource' requires holding mutex 'mutex' exclusively [-Wthread-safety-analysis]
   17 |         b.resource++;
      |           ^
1 warning generated.
ASM generation compiler returned: 0
<source>:17:11: warning: writing variable 'resource' requires holding mutex 'mutex' exclusively [-Wthread-safety-analysis]
   17 |         b.resource++;

Even though we are holding the lock.

Build args: -std=c++23 -Wthread-safety -D_LIBCPP_ENABLE_THREAD_SAFETY_ANNOTATIONS=1 -stdlib=libc++

Metadata

Metadata

Assignees

No one assigned

    Labels

    clang:diagnosticsNew/improved warning or error message in Clang, but not in clang-tidy or static analyzerfalse-negativeWarning doesn't fire when it should

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions