blob: 420acd5aacdbabf1d6572041504660579344cb67 [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;
Jordy Roseaf5b0432011-07-15 06:28:59 +000042
43 typedef void (UnixAPIChecker::*SubChecker)(CheckerContext &,
44 const CallExpr *) const;
Ted Kremenekc1275da2012-01-03 23:43:13 +000045private:
46 bool ReportZeroByteAllocation(CheckerContext &C,
47 const ProgramState *falseState,
48 const Expr *arg,
49 const char *fn_name) const;
Ted Kremenek381d1bf2010-02-25 00:20:35 +000050};
51} //end anonymous namespace
52
Ted Kremenek381d1bf2010-02-25 00:20:35 +000053//===----------------------------------------------------------------------===//
54// Utility functions.
55//===----------------------------------------------------------------------===//
56
Jordy Roseaf5b0432011-07-15 06:28:59 +000057static inline void LazyInitialize(llvm::OwningPtr<BugType> &BT,
58 const char *name) {
Ted Kremenek381d1bf2010-02-25 00:20:35 +000059 if (BT)
60 return;
Jordy Roseaf5b0432011-07-15 06:28:59 +000061 BT.reset(new BugType(name, "Unix API"));
Ted Kremenek381d1bf2010-02-25 00:20:35 +000062}
63
64//===----------------------------------------------------------------------===//
65// "open" (man 2 open)
66//===----------------------------------------------------------------------===//
67
Jordy Roseaf5b0432011-07-15 06:28:59 +000068void UnixAPIChecker::CheckOpen(CheckerContext &C, const CallExpr *CE) const {
Ted Kremenekbace4ba2010-04-08 22:15:34 +000069 // The definition of O_CREAT is platform specific. We need a better way
70 // of querying this information from the checking environment.
Jordy Roseaf5b0432011-07-15 06:28:59 +000071 if (!Val_O_CREAT.hasValue()) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000072 if (C.getASTContext().getTargetInfo().getTriple().getVendor()
73 == llvm::Triple::Apple)
Jordy Roseaf5b0432011-07-15 06:28:59 +000074 Val_O_CREAT = 0x0200;
Ted Kremenekbace4ba2010-04-08 22:15:34 +000075 else {
76 // FIXME: We need a more general way of getting the O_CREAT value.
77 // We could possibly grovel through the preprocessor state, but
Argyrios Kyrtzidisd2592a32010-12-22 18:53:44 +000078 // that would require passing the Preprocessor object to the ExprEngine.
Ted Kremenekbace4ba2010-04-08 22:15:34 +000079 return;
80 }
81 }
82
Ted Kremenek381d1bf2010-02-25 00:20:35 +000083 // Look at the 'oflags' argument for the O_CREAT flag.
Ted Kremenek18c66fd2011-08-15 22:09:50 +000084 const ProgramState *state = C.getState();
Ted Kremenek381d1bf2010-02-25 00:20:35 +000085
86 if (CE->getNumArgs() < 2) {
87 // The frontend should issue a warning for this case, so this is a sanity
88 // check.
89 return;
90 }
91
92 // Now check if oflags has O_CREAT set.
93 const Expr *oflagsEx = CE->getArg(1);
Ted Kremenek5eca4822012-01-06 22:09:28 +000094 const SVal V = state->getSVal(oflagsEx, C.getLocationContext());
Ted Kremenek381d1bf2010-02-25 00:20:35 +000095 if (!isa<NonLoc>(V)) {
96 // The case where 'V' can be a location can only be due to a bad header,
97 // so in this case bail out.
98 return;
99 }
100 NonLoc oflags = cast<NonLoc>(V);
101 NonLoc ocreateFlag =
Jordy Roseaf5b0432011-07-15 06:28:59 +0000102 cast<NonLoc>(C.getSValBuilder().makeIntVal(Val_O_CREAT.getValue(),
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000103 oflagsEx->getType()));
Ted Kremenek9c149532010-12-01 21:57:22 +0000104 SVal maskedFlagsUC = C.getSValBuilder().evalBinOpNN(state, BO_And,
Ted Kremenek846eabd2010-12-01 21:28:31 +0000105 oflags, ocreateFlag,
106 oflagsEx->getType());
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000107 if (maskedFlagsUC.isUnknownOrUndef())
108 return;
109 DefinedSVal maskedFlags = cast<DefinedSVal>(maskedFlagsUC);
110
111 // Check if maskedFlags is non-zero.
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000112 const ProgramState *trueState, *falseState;
Ted Kremenek28f47b92010-12-01 22:16:56 +0000113 llvm::tie(trueState, falseState) = state->assume(maskedFlags);
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000114
115 // Only emit an error if the value of 'maskedFlags' is properly
116 // constrained;
117 if (!(trueState && !falseState))
118 return;
119
120 if (CE->getNumArgs() < 3) {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000121 ExplodedNode *N = C.generateSink(trueState);
Ted Kremenekc757d792010-02-25 05:44:05 +0000122 if (!N)
123 return;
124
Jordy Roseaf5b0432011-07-15 06:28:59 +0000125 LazyInitialize(BT_open, "Improper use of 'open'");
126
Anna Zakse172e8b2011-08-17 23:00:25 +0000127 BugReport *report =
128 new BugReport(*BT_open,
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000129 "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);
133 }
134}
135
136//===----------------------------------------------------------------------===//
Ted Kremenek99d98382010-04-08 19:53:31 +0000137// pthread_once
138//===----------------------------------------------------------------------===//
139
Jordy Roseaf5b0432011-07-15 06:28:59 +0000140void UnixAPIChecker::CheckPthreadOnce(CheckerContext &C,
141 const CallExpr *CE) const {
Ted Kremenek99d98382010-04-08 19:53:31 +0000142
143 // This is similar to 'CheckDispatchOnce' in the MacOSXAPIChecker.
144 // They can possibly be refactored.
145
Ted Kremenek99d98382010-04-08 19:53:31 +0000146 if (CE->getNumArgs() < 1)
147 return;
148
149 // Check if the first argument is stack allocated. If so, issue a warning
150 // because that's likely to be bad news.
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000151 const ProgramState *state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +0000152 const MemRegion *R =
153 state->getSVal(CE->getArg(0), C.getLocationContext()).getAsRegion();
Ted Kremenek99d98382010-04-08 19:53:31 +0000154 if (!R || !isa<StackSpaceRegion>(R->getMemorySpace()))
155 return;
156
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000157 ExplodedNode *N = C.generateSink(state);
Ted Kremenek99d98382010-04-08 19:53:31 +0000158 if (!N)
159 return;
160
161 llvm::SmallString<256> S;
162 llvm::raw_svector_ostream os(S);
163 os << "Call to 'pthread_once' uses";
164 if (const VarRegion *VR = dyn_cast<VarRegion>(R))
165 os << " the local variable '" << VR->getDecl()->getName() << '\'';
166 else
167 os << " stack allocated memory";
168 os << " for the \"control\" value. Using such transient memory for "
169 "the control value is potentially dangerous.";
170 if (isa<VarRegion>(R) && isa<StackLocalsSpaceRegion>(R->getMemorySpace()))
171 os << " Perhaps you intended to declare the variable as 'static'?";
172
Jordy Roseaf5b0432011-07-15 06:28:59 +0000173 LazyInitialize(BT_pthreadOnce, "Improper use of 'pthread_once'");
174
Anna Zakse172e8b2011-08-17 23:00:25 +0000175 BugReport *report = new BugReport(*BT_pthreadOnce, os.str(), N);
Ted Kremenek99d98382010-04-08 19:53:31 +0000176 report->addRange(CE->getArg(0)->getSourceRange());
177 C.EmitReport(report);
178}
179
180//===----------------------------------------------------------------------===//
Ted Kremenekc1275da2012-01-03 23:43:13 +0000181// "calloc", "malloc" and "realloc" with allocation size 0
Ted Kremenekb12fbc22010-11-16 18:47:04 +0000182//===----------------------------------------------------------------------===//
183
Ted Kremenekc1275da2012-01-03 23:43:13 +0000184// Returns true if we try to do a zero byte allocation, false otherwise.
185// Fills in trueState and falseState.
186static bool IsZeroByteAllocation(const ProgramState *state,
187 const SVal argVal,
188 const ProgramState **trueState,
189 const ProgramState **falseState) {
190 llvm::tie(*trueState, *falseState) = state->assume(cast<DefinedSVal>(argVal));
191 return (*falseState && !*trueState);
192}
193
194// Generates an error report, indicating that the function whose name is given
195// will perform a zero byte allocation.
196// Returns false if an error occured, true otherwise.
197bool UnixAPIChecker::ReportZeroByteAllocation(CheckerContext &C,
198 const ProgramState *falseState,
199 const Expr *arg,
200 const char *fn_name) const {
201 ExplodedNode *N = C.generateSink(falseState);
202 if (!N)
203 return false;
204
205 // FIXME: Add reference to CERT advisory, and/or C99 standard in bug
206 // output.
207 LazyInitialize(BT_mallocZero, "Undefined allocation of 0 bytes");
208
209 llvm::SmallString<256> S;
210 llvm::raw_svector_ostream os(S);
211 os << "Call to '" << fn_name << "' has an allocation size of 0 bytes";
212 BugReport *report = new BugReport(*BT_mallocZero, os.str(), N);
213
214 report->addRange(arg->getSourceRange());
215 report->addVisitor(bugreporter::getTrackNullOrUndefValueVisitor(N, arg));
216 C.EmitReport(report);
217
218 return true;
219}
220
221void UnixAPIChecker::CheckCallocZero(CheckerContext &C,
222 const CallExpr *CE) const {
223 unsigned int nArgs = CE->getNumArgs();
224 if (nArgs != 2)
225 return;
226
227 const ProgramState *state = C.getState();
228 const ProgramState *trueState = NULL, *falseState = NULL;
229
230 unsigned int i;
231 for (i = 0; i < nArgs; i++) {
232 const Expr *arg = CE->getArg(i);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000233 SVal argVal = state->getSVal(arg, C.getLocationContext());
Ted Kremenekc1275da2012-01-03 23:43:13 +0000234 if (argVal.isUnknownOrUndef()) {
235 if (i == 0)
236 continue;
237 else
238 return;
239 }
240
241 if (IsZeroByteAllocation(state, argVal, &trueState, &falseState)) {
242 if (ReportZeroByteAllocation(C, falseState, arg, "calloc"))
243 return;
244 else if (i == 0)
245 continue;
246 else
247 return;
248 }
249 }
250
251 // Assume the the value is non-zero going forward.
252 assert(trueState);
253 if (trueState != state)
254 C.addTransition(trueState);
255}
256
Ted Kremenekb12fbc22010-11-16 18:47:04 +0000257// FIXME: Eventually this should be rolled into the MallocChecker, but this
258// check is more basic and is valuable for widespread use.
Jordy Roseaf5b0432011-07-15 06:28:59 +0000259void UnixAPIChecker::CheckMallocZero(CheckerContext &C,
260 const CallExpr *CE) const {
Ted Kremenekb12fbc22010-11-16 18:47:04 +0000261 // Sanity check that malloc takes one argument.
262 if (CE->getNumArgs() != 1)
263 return;
264
265 // Check if the allocation size is 0.
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000266 const ProgramState *state = C.getState();
Ted Kremenekc1275da2012-01-03 23:43:13 +0000267 const ProgramState *trueState = NULL, *falseState = NULL;
268 const Expr *arg = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000269 SVal argVal = state->getSVal(arg, C.getLocationContext());
Ted Kremenekb12fbc22010-11-16 18:47:04 +0000270
271 if (argVal.isUnknownOrUndef())
272 return;
Ted Kremenek8fec9722010-11-17 00:50:34 +0000273
Ted Kremenekc1275da2012-01-03 23:43:13 +0000274 // Is the value perfectly constrained to zero?
275 if (IsZeroByteAllocation(state, argVal, &trueState, &falseState)) {
276 (void) ReportZeroByteAllocation(C, falseState, arg, "malloc");
Ted Kremenekb12fbc22010-11-16 18:47:04 +0000277 return;
278 }
279 // Assume the the value is non-zero going forward.
280 assert(trueState);
Ted Kremenekc1275da2012-01-03 23:43:13 +0000281 if (trueState != state)
Anna Zaks0bd6b112011-10-26 21:06:34 +0000282 C.addTransition(trueState);
Ted Kremenekc1275da2012-01-03 23:43:13 +0000283}
284
285void UnixAPIChecker::CheckReallocZero(CheckerContext &C,
286 const CallExpr *CE) const {
287 if (CE->getNumArgs() != 2)
288 return;
289
290 const ProgramState *state = C.getState();
291 const ProgramState *trueState = NULL, *falseState = NULL;
292 const Expr *arg = CE->getArg(1);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000293 SVal argVal = state->getSVal(arg, C.getLocationContext());
Ted Kremenekc1275da2012-01-03 23:43:13 +0000294
295 if (argVal.isUnknownOrUndef())
296 return;
297
298 if (IsZeroByteAllocation(state, argVal, &trueState, &falseState)) {
299 ReportZeroByteAllocation(C, falseState, arg, "realloc");
300 return;
Ted Kremenekb12fbc22010-11-16 18:47:04 +0000301 }
Ted Kremenekc1275da2012-01-03 23:43:13 +0000302
303 // Assume the the value is non-zero going forward.
304 assert(trueState);
305 if (trueState != state)
306 C.addTransition(trueState);
Ted Kremenekb12fbc22010-11-16 18:47:04 +0000307}
308
309//===----------------------------------------------------------------------===//
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000310// Central dispatch function.
311//===----------------------------------------------------------------------===//
312
Argyrios Kyrtzidis983326f2011-02-23 01:05:36 +0000313void UnixAPIChecker::checkPreStmt(const CallExpr *CE, CheckerContext &C) const {
Anna Zaksb805c8f2011-12-01 05:57:37 +0000314 StringRef FName = C.getCalleeName(CE);
315 if (FName.empty())
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000316 return;
317
Jordy Roseaf5b0432011-07-15 06:28:59 +0000318 SubChecker SC =
Anna Zaksb805c8f2011-12-01 05:57:37 +0000319 llvm::StringSwitch<SubChecker>(FName)
Jordy Roseaf5b0432011-07-15 06:28:59 +0000320 .Case("open", &UnixAPIChecker::CheckOpen)
321 .Case("pthread_once", &UnixAPIChecker::CheckPthreadOnce)
Ted Kremenekc1275da2012-01-03 23:43:13 +0000322 .Case("calloc", &UnixAPIChecker::CheckCallocZero)
Jordy Roseaf5b0432011-07-15 06:28:59 +0000323 .Case("malloc", &UnixAPIChecker::CheckMallocZero)
Ted Kremenekc1275da2012-01-03 23:43:13 +0000324 .Case("realloc", &UnixAPIChecker::CheckReallocZero)
Jordy Roseaf5b0432011-07-15 06:28:59 +0000325 .Default(NULL);
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000326
Jordy Roseaf5b0432011-07-15 06:28:59 +0000327 if (SC)
328 (this->*SC)(C, CE);
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000329}
Argyrios Kyrtzidis983326f2011-02-23 01:05:36 +0000330
331//===----------------------------------------------------------------------===//
332// Registration.
333//===----------------------------------------------------------------------===//
334
335void ento::registerUnixAPIChecker(CheckerManager &mgr) {
336 mgr.registerChecker<UnixAPIChecker>();
337}