blob: aa7e25bc671da7f82e85dae943e72542134e02ad [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 Kremenek381d1bf2010-02-25 00:20:35 +000030
31namespace {
Argyrios Kyrtzidisec8605f2011-03-01 01:16:21 +000032class UnixAPIChecker : public Checker< check::PreStmt<CallExpr> > {
Stephen Hines651f13c2014-04-23 16:59:28 -070033 mutable std::unique_ptr<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;
Jordan Roseeafaad22012-10-30 01:37:16 +000044 void CheckReallocfZero(CheckerContext &C, const CallExpr *CE) const;
Ted Kremenek3e977582012-01-11 08:13:21 +000045 void CheckAllocaZero(CheckerContext &C, const CallExpr *CE) const;
46 void CheckVallocZero(CheckerContext &C, const CallExpr *CE) const;
Jordy Roseaf5b0432011-07-15 06:28:59 +000047
48 typedef void (UnixAPIChecker::*SubChecker)(CheckerContext &,
49 const CallExpr *) const;
Ted Kremenekc1275da2012-01-03 23:43:13 +000050private:
51 bool ReportZeroByteAllocation(CheckerContext &C,
Ted Kremenek8bef8232012-01-26 21:29:00 +000052 ProgramStateRef falseState,
Ted Kremenekc1275da2012-01-03 23:43:13 +000053 const Expr *arg,
54 const char *fn_name) const;
Ted Kremenek3e977582012-01-11 08:13:21 +000055 void BasicAllocationCheck(CheckerContext &C,
56 const CallExpr *CE,
57 const unsigned numArgs,
58 const unsigned sizeArg,
59 const char *fn) const;
Stephen Hines651f13c2014-04-23 16:59:28 -070060 void LazyInitialize(std::unique_ptr<BugType> &BT, const char *name) const {
61 if (BT)
62 return;
63 BT.reset(new BugType(this, name, categories::UnixAPI));
64 }
Ted Kremenek381d1bf2010-02-25 00:20:35 +000065};
66} //end anonymous namespace
67
Ted Kremenek381d1bf2010-02-25 00:20:35 +000068//===----------------------------------------------------------------------===//
Ted Kremenek381d1bf2010-02-25 00:20:35 +000069// "open" (man 2 open)
70//===----------------------------------------------------------------------===//
71
Jordy Roseaf5b0432011-07-15 06:28:59 +000072void UnixAPIChecker::CheckOpen(CheckerContext &C, const CallExpr *CE) const {
Ted Kremenekbace4ba2010-04-08 22:15:34 +000073 // The definition of O_CREAT is platform specific. We need a better way
74 // of querying this information from the checking environment.
Jordy Roseaf5b0432011-07-15 06:28:59 +000075 if (!Val_O_CREAT.hasValue()) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000076 if (C.getASTContext().getTargetInfo().getTriple().getVendor()
77 == llvm::Triple::Apple)
Jordy Roseaf5b0432011-07-15 06:28:59 +000078 Val_O_CREAT = 0x0200;
Ted Kremenekbace4ba2010-04-08 22:15:34 +000079 else {
80 // FIXME: We need a more general way of getting the O_CREAT value.
81 // We could possibly grovel through the preprocessor state, but
Argyrios Kyrtzidisd2592a32010-12-22 18:53:44 +000082 // that would require passing the Preprocessor object to the ExprEngine.
Stephen Hines651f13c2014-04-23 16:59:28 -070083 // See also: MallocChecker.cpp / M_ZERO.
Ted Kremenekbace4ba2010-04-08 22:15:34 +000084 return;
85 }
86 }
87
Ted Kremenek381d1bf2010-02-25 00:20:35 +000088 // Look at the 'oflags' argument for the O_CREAT flag.
Ted Kremenek8bef8232012-01-26 21:29:00 +000089 ProgramStateRef state = C.getState();
Ted Kremenek381d1bf2010-02-25 00:20:35 +000090
91 if (CE->getNumArgs() < 2) {
92 // The frontend should issue a warning for this case, so this is a sanity
93 // check.
94 return;
95 }
96
97 // Now check if oflags has O_CREAT set.
98 const Expr *oflagsEx = CE->getArg(1);
Ted Kremenek5eca4822012-01-06 22:09:28 +000099 const SVal V = state->getSVal(oflagsEx, C.getLocationContext());
David Blaikie5251abe2013-02-20 05:52:05 +0000100 if (!V.getAs<NonLoc>()) {
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000101 // The case where 'V' can be a location can only be due to a bad header,
102 // so in this case bail out.
103 return;
104 }
David Blaikie5251abe2013-02-20 05:52:05 +0000105 NonLoc oflags = V.castAs<NonLoc>();
106 NonLoc ocreateFlag = C.getSValBuilder()
107 .makeIntVal(Val_O_CREAT.getValue(), oflagsEx->getType()).castAs<NonLoc>();
Ted Kremenek9c149532010-12-01 21:57:22 +0000108 SVal maskedFlagsUC = C.getSValBuilder().evalBinOpNN(state, BO_And,
Ted Kremenek846eabd2010-12-01 21:28:31 +0000109 oflags, ocreateFlag,
110 oflagsEx->getType());
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000111 if (maskedFlagsUC.isUnknownOrUndef())
112 return;
David Blaikie5251abe2013-02-20 05:52:05 +0000113 DefinedSVal maskedFlags = maskedFlagsUC.castAs<DefinedSVal>();
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000114
115 // Check if maskedFlags is non-zero.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000116 ProgramStateRef trueState, falseState;
Stephen Hines651f13c2014-04-23 16:59:28 -0700117 std::tie(trueState, falseState) = state->assume(maskedFlags);
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000118
119 // Only emit an error if the value of 'maskedFlags' is properly
120 // constrained;
121 if (!(trueState && !falseState))
122 return;
123
124 if (CE->getNumArgs() < 3) {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000125 ExplodedNode *N = C.generateSink(trueState);
Ted Kremenekc757d792010-02-25 05:44:05 +0000126 if (!N)
127 return;
128
Jordy Roseaf5b0432011-07-15 06:28:59 +0000129 LazyInitialize(BT_open, "Improper use of 'open'");
130
Anna Zakse172e8b2011-08-17 23:00:25 +0000131 BugReport *report =
132 new BugReport(*BT_open,
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000133 "Call to 'open' requires a third argument when "
134 "the 'O_CREAT' flag is set", N);
135 report->addRange(oflagsEx->getSourceRange());
Jordan Rose785950e2012-11-02 01:53:40 +0000136 C.emitReport(report);
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000137 }
138}
139
140//===----------------------------------------------------------------------===//
Ted Kremenek99d98382010-04-08 19:53:31 +0000141// pthread_once
142//===----------------------------------------------------------------------===//
143
Jordy Roseaf5b0432011-07-15 06:28:59 +0000144void UnixAPIChecker::CheckPthreadOnce(CheckerContext &C,
145 const CallExpr *CE) const {
Ted Kremenek99d98382010-04-08 19:53:31 +0000146
147 // This is similar to 'CheckDispatchOnce' in the MacOSXAPIChecker.
148 // They can possibly be refactored.
149
Ted Kremenek99d98382010-04-08 19:53:31 +0000150 if (CE->getNumArgs() < 1)
151 return;
152
153 // Check if the first argument is stack allocated. If so, issue a warning
154 // because that's likely to be bad news.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000155 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +0000156 const MemRegion *R =
157 state->getSVal(CE->getArg(0), C.getLocationContext()).getAsRegion();
Ted Kremenek99d98382010-04-08 19:53:31 +0000158 if (!R || !isa<StackSpaceRegion>(R->getMemorySpace()))
159 return;
160
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000161 ExplodedNode *N = C.generateSink(state);
Ted Kremenek99d98382010-04-08 19:53:31 +0000162 if (!N)
163 return;
164
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000165 SmallString<256> S;
Ted Kremenek99d98382010-04-08 19:53:31 +0000166 llvm::raw_svector_ostream os(S);
167 os << "Call to 'pthread_once' uses";
168 if (const VarRegion *VR = dyn_cast<VarRegion>(R))
169 os << " the local variable '" << VR->getDecl()->getName() << '\'';
170 else
171 os << " stack allocated memory";
172 os << " for the \"control\" value. Using such transient memory for "
173 "the control value is potentially dangerous.";
174 if (isa<VarRegion>(R) && isa<StackLocalsSpaceRegion>(R->getMemorySpace()))
175 os << " Perhaps you intended to declare the variable as 'static'?";
176
Jordy Roseaf5b0432011-07-15 06:28:59 +0000177 LazyInitialize(BT_pthreadOnce, "Improper use of 'pthread_once'");
178
Anna Zakse172e8b2011-08-17 23:00:25 +0000179 BugReport *report = new BugReport(*BT_pthreadOnce, os.str(), N);
Ted Kremenek99d98382010-04-08 19:53:31 +0000180 report->addRange(CE->getArg(0)->getSourceRange());
Jordan Rose785950e2012-11-02 01:53:40 +0000181 C.emitReport(report);
Ted Kremenek99d98382010-04-08 19:53:31 +0000182}
183
184//===----------------------------------------------------------------------===//
Jordan Roseeafaad22012-10-30 01:37:16 +0000185// "calloc", "malloc", "realloc", "reallocf", "alloca" and "valloc"
186// with allocation size 0
Ted Kremenekb12fbc22010-11-16 18:47:04 +0000187//===----------------------------------------------------------------------===//
Ted Kremenek3e977582012-01-11 08:13:21 +0000188// FIXME: Eventually these should be rolled into the MallocChecker, but right now
189// they're more basic and valuable for widespread use.
Ted Kremenekb12fbc22010-11-16 18:47:04 +0000190
Ted Kremenekc1275da2012-01-03 23:43:13 +0000191// Returns true if we try to do a zero byte allocation, false otherwise.
192// Fills in trueState and falseState.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000193static bool IsZeroByteAllocation(ProgramStateRef state,
Ted Kremenekc1275da2012-01-03 23:43:13 +0000194 const SVal argVal,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000195 ProgramStateRef *trueState,
196 ProgramStateRef *falseState) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700197 std::tie(*trueState, *falseState) =
David Blaikie5251abe2013-02-20 05:52:05 +0000198 state->assume(argVal.castAs<DefinedSVal>());
Ted Kremenek3e977582012-01-11 08:13:21 +0000199
Ted Kremenekc1275da2012-01-03 23:43:13 +0000200 return (*falseState && !*trueState);
201}
202
203// Generates an error report, indicating that the function whose name is given
204// will perform a zero byte allocation.
Stephen Hines651f13c2014-04-23 16:59:28 -0700205// Returns false if an error occurred, true otherwise.
Ted Kremenekc1275da2012-01-03 23:43:13 +0000206bool UnixAPIChecker::ReportZeroByteAllocation(CheckerContext &C,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000207 ProgramStateRef falseState,
Ted Kremenekc1275da2012-01-03 23:43:13 +0000208 const Expr *arg,
209 const char *fn_name) const {
210 ExplodedNode *N = C.generateSink(falseState);
211 if (!N)
212 return false;
213
Ted Kremenek3e977582012-01-11 08:13:21 +0000214 LazyInitialize(BT_mallocZero,
Stephen Hines651f13c2014-04-23 16:59:28 -0700215 "Undefined allocation of 0 bytes (CERT MEM04-C; CWE-131)");
Ted Kremenekc1275da2012-01-03 23:43:13 +0000216
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000217 SmallString<256> S;
Ted Kremenekc1275da2012-01-03 23:43:13 +0000218 llvm::raw_svector_ostream os(S);
219 os << "Call to '" << fn_name << "' has an allocation size of 0 bytes";
220 BugReport *report = new BugReport(*BT_mallocZero, os.str(), N);
221
222 report->addRange(arg->getSourceRange());
Jordan Rosea1f81bb2012-08-28 00:50:51 +0000223 bugreporter::trackNullOrUndefValue(N, arg, *report);
Jordan Rose785950e2012-11-02 01:53:40 +0000224 C.emitReport(report);
Ted Kremenekc1275da2012-01-03 23:43:13 +0000225
226 return true;
227}
228
Ted Kremenek3e977582012-01-11 08:13:21 +0000229// Does a basic check for 0-sized allocations suitable for most of the below
230// functions (modulo "calloc")
231void UnixAPIChecker::BasicAllocationCheck(CheckerContext &C,
232 const CallExpr *CE,
233 const unsigned numArgs,
234 const unsigned sizeArg,
235 const char *fn) const {
236 // Sanity check for the correct number of arguments
237 if (CE->getNumArgs() != numArgs)
238 return;
239
240 // Check if the allocation size is 0.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000241 ProgramStateRef state = C.getState();
242 ProgramStateRef trueState = NULL, falseState = NULL;
Ted Kremenek3e977582012-01-11 08:13:21 +0000243 const Expr *arg = CE->getArg(sizeArg);
244 SVal argVal = state->getSVal(arg, C.getLocationContext());
245
246 if (argVal.isUnknownOrUndef())
247 return;
248
249 // Is the value perfectly constrained to zero?
250 if (IsZeroByteAllocation(state, argVal, &trueState, &falseState)) {
251 (void) ReportZeroByteAllocation(C, falseState, arg, fn);
252 return;
253 }
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +0000254 // Assume the value is non-zero going forward.
Ted Kremenek3e977582012-01-11 08:13:21 +0000255 assert(trueState);
256 if (trueState != state)
257 C.addTransition(trueState);
258}
259
Ted Kremenekc1275da2012-01-03 23:43:13 +0000260void UnixAPIChecker::CheckCallocZero(CheckerContext &C,
261 const CallExpr *CE) const {
262 unsigned int nArgs = CE->getNumArgs();
263 if (nArgs != 2)
264 return;
265
Ted Kremenek8bef8232012-01-26 21:29:00 +0000266 ProgramStateRef state = C.getState();
267 ProgramStateRef trueState = NULL, falseState = NULL;
Ted Kremenekc1275da2012-01-03 23:43:13 +0000268
269 unsigned int i;
270 for (i = 0; i < nArgs; i++) {
271 const Expr *arg = CE->getArg(i);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000272 SVal argVal = state->getSVal(arg, C.getLocationContext());
Ted Kremenekc1275da2012-01-03 23:43:13 +0000273 if (argVal.isUnknownOrUndef()) {
274 if (i == 0)
275 continue;
276 else
277 return;
278 }
279
280 if (IsZeroByteAllocation(state, argVal, &trueState, &falseState)) {
281 if (ReportZeroByteAllocation(C, falseState, arg, "calloc"))
282 return;
283 else if (i == 0)
284 continue;
285 else
286 return;
287 }
288 }
289
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +0000290 // Assume the value is non-zero going forward.
Ted Kremenekc1275da2012-01-03 23:43:13 +0000291 assert(trueState);
292 if (trueState != state)
293 C.addTransition(trueState);
294}
295
Jordy Roseaf5b0432011-07-15 06:28:59 +0000296void UnixAPIChecker::CheckMallocZero(CheckerContext &C,
297 const CallExpr *CE) const {
Ted Kremenek3e977582012-01-11 08:13:21 +0000298 BasicAllocationCheck(C, CE, 1, 0, "malloc");
Ted Kremenekc1275da2012-01-03 23:43:13 +0000299}
300
301void UnixAPIChecker::CheckReallocZero(CheckerContext &C,
302 const CallExpr *CE) const {
Ted Kremenek3e977582012-01-11 08:13:21 +0000303 BasicAllocationCheck(C, CE, 2, 1, "realloc");
Ted Kremenekb12fbc22010-11-16 18:47:04 +0000304}
Ted Kremenek3e977582012-01-11 08:13:21 +0000305
Jordan Roseeafaad22012-10-30 01:37:16 +0000306void UnixAPIChecker::CheckReallocfZero(CheckerContext &C,
307 const CallExpr *CE) const {
308 BasicAllocationCheck(C, CE, 2, 1, "reallocf");
309}
310
Ted Kremenek3e977582012-01-11 08:13:21 +0000311void 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)
Jordan Roseeafaad22012-10-30 01:37:16 +0000343 .Case("reallocf", &UnixAPIChecker::CheckReallocfZero)
Ted Kremenek3e977582012-01-11 08:13:21 +0000344 .Cases("alloca", "__builtin_alloca", &UnixAPIChecker::CheckAllocaZero)
345 .Case("valloc", &UnixAPIChecker::CheckVallocZero)
Jordy Roseaf5b0432011-07-15 06:28:59 +0000346 .Default(NULL);
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000347
Jordy Roseaf5b0432011-07-15 06:28:59 +0000348 if (SC)
349 (this->*SC)(C, CE);
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000350}
Argyrios Kyrtzidis983326f2011-02-23 01:05:36 +0000351
352//===----------------------------------------------------------------------===//
353// Registration.
354//===----------------------------------------------------------------------===//
355
356void ento::registerUnixAPIChecker(CheckerManager &mgr) {
357 mgr.registerChecker<UnixAPIChecker>();
358}