Files
clang-p2996/clang/test/Analysis/block-in-critical-section.cpp
Anna Zaks c154f7bc37 [analyzer] Add a checker that detects blocks in critical sections
This checker should find the calls to blocking functions (for example: sleep, getc, fgets,read,recv etc.) inside a critical section. When sleep(x) is called while a mutex is held, other threads cannot lock the same mutex. This might take some time, leading to bad performance or even deadlock.

Example:

mutex_t m;

void f() {
  sleep(1000); // Error: sleep() while m is locked! [f() is called from foobar() while m is locked]
  // do some work
}

void foobar() {
  lock(m);
  f();
  unlock(m);
}

A patch by zdtorok (Zoltán Dániel Török)!

Differential Revision: https://reviews.llvm.org/D21506

llvm-svn: 282011
2016-09-20 20:28:50 +00:00

51 lines
1.2 KiB
C++

// RUN: %clang_cc1 -analyze -analyzer-checker=alpha.unix.BlockInCriticalSection -std=c++11 -verify %s
void sleep(int x) {}
namespace std {
struct mutex {
void lock() {}
void unlock() {}
};
}
void testBlockInCriticalSection() {
std::mutex m;
m.lock();
sleep(3); // expected-warning {{A blocking function %s is called inside a critical section}}
m.unlock();
}
void testBlockInCriticalSectionWithNestedMutexes() {
std::mutex m, n, k;
m.lock();
n.lock();
k.lock();
sleep(3); // expected-warning {{A blocking function %s is called inside a critical section}}
k.unlock();
sleep(5); // expected-warning {{A blocking function %s is called inside a critical section}}
n.unlock();
sleep(3); // expected-warning {{A blocking function %s is called inside a critical section}}
m.unlock();
sleep(3); // no-warning
}
void f() {
sleep(1000); // expected-warning {{A blocking function %s is called inside a critical section}}
}
void testBlockInCriticalSectionInterProcedural() {
std::mutex m;
m.lock();
f();
m.unlock();
}
void testBlockInCriticalSectionUnexpectedUnlock() {
std::mutex m;
m.unlock();
sleep(1); // no-warning
m.lock();
sleep(1); // expected-warning {{A blocking function %s is called inside a critical section}}
}