25 #include "llvm/ADT/SmallString.h"
26 #include "llvm/ADT/StringSwitch.h"
27 #include "llvm/Support/raw_ostream.h"
29 using namespace clang;
33 class MacOSXAPIChecker :
public Checker< check::PreStmt<CallExpr> > {
34 mutable std::unique_ptr<BugType> BT_dispatchOnce;
36 static const ObjCIvarRegion *getParentIvarRegion(
const MemRegion *R);
39 void checkPreStmt(
const CallExpr *CE, CheckerContext &C)
const;
41 void CheckDispatchOnce(CheckerContext &C,
const CallExpr *CE,
42 StringRef FName)
const;
44 typedef void (MacOSXAPIChecker::*SubChecker)(CheckerContext &,
46 StringRef FName)
const;
54 const ObjCIvarRegion *
55 MacOSXAPIChecker::getParentIvarRegion(
const MemRegion *R) {
56 const SubRegion *SR = dyn_cast<SubRegion>(R);
58 if (
const ObjCIvarRegion *IR = dyn_cast<ObjCIvarRegion>(SR))
60 SR = dyn_cast<SubRegion>(SR->getSuperRegion());
65 void MacOSXAPIChecker::CheckDispatchOnce(CheckerContext &C,
const CallExpr *CE,
66 StringRef FName)
const {
72 const MemRegion *R =
C.getSVal(CE->
getArg(0)).getAsRegion();
77 const MemRegion *RB = R->getBaseRegion();
78 const MemSpaceRegion *RS = RB->getMemorySpace();
79 if (isa<GlobalsSpaceRegion>(RS))
87 StringRef TrimmedFName = FName.ltrim(
'_');
88 if (TrimmedFName != FName)
93 llvm::raw_svector_ostream os(S);
94 bool SuggestStatic =
false;
95 os <<
"Call to '" << FName <<
"' uses";
96 if (
const VarRegion *VR = dyn_cast<VarRegion>(RB)) {
97 const VarDecl *VD = VR->getDecl();
107 os <<
" memory within";
109 os <<
" the block variable '";
111 os <<
" the local variable '";
112 os << VR->getDecl()->
getName() <<
'\'';
113 SuggestStatic =
true;
114 }
else if (
const ObjCIvarRegion *IVR = getParentIvarRegion(R)) {
116 os <<
" memory within";
117 os <<
" the instance variable '" << IVR->getDecl()->getName() <<
'\'';
118 }
else if (isa<HeapSpaceRegion>(RS)) {
119 os <<
" heap-allocated memory";
120 }
else if (isa<UnknownSpaceRegion>(RS)) {
128 os <<
" stack allocated memory";
130 os <<
" for the predicate value. Using such transient memory for "
131 "the predicate is potentially dangerous.";
133 os <<
" Perhaps you intended to declare the variable as 'static'?";
135 ExplodedNode *N =
C.generateErrorNode();
139 if (!BT_dispatchOnce)
140 BT_dispatchOnce.reset(
new BugType(
this,
"Improper use of 'dispatch_once'",
141 "API Misuse (Apple)"));
144 std::make_unique<PathSensitiveBugReport>(*BT_dispatchOnce, os.str(), N);
146 C.emitReport(std::move(report));
153 void MacOSXAPIChecker::checkPreStmt(
const CallExpr *CE,
154 CheckerContext &C)
const {
155 StringRef Name =
C.getCalleeName(CE);
160 llvm::StringSwitch<SubChecker>(Name)
161 .Cases(
"dispatch_once",
164 &MacOSXAPIChecker::CheckDispatchOnce)
168 (this->*SC)(C, CE, Name);
175 void ento::registerMacOSXAPIChecker(CheckerManager &mgr) {
176 mgr.registerChecker<MacOSXAPIChecker>();
179 bool ento::shouldRegisterMacOSXAPIChecker(
const CheckerManager &mgr) {