blob: 600de659b974be6c3a7c0475bc1f46a3ef7a28b2 [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 Kramer8fe83e12012-02-04 13:45:25 +000022#include "llvm/ADT/SmallString.h"
Benjamin Kramer00bd44d2012-02-04 12:31:12 +000023#include "llvm/ADT/STLExtras.h"
Benjamin Kramer5e2d2c22010-03-27 21:19:47 +000024#include "llvm/ADT/StringSwitch.h"
Ted Kremenek381d1bf2010-02-25 00:20:35 +000025#include <fcntl.h>
26
27using namespace clang;
Ted Kremenek9ef65372010-12-23 07:20:52 +000028using namespace ento;
Ted Kremenek66d51422010-04-09 20:26:58 +000029using llvm::Optional;
Ted Kremenek381d1bf2010-02-25 00:20:35 +000030
31namespace {
Argyrios Kyrtzidisec8605f2011-03-01 01:16:21 +000032class UnixAPIChecker : public Checker< check::PreStmt<CallExpr> > {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +000033 mutable OwningPtr<BugType> BT_open, BT_pthreadOnce, BT_mallocZero;
Argyrios Kyrtzidis983326f2011-02-23 01:05:36 +000034 mutable Optional<uint64_t> Val_O_CREAT;
Ted Kremenekbace4ba2010-04-08 22:15:34 +000035
36public:
Argyrios Kyrtzidis983326f2011-02-23 01:05:36 +000037 void checkPreStmt(const CallExpr *CE, CheckerContext &C) const;
Jordy Roseaf5b0432011-07-15 06:28:59 +000038
39 void CheckOpen(CheckerContext &C, const CallExpr *CE) const;
40 void CheckPthreadOnce(CheckerContext &C, const CallExpr *CE) const;
Ted Kremenekc1275da2012-01-03 23:43:13 +000041 void CheckCallocZero(CheckerContext &C, const CallExpr *CE) const;
Jordy Roseaf5b0432011-07-15 06:28:59 +000042 void CheckMallocZero(CheckerContext &C, const CallExpr *CE) const;
Ted Kremenekc1275da2012-01-03 23:43:13 +000043 void CheckReallocZero(CheckerContext &C, const CallExpr *CE) const;
Ted Kremenek3e977582012-01-11 08:13:21 +000044 void CheckAllocaZero(CheckerContext &C, const CallExpr *CE) const;
45 void CheckVallocZero(CheckerContext &C, const CallExpr *CE) const;
Jordy Roseaf5b0432011-07-15 06:28:59 +000046
47 typedef void (UnixAPIChecker::*SubChecker)(CheckerContext &,
48 const CallExpr *) const;
Ted Kremenekc1275da2012-01-03 23:43:13 +000049private:
50 bool ReportZeroByteAllocation(CheckerContext &C,
Ted Kremenek8bef8232012-01-26 21:29:00 +000051 ProgramStateRef falseState,
Ted Kremenekc1275da2012-01-03 23:43:13 +000052 const Expr *arg,
53 const char *fn_name) const;
Ted Kremenek3e977582012-01-11 08:13:21 +000054 void BasicAllocationCheck(CheckerContext &C,
55 const CallExpr *CE,
56 const unsigned numArgs,
57 const unsigned sizeArg,
58 const char *fn) const;
Ted Kremenek381d1bf2010-02-25 00:20:35 +000059};
60} //end anonymous namespace
61
Ted Kremenek381d1bf2010-02-25 00:20:35 +000062//===----------------------------------------------------------------------===//
63// Utility functions.
64//===----------------------------------------------------------------------===//
65
Dylan Noblesmith6f42b622012-02-05 02:12:40 +000066static inline void LazyInitialize(OwningPtr<BugType> &BT,
Jordy Roseaf5b0432011-07-15 06:28:59 +000067 const char *name) {
Ted Kremenek381d1bf2010-02-25 00:20:35 +000068 if (BT)
69 return;
Ted Kremenek6fd45052012-04-05 20:43:28 +000070 BT.reset(new BugType(name, categories::UnixAPI));
Ted Kremenek381d1bf2010-02-25 00:20:35 +000071}
72
73//===----------------------------------------------------------------------===//
74// "open" (man 2 open)
75//===----------------------------------------------------------------------===//
76
Jordy Roseaf5b0432011-07-15 06:28:59 +000077void UnixAPIChecker::CheckOpen(CheckerContext &C, const CallExpr *CE) const {
Ted Kremenekbace4ba2010-04-08 22:15:34 +000078 // The definition of O_CREAT is platform specific. We need a better way
79 // of querying this information from the checking environment.
Jordy Roseaf5b0432011-07-15 06:28:59 +000080 if (!Val_O_CREAT.hasValue()) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000081 if (C.getASTContext().getTargetInfo().getTriple().getVendor()
82 == llvm::Triple::Apple)
Jordy Roseaf5b0432011-07-15 06:28:59 +000083 Val_O_CREAT = 0x0200;
Ted Kremenekbace4ba2010-04-08 22:15:34 +000084 else {
85 // FIXME: We need a more general way of getting the O_CREAT value.
86 // We could possibly grovel through the preprocessor state, but
Argyrios Kyrtzidisd2592a32010-12-22 18:53:44 +000087 // that would require passing the Preprocessor object to the ExprEngine.
Ted Kremenekbace4ba2010-04-08 22:15:34 +000088 return;
89 }
90 }
91
Ted Kremenek381d1bf2010-02-25 00:20:35 +000092 // Look at the 'oflags' argument for the O_CREAT flag.
Ted Kremenek8bef8232012-01-26 21:29:00 +000093 ProgramStateRef state = C.getState();
Ted Kremenek381d1bf2010-02-25 00:20:35 +000094
95 if (CE->getNumArgs() < 2) {
96 // The frontend should issue a warning for this case, so this is a sanity
97 // check.
98 return;
99 }
100
101 // Now check if oflags has O_CREAT set.
102 const Expr *oflagsEx = CE->getArg(1);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000103 const SVal V = state->getSVal(oflagsEx, C.getLocationContext());
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000104 if (!isa<NonLoc>(V)) {
105 // The case where 'V' can be a location can only be due to a bad header,
106 // so in this case bail out.
107 return;
108 }
109 NonLoc oflags = cast<NonLoc>(V);
110 NonLoc ocreateFlag =
Jordy Roseaf5b0432011-07-15 06:28:59 +0000111 cast<NonLoc>(C.getSValBuilder().makeIntVal(Val_O_CREAT.getValue(),
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000112 oflagsEx->getType()));
Ted Kremenek9c149532010-12-01 21:57:22 +0000113 SVal maskedFlagsUC = C.getSValBuilder().evalBinOpNN(state, BO_And,
Ted Kremenek846eabd2010-12-01 21:28:31 +0000114 oflags, ocreateFlag,
115 oflagsEx->getType());
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000116 if (maskedFlagsUC.isUnknownOrUndef())
117 return;
118 DefinedSVal maskedFlags = cast<DefinedSVal>(maskedFlagsUC);
119
120 // Check if maskedFlags is non-zero.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000121 ProgramStateRef trueState, falseState;
Ted Kremenek28f47b92010-12-01 22:16:56 +0000122 llvm::tie(trueState, falseState) = state->assume(maskedFlags);
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000123
124 // Only emit an error if the value of 'maskedFlags' is properly
125 // constrained;
126 if (!(trueState && !falseState))
127 return;
128
129 if (CE->getNumArgs() < 3) {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000130 ExplodedNode *N = C.generateSink(trueState);
Ted Kremenekc757d792010-02-25 05:44:05 +0000131 if (!N)
132 return;
133
Jordy Roseaf5b0432011-07-15 06:28:59 +0000134 LazyInitialize(BT_open, "Improper use of 'open'");
135
Anna Zakse172e8b2011-08-17 23:00:25 +0000136 BugReport *report =
137 new BugReport(*BT_open,
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000138 "Call to 'open' requires a third argument when "
139 "the 'O_CREAT' flag is set", N);
140 report->addRange(oflagsEx->getSourceRange());
141 C.EmitReport(report);
142 }
143}
144
145//===----------------------------------------------------------------------===//
Ted Kremenek99d98382010-04-08 19:53:31 +0000146// pthread_once
147//===----------------------------------------------------------------------===//
148
Jordy Roseaf5b0432011-07-15 06:28:59 +0000149void UnixAPIChecker::CheckPthreadOnce(CheckerContext &C,
150 const CallExpr *CE) const {
Ted Kremenek99d98382010-04-08 19:53:31 +0000151
152 // This is similar to 'CheckDispatchOnce' in the MacOSXAPIChecker.
153 // They can possibly be refactored.
154
Ted Kremenek99d98382010-04-08 19:53:31 +0000155 if (CE->getNumArgs() < 1)
156 return;
157
158 // Check if the first argument is stack allocated. If so, issue a warning
159 // because that's likely to be bad news.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000160 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +0000161 const MemRegion *R =
162 state->getSVal(CE->getArg(0), C.getLocationContext()).getAsRegion();
Ted Kremenek99d98382010-04-08 19:53:31 +0000163 if (!R || !isa<StackSpaceRegion>(R->getMemorySpace()))
164 return;
165
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000166 ExplodedNode *N = C.generateSink(state);
Ted Kremenek99d98382010-04-08 19:53:31 +0000167 if (!N)
168 return;
169
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000170 SmallString<256> S;
Ted Kremenek99d98382010-04-08 19:53:31 +0000171 llvm::raw_svector_ostream os(S);
172 os << "Call to 'pthread_once' uses";
173 if (const VarRegion *VR = dyn_cast<VarRegion>(R))
174 os << " the local variable '" << VR->getDecl()->getName() << '\'';
175 else
176 os << " stack allocated memory";
177 os << " for the \"control\" value. Using such transient memory for "
178 "the control value is potentially dangerous.";
179 if (isa<VarRegion>(R) && isa<StackLocalsSpaceRegion>(R->getMemorySpace()))
180 os << " Perhaps you intended to declare the variable as 'static'?";
181
Jordy Roseaf5b0432011-07-15 06:28:59 +0000182 LazyInitialize(BT_pthreadOnce, "Improper use of 'pthread_once'");
183
Anna Zakse172e8b2011-08-17 23:00:25 +0000184 BugReport *report = new BugReport(*BT_pthreadOnce, os.str(), N);
Ted Kremenek99d98382010-04-08 19:53:31 +0000185 report->addRange(CE->getArg(0)->getSourceRange());
186 C.EmitReport(report);
187}
188
189//===----------------------------------------------------------------------===//
Ted Kremenek3e977582012-01-11 08:13:21 +0000190// "calloc", "malloc", "realloc", "alloca" and "valloc" with allocation size 0
Ted Kremenekb12fbc22010-11-16 18:47:04 +0000191//===----------------------------------------------------------------------===//
Ted Kremenek3e977582012-01-11 08:13:21 +0000192// FIXME: Eventually these should be rolled into the MallocChecker, but right now
193// they're more basic and valuable for widespread use.
Ted Kremenekb12fbc22010-11-16 18:47:04 +0000194
Ted Kremenekc1275da2012-01-03 23:43:13 +0000195// Returns true if we try to do a zero byte allocation, false otherwise.
196// Fills in trueState and falseState.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000197static bool IsZeroByteAllocation(ProgramStateRef state,
Ted Kremenekc1275da2012-01-03 23:43:13 +0000198 const SVal argVal,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000199 ProgramStateRef *trueState,
200 ProgramStateRef *falseState) {
Ted Kremenek3e977582012-01-11 08:13:21 +0000201 llvm::tie(*trueState, *falseState) =
202 state->assume(cast<DefinedSVal>(argVal));
203
Ted Kremenekc1275da2012-01-03 23:43:13 +0000204 return (*falseState && !*trueState);
205}
206
207// Generates an error report, indicating that the function whose name is given
208// will perform a zero byte allocation.
209// Returns false if an error occured, true otherwise.
210bool UnixAPIChecker::ReportZeroByteAllocation(CheckerContext &C,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000211 ProgramStateRef falseState,
Ted Kremenekc1275da2012-01-03 23:43:13 +0000212 const Expr *arg,
213 const char *fn_name) const {
214 ExplodedNode *N = C.generateSink(falseState);
215 if (!N)
216 return false;
217
Ted Kremenek3e977582012-01-11 08:13:21 +0000218 LazyInitialize(BT_mallocZero,
219 "Undefined allocation of 0 bytes (CERT MEM04-C; CWE-131)");
Ted Kremenekc1275da2012-01-03 23:43:13 +0000220
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000221 SmallString<256> S;
Ted Kremenekc1275da2012-01-03 23:43:13 +0000222 llvm::raw_svector_ostream os(S);
223 os << "Call to '" << fn_name << "' has an allocation size of 0 bytes";
224 BugReport *report = new BugReport(*BT_mallocZero, os.str(), N);
225
226 report->addRange(arg->getSourceRange());
Ted Kremenek76aadc32012-03-09 01:13:14 +0000227 report->addVisitor(bugreporter::getTrackNullOrUndefValueVisitor(N, arg,
228 report));
Ted Kremenekc1275da2012-01-03 23:43:13 +0000229 C.EmitReport(report);
230
231 return true;
232}
233
Ted Kremenek3e977582012-01-11 08:13:21 +0000234// Does a basic check for 0-sized allocations suitable for most of the below
235// functions (modulo "calloc")
236void UnixAPIChecker::BasicAllocationCheck(CheckerContext &C,
237 const CallExpr *CE,
238 const unsigned numArgs,
239 const unsigned sizeArg,
240 const char *fn) const {
241 // Sanity check for the correct number of arguments
242 if (CE->getNumArgs() != numArgs)
243 return;
244
245 // Check if the allocation size is 0.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000246 ProgramStateRef state = C.getState();
247 ProgramStateRef trueState = NULL, falseState = NULL;
Ted Kremenek3e977582012-01-11 08:13:21 +0000248 const Expr *arg = CE->getArg(sizeArg);
249 SVal argVal = state->getSVal(arg, C.getLocationContext());
250
251 if (argVal.isUnknownOrUndef())
252 return;
253
254 // Is the value perfectly constrained to zero?
255 if (IsZeroByteAllocation(state, argVal, &trueState, &falseState)) {
256 (void) ReportZeroByteAllocation(C, falseState, arg, fn);
257 return;
258 }
259 // Assume the the value is non-zero going forward.
260 assert(trueState);
261 if (trueState != state)
262 C.addTransition(trueState);
263}
264
Ted Kremenekc1275da2012-01-03 23:43:13 +0000265void UnixAPIChecker::CheckCallocZero(CheckerContext &C,
266 const CallExpr *CE) const {
267 unsigned int nArgs = CE->getNumArgs();
268 if (nArgs != 2)
269 return;
270
Ted Kremenek8bef8232012-01-26 21:29:00 +0000271 ProgramStateRef state = C.getState();
272 ProgramStateRef trueState = NULL, falseState = NULL;
Ted Kremenekc1275da2012-01-03 23:43:13 +0000273
274 unsigned int i;
275 for (i = 0; i < nArgs; i++) {
276 const Expr *arg = CE->getArg(i);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000277 SVal argVal = state->getSVal(arg, C.getLocationContext());
Ted Kremenekc1275da2012-01-03 23:43:13 +0000278 if (argVal.isUnknownOrUndef()) {
279 if (i == 0)
280 continue;
281 else
282 return;
283 }
284
285 if (IsZeroByteAllocation(state, argVal, &trueState, &falseState)) {
286 if (ReportZeroByteAllocation(C, falseState, arg, "calloc"))
287 return;
288 else if (i == 0)
289 continue;
290 else
291 return;
292 }
293 }
294
295 // Assume the the value is non-zero going forward.
296 assert(trueState);
297 if (trueState != state)
298 C.addTransition(trueState);
299}
300
Jordy Roseaf5b0432011-07-15 06:28:59 +0000301void UnixAPIChecker::CheckMallocZero(CheckerContext &C,
302 const CallExpr *CE) const {
Ted Kremenek3e977582012-01-11 08:13:21 +0000303 BasicAllocationCheck(C, CE, 1, 0, "malloc");
Ted Kremenekc1275da2012-01-03 23:43:13 +0000304}
305
306void UnixAPIChecker::CheckReallocZero(CheckerContext &C,
307 const CallExpr *CE) const {
Ted Kremenek3e977582012-01-11 08:13:21 +0000308 BasicAllocationCheck(C, CE, 2, 1, "realloc");
Ted Kremenekb12fbc22010-11-16 18:47:04 +0000309}
Ted Kremenek3e977582012-01-11 08:13:21 +0000310
311void UnixAPIChecker::CheckAllocaZero(CheckerContext &C,
312 const CallExpr *CE) const {
313 BasicAllocationCheck(C, CE, 1, 0, "alloca");
314}
315
316void UnixAPIChecker::CheckVallocZero(CheckerContext &C,
317 const CallExpr *CE) const {
318 BasicAllocationCheck(C, CE, 1, 0, "valloc");
319}
320
321
Ted Kremenekb12fbc22010-11-16 18:47:04 +0000322//===----------------------------------------------------------------------===//
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000323// Central dispatch function.
324//===----------------------------------------------------------------------===//
325
Ted Kremenek3e977582012-01-11 08:13:21 +0000326void UnixAPIChecker::checkPreStmt(const CallExpr *CE,
327 CheckerContext &C) const {
Jordan Rose5ef6e942012-07-10 23:13:01 +0000328 const FunctionDecl *FD = C.getCalleeDecl(CE);
329 if (!FD || FD->getKind() != Decl::Function)
330 return;
331
332 StringRef FName = C.getCalleeName(FD);
Anna Zaksb805c8f2011-12-01 05:57:37 +0000333 if (FName.empty())
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000334 return;
335
Jordy Roseaf5b0432011-07-15 06:28:59 +0000336 SubChecker SC =
Anna Zaksb805c8f2011-12-01 05:57:37 +0000337 llvm::StringSwitch<SubChecker>(FName)
Jordy Roseaf5b0432011-07-15 06:28:59 +0000338 .Case("open", &UnixAPIChecker::CheckOpen)
339 .Case("pthread_once", &UnixAPIChecker::CheckPthreadOnce)
Ted Kremenekc1275da2012-01-03 23:43:13 +0000340 .Case("calloc", &UnixAPIChecker::CheckCallocZero)
Jordy Roseaf5b0432011-07-15 06:28:59 +0000341 .Case("malloc", &UnixAPIChecker::CheckMallocZero)
Ted Kremenekc1275da2012-01-03 23:43:13 +0000342 .Case("realloc", &UnixAPIChecker::CheckReallocZero)
Ted Kremenek3e977582012-01-11 08:13:21 +0000343 .Cases("alloca", "__builtin_alloca", &UnixAPIChecker::CheckAllocaZero)
344 .Case("valloc", &UnixAPIChecker::CheckVallocZero)
Jordy Roseaf5b0432011-07-15 06:28:59 +0000345 .Default(NULL);
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000346
Jordy Roseaf5b0432011-07-15 06:28:59 +0000347 if (SC)
348 (this->*SC)(C, CE);
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000349}
Argyrios Kyrtzidis983326f2011-02-23 01:05:36 +0000350
351//===----------------------------------------------------------------------===//
352// Registration.
353//===----------------------------------------------------------------------===//
354
355void ento::registerUnixAPIChecker(CheckerManager &mgr) {
356 mgr.registerChecker<UnixAPIChecker>();
357}