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 Guard = &
Call.getCalleeAnalysisDeclContext()->getASTContext().Idents.get(
108 IdentifierInfoInitialized =
true;
112 template <
typename T>
bool matchesImpl(
const CallEvent &
Call)
const {
113 const T *
C = dyn_cast<T>(&
Call);
117 cast<CXXRecordDecl>(
C->getDecl()->getParent())->getIdentifier();
122 RAIIMutexDescriptor(StringRef GuardName) : GuardName(GuardName) {}
124 initIdentifierInfo(
Call);
126 return matchesImpl<CXXConstructorCall>(
Call);
128 return matchesImpl<CXXDestructorCall>(
Call);
134 if (std::optional<SVal> Object =
Call.getReturnValueUnderConstruction()) {
135 LockRegion =
Object->getAsRegion();
138 LockRegion = cast<CXXDestructorCall>(
Call).getCXXThisVal().getAsRegion();
144using MutexDescriptor =
145 std::variant<FirstArgMutexDescriptor, MemberMutexDescriptor,
146 RAIIMutexDescriptor>;
148class BlockInCriticalSectionChecker :
public Checker<check::PostCall> {
150 const std::array<MutexDescriptor, 8> MutexDescriptors{
151 MemberMutexDescriptor(
165 RAIIMutexDescriptor(
"lock_guard"),
166 RAIIMutexDescriptor(
"unique_lock")};
168 const std::array<CallDescription, 5> BlockingFunctions{
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,
211struct iterator_traits<
212 typename
llvm::ImmutableList<CritSectionMarker>::iterator> {
221std::optional<MutexDescriptor>
222BlockInCriticalSectionChecker::checkDescriptorMatch(
const CallEvent &
Call,
225 const auto Descriptor =
226 llvm::find_if(MutexDescriptors, [&
Call, IsLock](
auto &&Descriptor) {
228 [&
Call, IsLock](
auto &&DescriptorImpl) {
229 return DescriptorImpl.matches(
Call, IsLock);
233 if (Descriptor != MutexDescriptors.end())
239 const MutexDescriptor &Descriptor,
242 [&
Call, IsLock](
auto &&Descriptor) {
243 return Descriptor.getRegion(
Call, IsLock);
248void BlockInCriticalSectionChecker::handleLock(
249 const MutexDescriptor &LockDescriptor,
const CallEvent &
Call,
256 const CritSectionMarker MarkToAdd{
Call.getOriginExpr(), MutexRegion};
258 C.getState()->add<ActiveCritSections>(MarkToAdd);
259 C.addTransition(StateWithLockEvent, createCritSectionNote(MarkToAdd,
C));
262void BlockInCriticalSectionChecker::handleUnlock(
263 const MutexDescriptor &UnlockDescriptor,
const CallEvent &
Call,
271 const auto ActiveSections = State->get<ActiveCritSections>();
272 const auto MostRecentLock =
273 llvm::find_if(ActiveSections, [MutexRegion](
auto &&Marker) {
274 return Marker.LockReg == MutexRegion;
276 if (MostRecentLock == ActiveSections.end())
280 auto &Factory = State->get_context<ActiveCritSections>();
281 llvm::ImmutableList<CritSectionMarker> NewList = Factory.getEmptyList();
282 for (
auto It = ActiveSections.begin(), End = ActiveSections.end(); It != End;
284 if (It != MostRecentLock)
285 NewList = Factory.add(*It, NewList);
288 State = State->set<ActiveCritSections>(NewList);
289 C.addTransition(State);
292bool BlockInCriticalSectionChecker::isBlockingInCritSection(
294 return llvm::any_of(BlockingFunctions,
295 [&
Call](
auto &&Fn) {
return Fn.matches(
Call); }) &&
296 !
C.getState()->get<ActiveCritSections>().isEmpty();
299void BlockInCriticalSectionChecker::checkPostCall(
const CallEvent &
Call,
301 if (isBlockingInCritSection(
Call,
C)) {
302 reportBlockInCritSection(
Call,
C);
303 }
else if (std::optional<MutexDescriptor> LockDesc =
304 checkDescriptorMatch(
Call,
C,
true)) {
305 handleLock(*LockDesc,
Call,
C);
306 }
else if (std::optional<MutexDescriptor> UnlockDesc =
307 checkDescriptorMatch(
Call,
C,
false)) {
308 handleUnlock(*UnlockDesc,
Call,
C);
312void BlockInCriticalSectionChecker::reportBlockInCritSection(
314 ExplodedNode *ErrNode =
C.generateNonFatalErrorNode(
C.getState());
319 llvm::raw_string_ostream os(msg);
320 os <<
"Call to blocking function '" <<
Call.getCalleeIdentifier()->getName()
321 <<
"' inside of critical section";
322 auto R = std::make_unique<PathSensitiveBugReport>(BlockInCritSectionBugType,
324 R->addRange(
Call.getSourceRange());
325 R->markInteresting(
Call.getReturnValue());
326 C.emitReport(std::move(R));
330BlockInCriticalSectionChecker::createCritSectionNote(CritSectionMarker M,
332 const BugType *BT = &this->BlockInCritSectionBugType;
334 llvm::raw_ostream &OS) {
339 const auto CritSectionBegins =
343 CritSectionBegins, std::back_inserter(LocksForMutex),
344 [M](
const auto &Marker) { return Marker.LockReg == M.LockReg; });
345 if (LocksForMutex.empty())
350 std::reverse(LocksForMutex.begin(), LocksForMutex.end());
354 const auto Position =
355 llvm::find_if(std::as_const(LocksForMutex), [M](
const auto &Marker) {
356 return Marker.LockExpr == M.LockExpr;
358 if (Position == LocksForMutex.end())
363 if (LocksForMutex.size() == 1) {
364 OS <<
"Entering critical section here";
368 const auto IndexOfLock =
369 std::distance(std::as_const(LocksForMutex).begin(), Position);
371 const auto OrdinalOfLock = IndexOfLock + 1;
372 OS <<
"Entering critical section for the " << OrdinalOfLock
373 << llvm::getOrdinalSuffix(OrdinalOfLock) <<
" time here";
377void ento::registerBlockInCriticalSectionChecker(
CheckerManager &mgr) {
381bool 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
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