1 //= UnixAPIChecker.h - Checks preconditions for various Unix APIs --*- C++ -*-//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This defines UnixAPIChecker, which is an assortment of checks on calls
11 // to various, widely used UNIX/Posix functions.
13 //===----------------------------------------------------------------------===//
15 #include "ClangSACheckers.h"
16 #include "clang/StaticAnalyzer/Core/CheckerV2.h"
17 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
18 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
19 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
20 #include "clang/Basic/TargetInfo.h"
21 #include "llvm/ADT/Optional.h"
22 #include "llvm/ADT/StringSwitch.h"
25 using namespace clang;
30 class UnixAPIChecker : public CheckerV2< check::PreStmt<CallExpr> > {
38 mutable BugType *BTypes[NumChecks];
41 mutable Optional<uint64_t> Val_O_CREAT;
44 UnixAPIChecker() { memset(BTypes, 0, sizeof(*BTypes) * NumChecks); }
46 for (unsigned i=0; i != NumChecks; ++i)
50 void checkPreStmt(const CallExpr *CE, CheckerContext &C) const;
52 } //end anonymous namespace
54 //===----------------------------------------------------------------------===//
56 //===----------------------------------------------------------------------===//
58 static inline void LazyInitialize(BugType *&BT, const char *name) {
61 BT = new BugType(name, "Unix API");
64 //===----------------------------------------------------------------------===//
65 // "open" (man 2 open)
66 //===----------------------------------------------------------------------===//
68 static void CheckOpen(CheckerContext &C, const UnixAPIChecker &UC,
69 const CallExpr *CE, BugType *&BT) {
70 // The definition of O_CREAT is platform specific. We need a better way
71 // of querying this information from the checking environment.
72 if (!UC.Val_O_CREAT.hasValue()) {
73 if (C.getASTContext().Target.getTriple().getVendor() == llvm::Triple::Apple)
74 UC.Val_O_CREAT = 0x0200;
76 // FIXME: We need a more general way of getting the O_CREAT value.
77 // We could possibly grovel through the preprocessor state, but
78 // that would require passing the Preprocessor object to the ExprEngine.
83 LazyInitialize(BT, "Improper use of 'open'");
85 // Look at the 'oflags' argument for the O_CREAT flag.
86 const GRState *state = C.getState();
88 if (CE->getNumArgs() < 2) {
89 // The frontend should issue a warning for this case, so this is a sanity
94 // Now check if oflags has O_CREAT set.
95 const Expr *oflagsEx = CE->getArg(1);
96 const SVal V = state->getSVal(oflagsEx);
97 if (!isa<NonLoc>(V)) {
98 // The case where 'V' can be a location can only be due to a bad header,
99 // so in this case bail out.
102 NonLoc oflags = cast<NonLoc>(V);
104 cast<NonLoc>(C.getSValBuilder().makeIntVal(UC.Val_O_CREAT.getValue(),
105 oflagsEx->getType()));
106 SVal maskedFlagsUC = C.getSValBuilder().evalBinOpNN(state, BO_And,
108 oflagsEx->getType());
109 if (maskedFlagsUC.isUnknownOrUndef())
111 DefinedSVal maskedFlags = cast<DefinedSVal>(maskedFlagsUC);
113 // Check if maskedFlags is non-zero.
114 const GRState *trueState, *falseState;
115 llvm::tie(trueState, falseState) = state->assume(maskedFlags);
117 // Only emit an error if the value of 'maskedFlags' is properly
119 if (!(trueState && !falseState))
122 if (CE->getNumArgs() < 3) {
123 ExplodedNode *N = C.generateSink(trueState);
127 EnhancedBugReport *report =
128 new EnhancedBugReport(*BT,
129 "Call to 'open' requires a third argument when "
130 "the 'O_CREAT' flag is set", N);
131 report->addRange(oflagsEx->getSourceRange());
132 C.EmitReport(report);
136 //===----------------------------------------------------------------------===//
138 //===----------------------------------------------------------------------===//
140 static void CheckPthreadOnce(CheckerContext &C, const UnixAPIChecker &,
141 const CallExpr *CE, BugType *&BT) {
143 // This is similar to 'CheckDispatchOnce' in the MacOSXAPIChecker.
144 // They can possibly be refactored.
146 LazyInitialize(BT, "Improper use of 'pthread_once'");
148 if (CE->getNumArgs() < 1)
151 // Check if the first argument is stack allocated. If so, issue a warning
152 // because that's likely to be bad news.
153 const GRState *state = C.getState();
154 const MemRegion *R = state->getSVal(CE->getArg(0)).getAsRegion();
155 if (!R || !isa<StackSpaceRegion>(R->getMemorySpace()))
158 ExplodedNode *N = C.generateSink(state);
162 llvm::SmallString<256> S;
163 llvm::raw_svector_ostream os(S);
164 os << "Call to 'pthread_once' uses";
165 if (const VarRegion *VR = dyn_cast<VarRegion>(R))
166 os << " the local variable '" << VR->getDecl()->getName() << '\'';
168 os << " stack allocated memory";
169 os << " for the \"control\" value. Using such transient memory for "
170 "the control value is potentially dangerous.";
171 if (isa<VarRegion>(R) && isa<StackLocalsSpaceRegion>(R->getMemorySpace()))
172 os << " Perhaps you intended to declare the variable as 'static'?";
174 EnhancedBugReport *report = new EnhancedBugReport(*BT, os.str(), N);
175 report->addRange(CE->getArg(0)->getSourceRange());
176 C.EmitReport(report);
179 //===----------------------------------------------------------------------===//
180 // "malloc" with allocation size 0
181 //===----------------------------------------------------------------------===//
183 // FIXME: Eventually this should be rolled into the MallocChecker, but this
184 // check is more basic and is valuable for widespread use.
185 static void CheckMallocZero(CheckerContext &C, const UnixAPIChecker &UC,
186 const CallExpr *CE, BugType *&BT) {
188 // Sanity check that malloc takes one argument.
189 if (CE->getNumArgs() != 1)
192 // Check if the allocation size is 0.
193 const GRState *state = C.getState();
194 SVal argVal = state->getSVal(CE->getArg(0));
196 if (argVal.isUnknownOrUndef())
199 const GRState *trueState, *falseState;
200 llvm::tie(trueState, falseState) = state->assume(cast<DefinedSVal>(argVal));
202 // Is the value perfectly constrained to zero?
203 if (falseState && !trueState) {
204 ExplodedNode *N = C.generateSink(falseState);
208 // FIXME: Add reference to CERT advisory, and/or C99 standard in bug
211 LazyInitialize(BT, "Undefined allocation of 0 bytes");
213 EnhancedBugReport *report =
214 new EnhancedBugReport(*BT, "Call to 'malloc' has an allocation size"
216 report->addRange(CE->getArg(0)->getSourceRange());
217 report->addVisitorCreator(bugreporter::registerTrackNullOrUndefValue,
219 C.EmitReport(report);
222 // Assume the the value is non-zero going forward.
224 if (trueState != state) {
225 C.addTransition(trueState);
229 //===----------------------------------------------------------------------===//
230 // Central dispatch function.
231 //===----------------------------------------------------------------------===//
233 typedef void (*SubChecker)(CheckerContext &C, const UnixAPIChecker &UC,
234 const CallExpr *CE, BugType *&BT);
238 const UnixAPIChecker *UC;
241 SubCheck(SubChecker sc, const UnixAPIChecker *uc, BugType *& bt)
242 : SC(sc), UC(uc), BT(&bt) {}
243 SubCheck() : SC(NULL), UC(NULL), BT(NULL) {}
245 void run(CheckerContext &C, const CallExpr *CE) const {
250 } // end anonymous namespace
252 void UnixAPIChecker::checkPreStmt(const CallExpr *CE, CheckerContext &C) const {
253 // Get the callee. All the functions we care about are C functions
254 // with simple identifiers.
255 const GRState *state = C.getState();
256 const Expr *Callee = CE->getCallee();
257 const FunctionTextRegion *Fn =
258 dyn_cast_or_null<FunctionTextRegion>(state->getSVal(Callee).getAsRegion());
263 const IdentifierInfo *FI = Fn->getDecl()->getIdentifier();
268 llvm::StringSwitch<SubCheck>(FI->getName())
270 SubCheck(CheckOpen, this, BTypes[OpenFn]))
271 .Case("pthread_once",
272 SubCheck(CheckPthreadOnce, this, BTypes[PthreadOnceFn]))
274 SubCheck(CheckMallocZero, this, BTypes[MallocZero]))
275 .Default(SubCheck());
280 //===----------------------------------------------------------------------===//
282 //===----------------------------------------------------------------------===//
284 void ento::registerUnixAPIChecker(CheckerManager &mgr) {
285 mgr.registerChecker<UnixAPIChecker>();