Search code examples
clangpthreadslockingwarningsmutex

How to fix clang warning "acquiring mutex 'lock' requires negative capability '!lock'"


I'm trying to address a warning in code that when compiled with clang -Weverything draws this:

$ cc -Weverything x.c
x.c:12:10: warning: acquiring mutex 'lock' requires negative capability '!lock' [-Wthread-safety-negative]
    int sc = pthread_rwlock_rdlock(&lock);
             ^
x.c:8:1: note: thread warning in function 'main'
{
^
1 warning generated.

The particular clang version identifies as

$ cc --version
FreeBSD clang version 15.0.7 (https://github.com/llvm/llvm-project.git llvmorg-15.0.7-0-g8dfdcc7b7bf6)
Target: x86_64-unknown-freebsd14.0
Thread model: posix
InstalledDir: /usr/bin

My minimal program to reproduce is

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

static pthread_rwlock_t lock;

int main (void)
{
    int sc = pthread_rwlock_init(&lock, NULL);
    if (sc != 0)
      perror ("pthread_rwlock_init");
    sc = pthread_rwlock_rdlock(&lock);
    if (sc != 0)
        perror ("pthread_rwlock_rdlock");
    sc = pthread_rwlock_unlock(&lock);
    if (sc != 0)
        perror ("pthread_rwlock_unlock");
    return EXIT_SUCCESS;
}

I could not find any explanation what a negative capability is or how to steal one from a compiler jockey. Does anyone know what's going on and how I can address the warning other than with -Wno-thread-safety-negative or an equivalent #pragma?


Solution

  • It looks like this is an LLVM bug, as discussed in the comment thread for the patch that introduced it. If I'm following the thread correctly, that patch was reverted, and possibly an improved one was applied.

    You should be able to suppress the warning by

    • turning it off (-Wno-thread-safety-negative), or
    • downgrading to a Clang / LLVM version released before October 2020, or maybe
    • upgrading to a newer Clang / LLVM (unclear how new it needs to be).