26#include "llvm/ADT/STLExtras.h"
27#include "llvm/ADT/SmallString.h"
28#include "llvm/ADT/StringExtras.h"
39struct CritSectionMarker {
40 const Expr *LockExpr{};
43 void Profile(llvm::FoldingSetNodeID &ID)
const {
48 [[nodiscard]]
constexpr bool
50 return LockExpr ==
Other.LockExpr && LockReg ==
Other.LockReg;
52 [[nodiscard]]
constexpr bool
54 return !(*
this ==
Other);
58class CallDescriptionBasedMatcher {
65 : LockFn(
std::move(LockFn)), UnlockFn(
std::move(UnlockFn)) {}
74class FirstArgMutexDescriptor :
public CallDescriptionBasedMatcher {
77 : CallDescriptionBasedMatcher(
std::move(LockFn),
std::move(UnlockFn)) {}
80 return Call.getArgSVal(0).getAsRegion();
84class MemberMutexDescriptor :
public CallDescriptionBasedMatcher {
87 : CallDescriptionBasedMatcher(
std::move(LockFn),
std::move(UnlockFn)) {}
90 return cast<CXXMemberCall>(
Call).getCXXThisVal().getAsRegion();
94class RAIIMutexDescriptor {
96 mutable bool IdentifierInfoInitialized{};
100 if (!IdentifierInfoInitialized) {
106 const auto &ASTCtx =
Call.getState()->getStateManager().getContext();
107 Guard = &ASTCtx.Idents.get(GuardName);
111 template <
typename T>
bool matchesImpl(
const CallEvent &
Call)
const {
112 const T *
C = dyn_cast<T>(&
Call);
116 cast<CXXRecordDecl>(
C->getDecl()->getParent())->getIdentifier();
121 RAIIMutexDescriptor(StringRef GuardName) : GuardName(GuardName) {}
123 initIdentifierInfo(
Call);
125 return matchesImpl<CXXConstructorCall>(
Call);
127 return matchesImpl<CXXDestructorCall>(
Call);
133 if (std::optional<SVal> Object =
Call.getReturnValueUnderConstruction()) {
134 LockRegion =
Object->getAsRegion();
137 LockRegion = cast<CXXDestructorCall>(
Call).getCXXThisVal().getAsRegion();
143using MutexDescriptor =
144 std::variant<FirstArgMutexDescriptor, MemberMutexDescriptor,
145 RAIIMutexDescriptor>;
147class BlockInCriticalSectionChecker :
public Checker<check::PostCall> {
149 const std::array<MutexDescriptor, 8> MutexDescriptors{
150 MemberMutexDescriptor({CDM::CXXMethod,
151 {
"std",
"mutex",
"lock"},
153 {CDM::CXXMethod, {
"std",
"mutex",
"unlock"}, 0}),
154 FirstArgMutexDescriptor({CDM::CLibrary, {
"pthread_mutex_lock"}, 1},
155 {CDM::CLibrary, {
"pthread_mutex_unlock"}, 1}),
156 FirstArgMutexDescriptor({CDM::CLibrary, {
"mtx_lock"}, 1},
157 {CDM::CLibrary, {
"mtx_unlock"}, 1}),
158 FirstArgMutexDescriptor({CDM::CLibrary, {
"pthread_mutex_trylock"}, 1},
159 {CDM::CLibrary, {
"pthread_mutex_unlock"}, 1}),
160 FirstArgMutexDescriptor({CDM::CLibrary, {
"mtx_trylock"}, 1},
161 {CDM::CLibrary, {
"mtx_unlock"}, 1}),
162 FirstArgMutexDescriptor({CDM::CLibrary, {
"mtx_timedlock"}, 1},
163 {CDM::CLibrary, {
"mtx_unlock"}, 1}),
164 RAIIMutexDescriptor(
"lock_guard"),
165 RAIIMutexDescriptor(
"unique_lock")};
168 {CDM::CLibrary, {
"getc"}},
169 {CDM::CLibrary, {
"fgets"}},
170 {CDM::CLibrary, {
"read"}},
171 {CDM::CLibrary, {
"recv"}}};
173 const BugType BlockInCritSectionBugType{
174 this,
"Call to blocking function in critical section",
"Blocking Error"};
178 [[nodiscard]]
const NoteTag *createCritSectionNote(CritSectionMarker M,
181 [[nodiscard]] std::optional<MutexDescriptor>
185 void handleLock(
const MutexDescriptor &Mutex,
const CallEvent &
Call,
188 void handleUnlock(
const MutexDescriptor &Mutex,
const CallEvent &
Call,
191 [[nodiscard]]
bool isBlockingInCritSection(
const CallEvent &
Call,
210struct std::iterator_traits<
211 typename
llvm::ImmutableList<CritSectionMarker>::iterator> {
219std::optional<MutexDescriptor>
220BlockInCriticalSectionChecker::checkDescriptorMatch(
const CallEvent &
Call,
223 const auto Descriptor =
224 llvm::find_if(MutexDescriptors, [&
Call, IsLock](
auto &&Descriptor) {
226 [&
Call, IsLock](
auto &&DescriptorImpl) {
227 return DescriptorImpl.matches(
Call, IsLock);
231 if (Descriptor != MutexDescriptors.end())
237 const MutexDescriptor &Descriptor,
240 [&
Call, IsLock](
auto &&Descriptor) {
241 return Descriptor.getRegion(
Call, IsLock);
246void BlockInCriticalSectionChecker::handleLock(
247 const MutexDescriptor &LockDescriptor,
const CallEvent &
Call,
254 const CritSectionMarker MarkToAdd{
Call.getOriginExpr(), MutexRegion};
256 C.getState()->add<ActiveCritSections>(MarkToAdd);
257 C.addTransition(StateWithLockEvent, createCritSectionNote(MarkToAdd,
C));
260void BlockInCriticalSectionChecker::handleUnlock(
261 const MutexDescriptor &UnlockDescriptor,
const CallEvent &
Call,
269 const auto ActiveSections = State->get<ActiveCritSections>();
270 const auto MostRecentLock =
271 llvm::find_if(ActiveSections, [MutexRegion](
auto &&Marker) {
272 return Marker.LockReg == MutexRegion;
274 if (MostRecentLock == ActiveSections.end())
278 auto &Factory = State->get_context<ActiveCritSections>();
279 llvm::ImmutableList<CritSectionMarker> NewList = Factory.getEmptyList();
280 for (
auto It = ActiveSections.begin(), End = ActiveSections.end(); It != End;
282 if (It != MostRecentLock)
283 NewList = Factory.add(*It, NewList);
286 State = State->set<ActiveCritSections>(NewList);
287 C.addTransition(State);
290bool BlockInCriticalSectionChecker::isBlockingInCritSection(
292 return BlockingFunctions.contains(
Call) &&
293 !
C.getState()->get<ActiveCritSections>().isEmpty();
296void BlockInCriticalSectionChecker::checkPostCall(
const CallEvent &
Call,
298 if (isBlockingInCritSection(
Call,
C)) {
299 reportBlockInCritSection(
Call,
C);
300 }
else if (std::optional<MutexDescriptor> LockDesc =
301 checkDescriptorMatch(
Call,
C,
true)) {
302 handleLock(*LockDesc,
Call,
C);
303 }
else if (std::optional<MutexDescriptor> UnlockDesc =
304 checkDescriptorMatch(
Call,
C,
false)) {
305 handleUnlock(*UnlockDesc,
Call,
C);
309void BlockInCriticalSectionChecker::reportBlockInCritSection(
311 ExplodedNode *ErrNode =
C.generateNonFatalErrorNode(
C.getState());
316 llvm::raw_string_ostream os(msg);
317 os <<
"Call to blocking function '" <<
Call.getCalleeIdentifier()->getName()
318 <<
"' inside of critical section";
319 auto R = std::make_unique<PathSensitiveBugReport>(BlockInCritSectionBugType,
321 R->addRange(
Call.getSourceRange());
322 R->markInteresting(
Call.getReturnValue());
323 C.emitReport(std::move(R));
327BlockInCriticalSectionChecker::createCritSectionNote(CritSectionMarker M,
329 const BugType *BT = &this->BlockInCritSectionBugType;
331 llvm::raw_ostream &OS) {
336 const auto CritSectionBegins =
340 CritSectionBegins, std::back_inserter(LocksForMutex),
341 [M](
const auto &Marker) { return Marker.LockReg == M.LockReg; });
342 if (LocksForMutex.empty())
347 std::reverse(LocksForMutex.begin(), LocksForMutex.end());
351 const auto Position =
352 llvm::find_if(std::as_const(LocksForMutex), [M](
const auto &Marker) {
353 return Marker.LockExpr == M.LockExpr;
355 if (Position == LocksForMutex.end())
360 if (LocksForMutex.size() == 1) {
361 OS <<
"Entering critical section here";
365 const auto IndexOfLock =
366 std::distance(std::as_const(LocksForMutex).begin(), Position);
368 const auto OrdinalOfLock = IndexOfLock + 1;
369 OS <<
"Entering critical section for the " << OrdinalOfLock
370 << llvm::getOrdinalSuffix(OrdinalOfLock) <<
" time here";
374void ento::registerBlockInCriticalSectionChecker(
CheckerManager &mgr) {
378bool ento::shouldRegisterBlockInCriticalSectionChecker(
static const MemRegion * getRegion(const CallEvent &Call, const MutexDescriptor &Descriptor, bool IsLock)
#define REGISTER_LIST_WITH_PROGRAMSTATE(Name, Elem)
Declares an immutable list type NameTy, suitable for placement into the ProgramState.
This represents one expression.
One of these records is kept for each identifier that is lexed.
const BugType & getBugType() const
An immutable set of CallDescriptions.
A CallDescription is a pattern that can be used to match calls based on the qualified name and the ar...
bool matches(const CallEvent &Call) const
Returns true if the CallEvent is a call to a function that matches the CallDescription.
Represents an abstract call to a function or method along a particular path.
CHECKER * registerChecker(AT &&... Args)
Used to register checkers.
const ProgramStateRef & getState() const
MemRegion - The root abstract class for all memory regions.
The tag upon which the TagVisitor reacts.
const ExplodedNode * getErrorNode() const
bool matches(const til::SExpr *E1, const til::SExpr *E2)
The JSON file list parser is used to communicate input to InstallAPI.
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
bool operator==(const CallGraphNode::CallRecord &LHS, const CallGraphNode::CallRecord &RHS)
bool operator!=(CanQual< T > x, CanQual< U > y)
const FunctionProtoType * T
@ Other
Other implicit parameter.
Diagnostic wrappers for TextAPI types for error reporting.
std::ptrdiff_t difference_type
CritSectionMarker & reference
CritSectionMarker * pointer
CritSectionMarker value_type
std::forward_iterator_tag iterator_category