Edit

Share via


Warning C26133

Caller failing to hold lock 'lock 1' before calling function 'function name', but 'lock 2' is held instead. Possible annotation mismatch.

Warning C26133 is issued when the analyzer detects that the lock required to call a function isn't held when the function is called. However, another lock that appears to be related is held. It's possible the code is thread-safe, and the annotations need to be updated.

This diagnostic usually doesn't indicate a bug in the code, but rather a mismatch between the annotations and the actual locking behavior. If so, the diagnostic should be resolved as there may be other static analysis issues that aren't being reported due to the inconsistent annotations.

Examples

In the following example, C26133 is emitted when DoTaskWithCustomLock is called.

warning C26133: Caller failing to hold lock 'customLock01' before calling function 'DoTaskWithCustomLock', but '(&customLock01)->cs' is held instead. Possible annotation mismatch.

#include <sal.h>

struct CustomLock
{
    int cs; // "Critical Section"
};

_Acquires_exclusive_lock_(criticalSection->cs) // notice the `->` indirection
void CustomLockAcquire(CustomLock* criticalSection);

_Releases_lock_(criticalSection->cs) // notice the `->` indirection
void CustomLockRelease(CustomLock* criticalSection);

CustomLock customLock01;

_Requires_lock_held_(customLock01) void DoTaskWithCustomLock();

void DoTask()
{
    CustomLockAcquire(&customLock01);
    DoTaskWithCustomLock(); // C26133
    CustomLockRelease(&customLock01);
}

In this example, the DoTask function is thread-safe and behaves as designed, but that design isn't correctly reflected in the concurrency SAL annotations. Fix by adjusting the annotations on the custom locking functions to use criticalSection rather than criticalSection->cs. The warning could also be fixed by changing the _Requires_lock_held_ annotation from customLock01 to customLock01.cs.

#include <sal.h>

struct CustomLock
{
    int cs; // "Critical Section"
};

_Acquires_exclusive_lock_(criticalSection)
void CustomLockAcquire(CustomLock* criticalSection);

_Releases_lock_(criticalSection)
void CustomLockRelease(CustomLock* criticalSection);

CustomLock customLock01;

_Requires_lock_held_(customLock01) void DoTaskWithCustomLock();

void DoTask()
{
    CustomLockAcquire(&customLock01);
    DoTaskWithCustomLock();
    CustomLockRelease(&customLock01);
}