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{
157 MemberMutexDescriptor(
161 {CDM::CXXMethod, {
"std",
"unlock"}, 0}),
162 FirstArgMutexDescriptor({CDM::CLibrary, {
"pthread_mutex_lock"}, 1},
163 {CDM::CLibrary, {
"pthread_mutex_unlock"}, 1}),
164 FirstArgMutexDescriptor({CDM::CLibrary, {
"mtx_lock"}, 1},
165 {CDM::CLibrary, {
"mtx_unlock"}, 1}),
166 FirstArgMutexDescriptor({CDM::CLibrary, {
"pthread_mutex_trylock"}, 1},
167 {CDM::CLibrary, {
"pthread_mutex_unlock"}, 1}),
168 FirstArgMutexDescriptor({CDM::CLibrary, {
"mtx_trylock"}, 1},
169 {CDM::CLibrary, {
"mtx_unlock"}, 1}),
170 FirstArgMutexDescriptor({CDM::CLibrary, {
"mtx_timedlock"}, 1},
171 {CDM::CLibrary, {
"mtx_unlock"}, 1}),
172 RAIIMutexDescriptor(
"lock_guard"),
173 RAIIMutexDescriptor(
"unique_lock")};
176 {CDM::CLibrary, {
"getc"}},
177 {CDM::CLibrary, {
"fgets"}},
178 {CDM::CLibrary, {
"read"}},
179 {CDM::CLibrary, {
"recv"}}};
181 const BugType BlockInCritSectionBugType{
182 this,
"Call to blocking function in critical section",
"Blocking Error"};
186 [[nodiscard]]
const NoteTag *createCritSectionNote(CritSectionMarker M,
189 [[nodiscard]] std::optional<MutexDescriptor>
193 void handleLock(
const MutexDescriptor &Mutex,
const CallEvent &
Call,
196 void handleUnlock(
const MutexDescriptor &Mutex,
const CallEvent &
Call,
199 [[nodiscard]]
bool isBlockingInCritSection(
const CallEvent &
Call,
218struct std::iterator_traits<
219 typename
llvm::ImmutableList<CritSectionMarker>::iterator> {
227std::optional<MutexDescriptor>
228BlockInCriticalSectionChecker::checkDescriptorMatch(
const CallEvent &
Call,
231 const auto Descriptor =
232 llvm::find_if(MutexDescriptors, [&
Call, IsLock](
auto &&Descriptor) {
234 [&
Call, IsLock](
auto &&DescriptorImpl) {
235 return DescriptorImpl.matches(
Call, IsLock);
239 if (Descriptor != MutexDescriptors.end())
245 const MutexDescriptor &Descriptor,
248 [&
Call, IsLock](
auto &&Descriptor) {
249 return Descriptor.getRegion(
Call, IsLock);
254void BlockInCriticalSectionChecker::handleLock(
255 const MutexDescriptor &LockDescriptor,
const CallEvent &
Call,
262 const CritSectionMarker MarkToAdd{
Call.getOriginExpr(), MutexRegion};
264 C.getState()->add<ActiveCritSections>(MarkToAdd);
265 C.addTransition(StateWithLockEvent, createCritSectionNote(MarkToAdd,
C));
268void BlockInCriticalSectionChecker::handleUnlock(
269 const MutexDescriptor &UnlockDescriptor,
const CallEvent &
Call,
277 const auto ActiveSections = State->get<ActiveCritSections>();
278 const auto MostRecentLock =
279 llvm::find_if(ActiveSections, [MutexRegion](
auto &&Marker) {
280 return Marker.LockReg == MutexRegion;
282 if (MostRecentLock == ActiveSections.end())
286 auto &Factory = State->get_context<ActiveCritSections>();
287 llvm::ImmutableList<CritSectionMarker> NewList = Factory.getEmptyList();
288 for (
auto It = ActiveSections.begin(), End = ActiveSections.end(); It != End;
290 if (It != MostRecentLock)
291 NewList = Factory.add(*It, NewList);
294 State = State->set<ActiveCritSections>(NewList);
295 C.addTransition(State);
298bool BlockInCriticalSectionChecker::isBlockingInCritSection(
300 return BlockingFunctions.contains(
Call) &&
301 !
C.getState()->get<ActiveCritSections>().isEmpty();
304void BlockInCriticalSectionChecker::checkPostCall(
const CallEvent &
Call,
306 if (isBlockingInCritSection(
Call,
C)) {
307 reportBlockInCritSection(
Call,
C);
308 }
else if (std::optional<MutexDescriptor> LockDesc =
309 checkDescriptorMatch(
Call,
C,
true)) {
310 handleLock(*LockDesc,
Call,
C);
311 }
else if (std::optional<MutexDescriptor> UnlockDesc =
312 checkDescriptorMatch(
Call,
C,
false)) {
313 handleUnlock(*UnlockDesc,
Call,
C);
317void BlockInCriticalSectionChecker::reportBlockInCritSection(
319 ExplodedNode *ErrNode =
C.generateNonFatalErrorNode(
C.getState());
324 llvm::raw_string_ostream os(msg);
325 os <<
"Call to blocking function '" <<
Call.getCalleeIdentifier()->getName()
326 <<
"' inside of critical section";
327 auto R = std::make_unique<PathSensitiveBugReport>(BlockInCritSectionBugType,
329 R->addRange(
Call.getSourceRange());
330 R->markInteresting(
Call.getReturnValue());
331 C.emitReport(std::move(R));
335BlockInCriticalSectionChecker::createCritSectionNote(CritSectionMarker M,
337 const BugType *BT = &this->BlockInCritSectionBugType;
339 llvm::raw_ostream &OS) {
344 const auto CritSectionBegins =
348 CritSectionBegins, std::back_inserter(LocksForMutex),
349 [M](
const auto &Marker) { return Marker.LockReg == M.LockReg; });
350 if (LocksForMutex.empty())
355 std::reverse(LocksForMutex.begin(), LocksForMutex.end());
359 const auto Position =
360 llvm::find_if(std::as_const(LocksForMutex), [M](
const auto &Marker) {
361 return Marker.LockExpr == M.LockExpr;
363 if (Position == LocksForMutex.end())
368 if (LocksForMutex.size() == 1) {
369 OS <<
"Entering critical section here";
373 const auto IndexOfLock =
374 std::distance(std::as_const(LocksForMutex).begin(), Position);
376 const auto OrdinalOfLock = IndexOfLock + 1;
377 OS <<
"Entering critical section for the " << OrdinalOfLock
378 << llvm::getOrdinalSuffix(OrdinalOfLock) <<
" time here";
382void ento::registerBlockInCriticalSectionChecker(
CheckerManager &mgr) {
386bool 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