blob: 3e11fd810e6d2e6d7bc03505688e290d7277e947 [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"
Chandler Carruth55fc8732012-12-04 09:13:33 +000016#include "clang/Basic/TargetInfo.h"
17#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
Argyrios Kyrtzidisec8605f2011-03-01 01:16:21 +000018#include "clang/StaticAnalyzer/Core/Checker.h"
Argyrios Kyrtzidis695fb502011-02-17 21:39:17 +000019#include "clang/StaticAnalyzer/Core/CheckerManager.h"
Argyrios Kyrtzidis983326f2011-02-23 01:05:36 +000020#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
Ted Kremenek66d51422010-04-09 20:26:58 +000021#include "llvm/ADT/Optional.h"
Benjamin Kramer00bd44d2012-02-04 12:31:12 +000022#include "llvm/ADT/STLExtras.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000023#include "llvm/ADT/SmallString.h"
Benjamin Kramer5e2d2c22010-03-27 21:19:47 +000024#include "llvm/ADT/StringSwitch.h"
Benjamin Kramera93d0f22012-12-01 17:12:56 +000025#include "llvm/Support/raw_ostream.h"
Ted Kremenek381d1bf2010-02-25 00:20:35 +000026#include <fcntl.h>
27
28using namespace clang;
Ted Kremenek9ef65372010-12-23 07:20:52 +000029using namespace ento;
Ted Kremenek66d51422010-04-09 20:26:58 +000030using llvm::Optional;
Ted Kremenek381d1bf2010-02-25 00:20:35 +000031
32namespace {
Argyrios Kyrtzidisec8605f2011-03-01 01:16:21 +000033class UnixAPIChecker : public Checker< check::PreStmt<CallExpr> > {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +000034 mutable OwningPtr<BugType> BT_open, BT_pthreadOnce, BT_mallocZero;
Argyrios Kyrtzidis983326f2011-02-23 01:05:36 +000035 mutable Optional<uint64_t> Val_O_CREAT;
Ted Kremenekbace4ba2010-04-08 22:15:34 +000036
37public:
Argyrios Kyrtzidis983326f2011-02-23 01:05:36 +000038 void checkPreStmt(const CallExpr *CE, CheckerContext &C) const;
Jordy Roseaf5b0432011-07-15 06:28:59 +000039
40 void CheckOpen(CheckerContext &C, const CallExpr *CE) const;
41 void CheckPthreadOnce(CheckerContext &C, const CallExpr *CE) const;
Ted Kremenekc1275da2012-01-03 23:43:13 +000042 void CheckCallocZero(CheckerContext &C, const CallExpr *CE) const;
Jordy Roseaf5b0432011-07-15 06:28:59 +000043 void CheckMallocZero(CheckerContext &C, const CallExpr *CE) const;
Ted Kremenekc1275da2012-01-03 23:43:13 +000044 void CheckReallocZero(CheckerContext &C, const CallExpr *CE) const;
Jordan Roseeafaad22012-10-30 01:37:16 +000045 void CheckReallocfZero(CheckerContext &C, const CallExpr *CE) const;
Ted Kremenek3e977582012-01-11 08:13:21 +000046 void CheckAllocaZero(CheckerContext &C, const CallExpr *CE) const;
47 void CheckVallocZero(CheckerContext &C, const CallExpr *CE) const;
Jordy Roseaf5b0432011-07-15 06:28:59 +000048
49 typedef void (UnixAPIChecker::*SubChecker)(CheckerContext &,
50 const CallExpr *) const;
Ted Kremenekc1275da2012-01-03 23:43:13 +000051private:
52 bool ReportZeroByteAllocation(CheckerContext &C,
Ted Kremenek8bef8232012-01-26 21:29:00 +000053 ProgramStateRef falseState,
Ted Kremenekc1275da2012-01-03 23:43:13 +000054 const Expr *arg,
55 const char *fn_name) const;
Ted Kremenek3e977582012-01-11 08:13:21 +000056 void BasicAllocationCheck(CheckerContext &C,
57 const CallExpr *CE,
58 const unsigned numArgs,
59 const unsigned sizeArg,
60 const char *fn) const;
Ted Kremenek381d1bf2010-02-25 00:20:35 +000061};
62} //end anonymous namespace
63
Ted Kremenek381d1bf2010-02-25 00:20:35 +000064//===----------------------------------------------------------------------===//
65// Utility functions.
66//===----------------------------------------------------------------------===//
67
Dylan Noblesmith6f42b622012-02-05 02:12:40 +000068static inline void LazyInitialize(OwningPtr<BugType> &BT,
Jordy Roseaf5b0432011-07-15 06:28:59 +000069 const char *name) {
Ted Kremenek381d1bf2010-02-25 00:20:35 +000070 if (BT)
71 return;
Ted Kremenek6fd45052012-04-05 20:43:28 +000072 BT.reset(new BugType(name, categories::UnixAPI));
Ted Kremenek381d1bf2010-02-25 00:20:35 +000073}
74
75//===----------------------------------------------------------------------===//
76// "open" (man 2 open)
77//===----------------------------------------------------------------------===//
78
Jordy Roseaf5b0432011-07-15 06:28:59 +000079void UnixAPIChecker::CheckOpen(CheckerContext &C, const CallExpr *CE) const {
Ted Kremenekbace4ba2010-04-08 22:15:34 +000080 // The definition of O_CREAT is platform specific. We need a better way
81 // of querying this information from the checking environment.
Jordy Roseaf5b0432011-07-15 06:28:59 +000082 if (!Val_O_CREAT.hasValue()) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000083 if (C.getASTContext().getTargetInfo().getTriple().getVendor()
84 == llvm::Triple::Apple)
Jordy Roseaf5b0432011-07-15 06:28:59 +000085 Val_O_CREAT = 0x0200;
Ted Kremenekbace4ba2010-04-08 22:15:34 +000086 else {
87 // FIXME: We need a more general way of getting the O_CREAT value.
88 // We could possibly grovel through the preprocessor state, but
Argyrios Kyrtzidisd2592a32010-12-22 18:53:44 +000089 // that would require passing the Preprocessor object to the ExprEngine.
Ted Kremenekbace4ba2010-04-08 22:15:34 +000090 return;
91 }
92 }
93
Ted Kremenek381d1bf2010-02-25 00:20:35 +000094 // Look at the 'oflags' argument for the O_CREAT flag.
Ted Kremenek8bef8232012-01-26 21:29:00 +000095 ProgramStateRef state = C.getState();
Ted Kremenek381d1bf2010-02-25 00:20:35 +000096
97 if (CE->getNumArgs() < 2) {
98 // The frontend should issue a warning for this case, so this is a sanity
99 // check.
100 return;
101 }
102
103 // Now check if oflags has O_CREAT set.
104 const Expr *oflagsEx = CE->getArg(1);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000105 const SVal V = state->getSVal(oflagsEx, C.getLocationContext());
David Blaikie5251abe2013-02-20 05:52:05 +0000106 if (!V.getAs<NonLoc>()) {
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000107 // The case where 'V' can be a location can only be due to a bad header,
108 // so in this case bail out.
109 return;
110 }
David Blaikie5251abe2013-02-20 05:52:05 +0000111 NonLoc oflags = V.castAs<NonLoc>();
112 NonLoc ocreateFlag = C.getSValBuilder()
113 .makeIntVal(Val_O_CREAT.getValue(), oflagsEx->getType()).castAs<NonLoc>();
Ted Kremenek9c149532010-12-01 21:57:22 +0000114 SVal maskedFlagsUC = C.getSValBuilder().evalBinOpNN(state, BO_And,
Ted Kremenek846eabd2010-12-01 21:28:31 +0000115 oflags, ocreateFlag,
116 oflagsEx->getType());
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000117 if (maskedFlagsUC.isUnknownOrUndef())
118 return;
David Blaikie5251abe2013-02-20 05:52:05 +0000119 DefinedSVal maskedFlags = maskedFlagsUC.castAs<DefinedSVal>();
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000120
121 // Check if maskedFlags is non-zero.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000122 ProgramStateRef trueState, falseState;
Ted Kremenek28f47b92010-12-01 22:16:56 +0000123 llvm::tie(trueState, falseState) = state->assume(maskedFlags);
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000124
125 // Only emit an error if the value of 'maskedFlags' is properly
126 // constrained;
127 if (!(trueState && !falseState))
128 return;
129
130 if (CE->getNumArgs() < 3) {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000131 ExplodedNode *N = C.generateSink(trueState);
Ted Kremenekc757d792010-02-25 05:44:05 +0000132 if (!N)
133 return;
134
Jordy Roseaf5b0432011-07-15 06:28:59 +0000135 LazyInitialize(BT_open, "Improper use of 'open'");
136
Anna Zakse172e8b2011-08-17 23:00:25 +0000137 BugReport *report =
138 new BugReport(*BT_open,
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000139 "Call to 'open' requires a third argument when "
140 "the 'O_CREAT' flag is set", N);
141 report->addRange(oflagsEx->getSourceRange());
Jordan Rose785950e2012-11-02 01:53:40 +0000142 C.emitReport(report);
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000143 }
144}
145
146//===----------------------------------------------------------------------===//
Ted Kremenek99d98382010-04-08 19:53:31 +0000147// pthread_once
148//===----------------------------------------------------------------------===//
149
Jordy Roseaf5b0432011-07-15 06:28:59 +0000150void UnixAPIChecker::CheckPthreadOnce(CheckerContext &C,
151 const CallExpr *CE) const {
Ted Kremenek99d98382010-04-08 19:53:31 +0000152
153 // This is similar to 'CheckDispatchOnce' in the MacOSXAPIChecker.
154 // They can possibly be refactored.
155
Ted Kremenek99d98382010-04-08 19:53:31 +0000156 if (CE->getNumArgs() < 1)
157 return;
158
159 // Check if the first argument is stack allocated. If so, issue a warning
160 // because that's likely to be bad news.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000161 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +0000162 const MemRegion *R =
163 state->getSVal(CE->getArg(0), C.getLocationContext()).getAsRegion();
Ted Kremenek99d98382010-04-08 19:53:31 +0000164 if (!R || !isa<StackSpaceRegion>(R->getMemorySpace()))
165 return;
166
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000167 ExplodedNode *N = C.generateSink(state);
Ted Kremenek99d98382010-04-08 19:53:31 +0000168 if (!N)
169 return;
170
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000171 SmallString<256> S;
Ted Kremenek99d98382010-04-08 19:53:31 +0000172 llvm::raw_svector_ostream os(S);
173 os << "Call to 'pthread_once' uses";
174 if (const VarRegion *VR = dyn_cast<VarRegion>(R))
175 os << " the local variable '" << VR->getDecl()->getName() << '\'';
176 else
177 os << " stack allocated memory";
178 os << " for the \"control\" value. Using such transient memory for "
179 "the control value is potentially dangerous.";
180 if (isa<VarRegion>(R) && isa<StackLocalsSpaceRegion>(R->getMemorySpace()))
181 os << " Perhaps you intended to declare the variable as 'static'?";
182
Jordy Roseaf5b0432011-07-15 06:28:59 +0000183 LazyInitialize(BT_pthreadOnce, "Improper use of 'pthread_once'");
184
Anna Zakse172e8b2011-08-17 23:00:25 +0000185 BugReport *report = new BugReport(*BT_pthreadOnce, os.str(), N);
Ted Kremenek99d98382010-04-08 19:53:31 +0000186 report->addRange(CE->getArg(0)->getSourceRange());
Jordan Rose785950e2012-11-02 01:53:40 +0000187 C.emitReport(report);
Ted Kremenek99d98382010-04-08 19:53:31 +0000188}
189
190//===----------------------------------------------------------------------===//
Jordan Roseeafaad22012-10-30 01:37:16 +0000191// "calloc", "malloc", "realloc", "reallocf", "alloca" and "valloc"
192// with allocation size 0
Ted Kremenekb12fbc22010-11-16 18:47:04 +0000193//===----------------------------------------------------------------------===//
Ted Kremenek3e977582012-01-11 08:13:21 +0000194// FIXME: Eventually these should be rolled into the MallocChecker, but right now
195// they're more basic and valuable for widespread use.
Ted Kremenekb12fbc22010-11-16 18:47:04 +0000196
Ted Kremenekc1275da2012-01-03 23:43:13 +0000197// Returns true if we try to do a zero byte allocation, false otherwise.
198// Fills in trueState and falseState.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000199static bool IsZeroByteAllocation(ProgramStateRef state,
Ted Kremenekc1275da2012-01-03 23:43:13 +0000200 const SVal argVal,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000201 ProgramStateRef *trueState,
202 ProgramStateRef *falseState) {
Ted Kremenek3e977582012-01-11 08:13:21 +0000203 llvm::tie(*trueState, *falseState) =
David Blaikie5251abe2013-02-20 05:52:05 +0000204 state->assume(argVal.castAs<DefinedSVal>());
Ted Kremenek3e977582012-01-11 08:13:21 +0000205
Ted Kremenekc1275da2012-01-03 23:43:13 +0000206 return (*falseState && !*trueState);
207}
208
209// Generates an error report, indicating that the function whose name is given
210// will perform a zero byte allocation.
211// Returns false if an error occured, true otherwise.
212bool UnixAPIChecker::ReportZeroByteAllocation(CheckerContext &C,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000213 ProgramStateRef falseState,
Ted Kremenekc1275da2012-01-03 23:43:13 +0000214 const Expr *arg,
215 const char *fn_name) const {
216 ExplodedNode *N = C.generateSink(falseState);
217 if (!N)
218 return false;
219
Ted Kremenek3e977582012-01-11 08:13:21 +0000220 LazyInitialize(BT_mallocZero,
221 "Undefined allocation of 0 bytes (CERT MEM04-C; CWE-131)");
Ted Kremenekc1275da2012-01-03 23:43:13 +0000222
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000223 SmallString<256> S;
Ted Kremenekc1275da2012-01-03 23:43:13 +0000224 llvm::raw_svector_ostream os(S);
225 os << "Call to '" << fn_name << "' has an allocation size of 0 bytes";
226 BugReport *report = new BugReport(*BT_mallocZero, os.str(), N);
227
228 report->addRange(arg->getSourceRange());
Jordan Rosea1f81bb2012-08-28 00:50:51 +0000229 bugreporter::trackNullOrUndefValue(N, arg, *report);
Jordan Rose785950e2012-11-02 01:53:40 +0000230 C.emitReport(report);
Ted Kremenekc1275da2012-01-03 23:43:13 +0000231
232 return true;
233}
234
Ted Kremenek3e977582012-01-11 08:13:21 +0000235// Does a basic check for 0-sized allocations suitable for most of the below
236// functions (modulo "calloc")
237void UnixAPIChecker::BasicAllocationCheck(CheckerContext &C,
238 const CallExpr *CE,
239 const unsigned numArgs,
240 const unsigned sizeArg,
241 const char *fn) const {
242 // Sanity check for the correct number of arguments
243 if (CE->getNumArgs() != numArgs)
244 return;
245
246 // Check if the allocation size is 0.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000247 ProgramStateRef state = C.getState();
248 ProgramStateRef trueState = NULL, falseState = NULL;
Ted Kremenek3e977582012-01-11 08:13:21 +0000249 const Expr *arg = CE->getArg(sizeArg);
250 SVal argVal = state->getSVal(arg, C.getLocationContext());
251
252 if (argVal.isUnknownOrUndef())
253 return;
254
255 // Is the value perfectly constrained to zero?
256 if (IsZeroByteAllocation(state, argVal, &trueState, &falseState)) {
257 (void) ReportZeroByteAllocation(C, falseState, arg, fn);
258 return;
259 }
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +0000260 // Assume the value is non-zero going forward.
Ted Kremenek3e977582012-01-11 08:13:21 +0000261 assert(trueState);
262 if (trueState != state)
263 C.addTransition(trueState);
264}
265
Ted Kremenekc1275da2012-01-03 23:43:13 +0000266void UnixAPIChecker::CheckCallocZero(CheckerContext &C,
267 const CallExpr *CE) const {
268 unsigned int nArgs = CE->getNumArgs();
269 if (nArgs != 2)
270 return;
271
Ted Kremenek8bef8232012-01-26 21:29:00 +0000272 ProgramStateRef state = C.getState();
273 ProgramStateRef trueState = NULL, falseState = NULL;
Ted Kremenekc1275da2012-01-03 23:43:13 +0000274
275 unsigned int i;
276 for (i = 0; i < nArgs; i++) {
277 const Expr *arg = CE->getArg(i);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000278 SVal argVal = state->getSVal(arg, C.getLocationContext());
Ted Kremenekc1275da2012-01-03 23:43:13 +0000279 if (argVal.isUnknownOrUndef()) {
280 if (i == 0)
281 continue;
282 else
283 return;
284 }
285
286 if (IsZeroByteAllocation(state, argVal, &trueState, &falseState)) {
287 if (ReportZeroByteAllocation(C, falseState, arg, "calloc"))
288 return;
289 else if (i == 0)
290 continue;
291 else
292 return;
293 }
294 }
295
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +0000296 // Assume the value is non-zero going forward.
Ted Kremenekc1275da2012-01-03 23:43:13 +0000297 assert(trueState);
298 if (trueState != state)
299 C.addTransition(trueState);
300}
301
Jordy Roseaf5b0432011-07-15 06:28:59 +0000302void UnixAPIChecker::CheckMallocZero(CheckerContext &C,
303 const CallExpr *CE) const {
Ted Kremenek3e977582012-01-11 08:13:21 +0000304 BasicAllocationCheck(C, CE, 1, 0, "malloc");
Ted Kremenekc1275da2012-01-03 23:43:13 +0000305}
306
307void UnixAPIChecker::CheckReallocZero(CheckerContext &C,
308 const CallExpr *CE) const {
Ted Kremenek3e977582012-01-11 08:13:21 +0000309 BasicAllocationCheck(C, CE, 2, 1, "realloc");
Ted Kremenekb12fbc22010-11-16 18:47:04 +0000310}
Ted Kremenek3e977582012-01-11 08:13:21 +0000311
Jordan Roseeafaad22012-10-30 01:37:16 +0000312void UnixAPIChecker::CheckReallocfZero(CheckerContext &C,
313 const CallExpr *CE) const {
314 BasicAllocationCheck(C, CE, 2, 1, "reallocf");
315}
316
Ted Kremenek3e977582012-01-11 08:13:21 +0000317void UnixAPIChecker::CheckAllocaZero(CheckerContext &C,
318 const CallExpr *CE) const {
319 BasicAllocationCheck(C, CE, 1, 0, "alloca");
320}
321
322void UnixAPIChecker::CheckVallocZero(CheckerContext &C,
323 const CallExpr *CE) const {
324 BasicAllocationCheck(C, CE, 1, 0, "valloc");
325}
326
327
Ted Kremenekb12fbc22010-11-16 18:47:04 +0000328//===----------------------------------------------------------------------===//
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000329// Central dispatch function.
330//===----------------------------------------------------------------------===//
331
Ted Kremenek3e977582012-01-11 08:13:21 +0000332void UnixAPIChecker::checkPreStmt(const CallExpr *CE,
333 CheckerContext &C) const {
Jordan Rose5ef6e942012-07-10 23:13:01 +0000334 const FunctionDecl *FD = C.getCalleeDecl(CE);
335 if (!FD || FD->getKind() != Decl::Function)
336 return;
337
338 StringRef FName = C.getCalleeName(FD);
Anna Zaksb805c8f2011-12-01 05:57:37 +0000339 if (FName.empty())
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000340 return;
341
Jordy Roseaf5b0432011-07-15 06:28:59 +0000342 SubChecker SC =
Anna Zaksb805c8f2011-12-01 05:57:37 +0000343 llvm::StringSwitch<SubChecker>(FName)
Jordy Roseaf5b0432011-07-15 06:28:59 +0000344 .Case("open", &UnixAPIChecker::CheckOpen)
345 .Case("pthread_once", &UnixAPIChecker::CheckPthreadOnce)
Ted Kremenekc1275da2012-01-03 23:43:13 +0000346 .Case("calloc", &UnixAPIChecker::CheckCallocZero)
Jordy Roseaf5b0432011-07-15 06:28:59 +0000347 .Case("malloc", &UnixAPIChecker::CheckMallocZero)
Ted Kremenekc1275da2012-01-03 23:43:13 +0000348 .Case("realloc", &UnixAPIChecker::CheckReallocZero)
Jordan Roseeafaad22012-10-30 01:37:16 +0000349 .Case("reallocf", &UnixAPIChecker::CheckReallocfZero)
Ted Kremenek3e977582012-01-11 08:13:21 +0000350 .Cases("alloca", "__builtin_alloca", &UnixAPIChecker::CheckAllocaZero)
351 .Case("valloc", &UnixAPIChecker::CheckVallocZero)
Jordy Roseaf5b0432011-07-15 06:28:59 +0000352 .Default(NULL);
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000353
Jordy Roseaf5b0432011-07-15 06:28:59 +0000354 if (SC)
355 (this->*SC)(C, CE);
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000356}
Argyrios Kyrtzidis983326f2011-02-23 01:05:36 +0000357
358//===----------------------------------------------------------------------===//
359// Registration.
360//===----------------------------------------------------------------------===//
361
362void ento::registerUnixAPIChecker(CheckerManager &mgr) {
363 mgr.registerChecker<UnixAPIChecker>();
364}