Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,25 @@ class RAIIMutexDescriptor {
return false;
const IdentifierInfo *II =
cast<CXXRecordDecl>(C->getDecl()->getParent())->getIdentifier();
return II == Guard;
if (II != Guard)
return false;

// For unique_lock, check if it's constructed with a ctor that takes the tag
// type defer_lock_t. In this case, the lock is not acquired.
if constexpr (std::is_same_v<T, CXXConstructorCall>) {
if (GuardName == "unique_lock" && C->getNumArgs() >= 2) {
const Expr *SecondArg = C->getArgExpr(1);
QualType ArgType = SecondArg->getType().getNonReferenceType();
QualType UnqualifiedType = ArgType.getUnqualifiedType();
if (const auto *RD = UnqualifiedType->getAsRecordDecl();
RD && RD->getName() == "defer_lock_t" &&
RD->getDeclContext()->isStdNamespace()) {
return false;
}
}
}

return true;
}

public:
Expand Down
9 changes: 9 additions & 0 deletions clang/test/Analysis/block-in-critical-section.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,12 @@ struct lock_guard {
lock_guard<T>(std::mutex) {}
~lock_guard<T>() {}
};
struct defer_lock_t {};
constexpr defer_lock_t defer_lock{};
template<typename T>
struct unique_lock {
unique_lock<T>(std::mutex) {}
unique_lock<T>(std::mutex, defer_lock_t) {} // defer_lock parameter
~unique_lock<T>() {}
};
template<typename T>
Expand Down Expand Up @@ -309,3 +312,9 @@ void testTrylockCurrentlyFalsePositive(pthread_mutex_t *m) {
// FIXME: this is a false positive, the lock was not acquired
}
}

void testBlockInCriticalSectionUniqueLockWithDeferLock() {
std::mutex g_mutex;
std::unique_lock<std::mutex> lock(g_mutex, std::defer_lock);
sleep(1); // no-warning
}
Loading