blob: ffe23f14b1c231e78275c88b76e9241c719778f7 [file] [log] [blame]
Ted Kremenek381d1bf2010-02-25 00:20:35 +00001//= UnixAPIChecker.h - Checks preconditions for various Unix APIs --*- C++ -*-//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This defines UnixAPIChecker, which is an assortment of checks on calls
11// to various, widely used UNIX/Posix functions.
12//
13//===----------------------------------------------------------------------===//
14
Argyrios Kyrtzidis027a6ab2011-02-15 07:42:33 +000015#include "ClangSACheckers.h"
Argyrios Kyrtzidisec8605f2011-03-01 01:16:21 +000016#include "clang/StaticAnalyzer/Core/Checker.h"
Argyrios Kyrtzidis695fb502011-02-17 21:39:17 +000017#include "clang/StaticAnalyzer/Core/CheckerManager.h"
Argyrios Kyrtzidis983326f2011-02-23 01:05:36 +000018#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
Ted Kremenek9b663712011-02-10 01:03:03 +000019#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
Argyrios Kyrtzidis983326f2011-02-23 01:05:36 +000020#include "clang/Basic/TargetInfo.h"
Ted Kremenek66d51422010-04-09 20:26:58 +000021#include "llvm/ADT/Optional.h"
Benjamin Kramer5e2d2c22010-03-27 21:19:47 +000022#include "llvm/ADT/StringSwitch.h"
Ted Kremenek381d1bf2010-02-25 00:20:35 +000023#include <fcntl.h>
24
25using namespace clang;
Ted Kremenek9ef65372010-12-23 07:20:52 +000026using namespace ento;
Ted Kremenek66d51422010-04-09 20:26:58 +000027using llvm::Optional;
Ted Kremenek381d1bf2010-02-25 00:20:35 +000028
29namespace {
Argyrios Kyrtzidisec8605f2011-03-01 01:16:21 +000030class UnixAPIChecker : public Checker< check::PreStmt<CallExpr> > {
Jordy Roseaf5b0432011-07-15 06:28:59 +000031 mutable llvm::OwningPtr<BugType> BT_open, BT_pthreadOnce, BT_mallocZero;
Argyrios Kyrtzidis983326f2011-02-23 01:05:36 +000032 mutable Optional<uint64_t> Val_O_CREAT;
Ted Kremenekbace4ba2010-04-08 22:15:34 +000033
34public:
Argyrios Kyrtzidis983326f2011-02-23 01:05:36 +000035 void checkPreStmt(const CallExpr *CE, CheckerContext &C) const;
Jordy Roseaf5b0432011-07-15 06:28:59 +000036
37 void CheckOpen(CheckerContext &C, const CallExpr *CE) const;
38 void CheckPthreadOnce(CheckerContext &C, const CallExpr *CE) const;
Ted Kremenekc1275da2012-01-03 23:43:13 +000039 void CheckCallocZero(CheckerContext &C, const CallExpr *CE) const;
Jordy Roseaf5b0432011-07-15 06:28:59 +000040 void CheckMallocZero(CheckerContext &C, const CallExpr *CE) const;
Ted Kremenekc1275da2012-01-03 23:43:13 +000041 void CheckReallocZero(CheckerContext &C, const CallExpr *CE) const;
Ted Kremenek3e977582012-01-11 08:13:21 +000042 void CheckAllocaZero(CheckerContext &C, const CallExpr *CE) const;
43 void CheckVallocZero(CheckerContext &C, const CallExpr *CE) const;
Jordy Roseaf5b0432011-07-15 06:28:59 +000044
45 typedef void (UnixAPIChecker::*SubChecker)(CheckerContext &,
46 const CallExpr *) const;
Ted Kremenekc1275da2012-01-03 23:43:13 +000047private:
48 bool ReportZeroByteAllocation(CheckerContext &C,
49 const ProgramState *falseState,
50 const Expr *arg,
51 const char *fn_name) const;
Ted Kremenek3e977582012-01-11 08:13:21 +000052 void BasicAllocationCheck(CheckerContext &C,
53 const CallExpr *CE,
54 const unsigned numArgs,
55 const unsigned sizeArg,
56 const char *fn) const;
Ted Kremenek381d1bf2010-02-25 00:20:35 +000057};
58} //end anonymous namespace
59
Ted Kremenek381d1bf2010-02-25 00:20:35 +000060//===----------------------------------------------------------------------===//
61// Utility functions.
62//===----------------------------------------------------------------------===//
63
Jordy Roseaf5b0432011-07-15 06:28:59 +000064static inline void LazyInitialize(llvm::OwningPtr<BugType> &BT,
65 const char *name) {
Ted Kremenek381d1bf2010-02-25 00:20:35 +000066 if (BT)
67 return;
Jordy Roseaf5b0432011-07-15 06:28:59 +000068 BT.reset(new BugType(name, "Unix API"));
Ted Kremenek381d1bf2010-02-25 00:20:35 +000069}
70
71//===----------------------------------------------------------------------===//
72// "open" (man 2 open)
73//===----------------------------------------------------------------------===//
74
Jordy Roseaf5b0432011-07-15 06:28:59 +000075void UnixAPIChecker::CheckOpen(CheckerContext &C, const CallExpr *CE) const {
Ted Kremenekbace4ba2010-04-08 22:15:34 +000076 // The definition of O_CREAT is platform specific. We need a better way
77 // of querying this information from the checking environment.
Jordy Roseaf5b0432011-07-15 06:28:59 +000078 if (!Val_O_CREAT.hasValue()) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000079 if (C.getASTContext().getTargetInfo().getTriple().getVendor()
80 == llvm::Triple::Apple)
Jordy Roseaf5b0432011-07-15 06:28:59 +000081 Val_O_CREAT = 0x0200;
Ted Kremenekbace4ba2010-04-08 22:15:34 +000082 else {
83 // FIXME: We need a more general way of getting the O_CREAT value.
84 // We could possibly grovel through the preprocessor state, but
Argyrios Kyrtzidisd2592a32010-12-22 18:53:44 +000085 // that would require passing the Preprocessor object to the ExprEngine.
Ted Kremenekbace4ba2010-04-08 22:15:34 +000086 return;
87 }
88 }
89
Ted Kremenek381d1bf2010-02-25 00:20:35 +000090 // Look at the 'oflags' argument for the O_CREAT flag.
Ted Kremenek18c66fd2011-08-15 22:09:50 +000091 const ProgramState *state = C.getState();
Ted Kremenek381d1bf2010-02-25 00:20:35 +000092
93 if (CE->getNumArgs() < 2) {
94 // The frontend should issue a warning for this case, so this is a sanity
95 // check.
96 return;
97 }
98
99 // Now check if oflags has O_CREAT set.
100 const Expr *oflagsEx = CE->getArg(1);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000101 const SVal V = state->getSVal(oflagsEx, C.getLocationContext());
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000102 if (!isa<NonLoc>(V)) {
103 // The case where 'V' can be a location can only be due to a bad header,
104 // so in this case bail out.
105 return;
106 }
107 NonLoc oflags = cast<NonLoc>(V);
108 NonLoc ocreateFlag =
Jordy Roseaf5b0432011-07-15 06:28:59 +0000109 cast<NonLoc>(C.getSValBuilder().makeIntVal(Val_O_CREAT.getValue(),
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000110 oflagsEx->getType()));
Ted Kremenek9c149532010-12-01 21:57:22 +0000111 SVal maskedFlagsUC = C.getSValBuilder().evalBinOpNN(state, BO_And,
Ted Kremenek846eabd2010-12-01 21:28:31 +0000112 oflags, ocreateFlag,
113 oflagsEx->getType());
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000114 if (maskedFlagsUC.isUnknownOrUndef())
115 return;
116 DefinedSVal maskedFlags = cast<DefinedSVal>(maskedFlagsUC);
117
118 // Check if maskedFlags is non-zero.
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000119 const ProgramState *trueState, *falseState;
Ted Kremenek28f47b92010-12-01 22:16:56 +0000120 llvm::tie(trueState, falseState) = state->assume(maskedFlags);
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000121
122 // Only emit an error if the value of 'maskedFlags' is properly
123 // constrained;
124 if (!(trueState && !falseState))
125 return;
126
127 if (CE->getNumArgs() < 3) {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000128 ExplodedNode *N = C.generateSink(trueState);
Ted Kremenekc757d792010-02-25 05:44:05 +0000129 if (!N)
130 return;
131
Jordy Roseaf5b0432011-07-15 06:28:59 +0000132 LazyInitialize(BT_open, "Improper use of 'open'");
133
Anna Zakse172e8b2011-08-17 23:00:25 +0000134 BugReport *report =
135 new BugReport(*BT_open,
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000136 "Call to 'open' requires a third argument when "
137 "the 'O_CREAT' flag is set", N);
138 report->addRange(oflagsEx->getSourceRange());
139 C.EmitReport(report);
140 }
141}
142
143//===----------------------------------------------------------------------===//
Ted Kremenek99d98382010-04-08 19:53:31 +0000144// pthread_once
145//===----------------------------------------------------------------------===//
146
Jordy Roseaf5b0432011-07-15 06:28:59 +0000147void UnixAPIChecker::CheckPthreadOnce(CheckerContext &C,
148 const CallExpr *CE) const {
Ted Kremenek99d98382010-04-08 19:53:31 +0000149
150 // This is similar to 'CheckDispatchOnce' in the MacOSXAPIChecker.
151 // They can possibly be refactored.
152
Ted Kremenek99d98382010-04-08 19:53:31 +0000153 if (CE->getNumArgs() < 1)
154 return;
155
156 // Check if the first argument is stack allocated. If so, issue a warning
157 // because that's likely to be bad news.
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000158 const ProgramState *state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +0000159 const MemRegion *R =
160 state->getSVal(CE->getArg(0), C.getLocationContext()).getAsRegion();
Ted Kremenek99d98382010-04-08 19:53:31 +0000161 if (!R || !isa<StackSpaceRegion>(R->getMemorySpace()))
162 return;
163
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000164 ExplodedNode *N = C.generateSink(state);
Ted Kremenek99d98382010-04-08 19:53:31 +0000165 if (!N)
166 return;
167
168 llvm::SmallString<256> S;
169 llvm::raw_svector_ostream os(S);
170 os << "Call to 'pthread_once' uses";
171 if (const VarRegion *VR = dyn_cast<VarRegion>(R))
172 os << " the local variable '" << VR->getDecl()->getName() << '\'';
173 else
174 os << " stack allocated memory";
175 os << " for the \"control\" value. Using such transient memory for "
176 "the control value is potentially dangerous.";
177 if (isa<VarRegion>(R) && isa<StackLocalsSpaceRegion>(R->getMemorySpace()))
178 os << " Perhaps you intended to declare the variable as 'static'?";
179
Jordy Roseaf5b0432011-07-15 06:28:59 +0000180 LazyInitialize(BT_pthreadOnce, "Improper use of 'pthread_once'");
181
Anna Zakse172e8b2011-08-17 23:00:25 +0000182 BugReport *report = new BugReport(*BT_pthreadOnce, os.str(), N);
Ted Kremenek99d98382010-04-08 19:53:31 +0000183 report->addRange(CE->getArg(0)->getSourceRange());
184 C.EmitReport(report);
185}
186
187//===----------------------------------------------------------------------===//
Ted Kremenek3e977582012-01-11 08:13:21 +0000188// "calloc", "malloc", "realloc", "alloca" and "valloc" with allocation size 0
Ted Kremenekb12fbc22010-11-16 18:47:04 +0000189//===----------------------------------------------------------------------===//
Ted Kremenek3e977582012-01-11 08:13:21 +0000190// FIXME: Eventually these should be rolled into the MallocChecker, but right now
191// they're more basic and valuable for widespread use.
Ted Kremenekb12fbc22010-11-16 18:47:04 +0000192
Ted Kremenekc1275da2012-01-03 23:43:13 +0000193// Returns true if we try to do a zero byte allocation, false otherwise.
194// Fills in trueState and falseState.
195static bool IsZeroByteAllocation(const ProgramState *state,
196 const SVal argVal,
197 const ProgramState **trueState,
198 const ProgramState **falseState) {
Ted Kremenek3e977582012-01-11 08:13:21 +0000199 llvm::tie(*trueState, *falseState) =
200 state->assume(cast<DefinedSVal>(argVal));
201
Ted Kremenekc1275da2012-01-03 23:43:13 +0000202 return (*falseState && !*trueState);
203}
204
205// Generates an error report, indicating that the function whose name is given
206// will perform a zero byte allocation.
207// Returns false if an error occured, true otherwise.
208bool UnixAPIChecker::ReportZeroByteAllocation(CheckerContext &C,
209 const ProgramState *falseState,
210 const Expr *arg,
211 const char *fn_name) const {
212 ExplodedNode *N = C.generateSink(falseState);
213 if (!N)
214 return false;
215
Ted Kremenek3e977582012-01-11 08:13:21 +0000216 LazyInitialize(BT_mallocZero,
217 "Undefined allocation of 0 bytes (CERT MEM04-C; CWE-131)");
Ted Kremenekc1275da2012-01-03 23:43:13 +0000218
219 llvm::SmallString<256> S;
220 llvm::raw_svector_ostream os(S);
221 os << "Call to '" << fn_name << "' has an allocation size of 0 bytes";
222 BugReport *report = new BugReport(*BT_mallocZero, os.str(), N);
223
224 report->addRange(arg->getSourceRange());
225 report->addVisitor(bugreporter::getTrackNullOrUndefValueVisitor(N, arg));
226 C.EmitReport(report);
227
228 return true;
229}
230
Ted Kremenek3e977582012-01-11 08:13:21 +0000231// Does a basic check for 0-sized allocations suitable for most of the below
232// functions (modulo "calloc")
233void UnixAPIChecker::BasicAllocationCheck(CheckerContext &C,
234 const CallExpr *CE,
235 const unsigned numArgs,
236 const unsigned sizeArg,
237 const char *fn) const {
238 // Sanity check for the correct number of arguments
239 if (CE->getNumArgs() != numArgs)
240 return;
241
242 // Check if the allocation size is 0.
243 const ProgramState *state = C.getState();
244 const ProgramState *trueState = NULL, *falseState = NULL;
245 const Expr *arg = CE->getArg(sizeArg);
246 SVal argVal = state->getSVal(arg, C.getLocationContext());
247
248 if (argVal.isUnknownOrUndef())
249 return;
250
251 // Is the value perfectly constrained to zero?
252 if (IsZeroByteAllocation(state, argVal, &trueState, &falseState)) {
253 (void) ReportZeroByteAllocation(C, falseState, arg, fn);
254 return;
255 }
256 // Assume the the value is non-zero going forward.
257 assert(trueState);
258 if (trueState != state)
259 C.addTransition(trueState);
260}
261
Ted Kremenekc1275da2012-01-03 23:43:13 +0000262void UnixAPIChecker::CheckCallocZero(CheckerContext &C,
263 const CallExpr *CE) const {
264 unsigned int nArgs = CE->getNumArgs();
265 if (nArgs != 2)
266 return;
267
268 const ProgramState *state = C.getState();
269 const ProgramState *trueState = NULL, *falseState = NULL;
270
271 unsigned int i;
272 for (i = 0; i < nArgs; i++) {
273 const Expr *arg = CE->getArg(i);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000274 SVal argVal = state->getSVal(arg, C.getLocationContext());
Ted Kremenekc1275da2012-01-03 23:43:13 +0000275 if (argVal.isUnknownOrUndef()) {
276 if (i == 0)
277 continue;
278 else
279 return;
280 }
281
282 if (IsZeroByteAllocation(state, argVal, &trueState, &falseState)) {
283 if (ReportZeroByteAllocation(C, falseState, arg, "calloc"))
284 return;
285 else if (i == 0)
286 continue;
287 else
288 return;
289 }
290 }
291
292 // Assume the the value is non-zero going forward.
293 assert(trueState);
294 if (trueState != state)
295 C.addTransition(trueState);
296}
297
Jordy Roseaf5b0432011-07-15 06:28:59 +0000298void UnixAPIChecker::CheckMallocZero(CheckerContext &C,
299 const CallExpr *CE) const {
Ted Kremenek3e977582012-01-11 08:13:21 +0000300 BasicAllocationCheck(C, CE, 1, 0, "malloc");
Ted Kremenekc1275da2012-01-03 23:43:13 +0000301}
302
303void UnixAPIChecker::CheckReallocZero(CheckerContext &C,
304 const CallExpr *CE) const {
Ted Kremenek3e977582012-01-11 08:13:21 +0000305 BasicAllocationCheck(C, CE, 2, 1, "realloc");
Ted Kremenekb12fbc22010-11-16 18:47:04 +0000306}
Ted Kremenek3e977582012-01-11 08:13:21 +0000307
308void UnixAPIChecker::CheckAllocaZero(CheckerContext &C,
309 const CallExpr *CE) const {
310 BasicAllocationCheck(C, CE, 1, 0, "alloca");
311}
312
313void UnixAPIChecker::CheckVallocZero(CheckerContext &C,
314 const CallExpr *CE) const {
315 BasicAllocationCheck(C, CE, 1, 0, "valloc");
316}
317
318
Ted Kremenekb12fbc22010-11-16 18:47:04 +0000319//===----------------------------------------------------------------------===//
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000320// Central dispatch function.
321//===----------------------------------------------------------------------===//
322
Ted Kremenek3e977582012-01-11 08:13:21 +0000323void UnixAPIChecker::checkPreStmt(const CallExpr *CE,
324 CheckerContext &C) const {
Anna Zaksb805c8f2011-12-01 05:57:37 +0000325 StringRef FName = C.getCalleeName(CE);
326 if (FName.empty())
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000327 return;
328
Jordy Roseaf5b0432011-07-15 06:28:59 +0000329 SubChecker SC =
Anna Zaksb805c8f2011-12-01 05:57:37 +0000330 llvm::StringSwitch<SubChecker>(FName)
Jordy Roseaf5b0432011-07-15 06:28:59 +0000331 .Case("open", &UnixAPIChecker::CheckOpen)
332 .Case("pthread_once", &UnixAPIChecker::CheckPthreadOnce)
Ted Kremenekc1275da2012-01-03 23:43:13 +0000333 .Case("calloc", &UnixAPIChecker::CheckCallocZero)
Jordy Roseaf5b0432011-07-15 06:28:59 +0000334 .Case("malloc", &UnixAPIChecker::CheckMallocZero)
Ted Kremenekc1275da2012-01-03 23:43:13 +0000335 .Case("realloc", &UnixAPIChecker::CheckReallocZero)
Ted Kremenek3e977582012-01-11 08:13:21 +0000336 .Cases("alloca", "__builtin_alloca", &UnixAPIChecker::CheckAllocaZero)
337 .Case("valloc", &UnixAPIChecker::CheckVallocZero)
Jordy Roseaf5b0432011-07-15 06:28:59 +0000338 .Default(NULL);
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000339
Jordy Roseaf5b0432011-07-15 06:28:59 +0000340 if (SC)
341 (this->*SC)(C, CE);
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000342}
Argyrios Kyrtzidis983326f2011-02-23 01:05:36 +0000343
344//===----------------------------------------------------------------------===//
345// Registration.
346//===----------------------------------------------------------------------===//
347
348void ento::registerUnixAPIChecker(CheckerManager &mgr) {
349 mgr.registerChecker<UnixAPIChecker>();
350}