blob: 375dc82b5a7368acd68332c0ebf4f45b25196292 [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 Kramer00bd44d2012-02-04 12:31:12 +000022#include "llvm/ADT/STLExtras.h"
Benjamin Kramer5e2d2c22010-03-27 21:19:47 +000023#include "llvm/ADT/StringSwitch.h"
Ted Kremenek381d1bf2010-02-25 00:20:35 +000024#include <fcntl.h>
25
26using namespace clang;
Ted Kremenek9ef65372010-12-23 07:20:52 +000027using namespace ento;
Ted Kremenek66d51422010-04-09 20:26:58 +000028using llvm::Optional;
Ted Kremenek381d1bf2010-02-25 00:20:35 +000029
30namespace {
Argyrios Kyrtzidisec8605f2011-03-01 01:16:21 +000031class UnixAPIChecker : public Checker< check::PreStmt<CallExpr> > {
Jordy Roseaf5b0432011-07-15 06:28:59 +000032 mutable llvm::OwningPtr<BugType> BT_open, BT_pthreadOnce, BT_mallocZero;
Argyrios Kyrtzidis983326f2011-02-23 01:05:36 +000033 mutable Optional<uint64_t> Val_O_CREAT;
Ted Kremenekbace4ba2010-04-08 22:15:34 +000034
35public:
Argyrios Kyrtzidis983326f2011-02-23 01:05:36 +000036 void checkPreStmt(const CallExpr *CE, CheckerContext &C) const;
Jordy Roseaf5b0432011-07-15 06:28:59 +000037
38 void CheckOpen(CheckerContext &C, const CallExpr *CE) const;
39 void CheckPthreadOnce(CheckerContext &C, const CallExpr *CE) const;
Ted Kremenekc1275da2012-01-03 23:43:13 +000040 void CheckCallocZero(CheckerContext &C, const CallExpr *CE) const;
Jordy Roseaf5b0432011-07-15 06:28:59 +000041 void CheckMallocZero(CheckerContext &C, const CallExpr *CE) const;
Ted Kremenekc1275da2012-01-03 23:43:13 +000042 void CheckReallocZero(CheckerContext &C, const CallExpr *CE) const;
Ted Kremenek3e977582012-01-11 08:13:21 +000043 void CheckAllocaZero(CheckerContext &C, const CallExpr *CE) const;
44 void CheckVallocZero(CheckerContext &C, const CallExpr *CE) const;
Jordy Roseaf5b0432011-07-15 06:28:59 +000045
46 typedef void (UnixAPIChecker::*SubChecker)(CheckerContext &,
47 const CallExpr *) const;
Ted Kremenekc1275da2012-01-03 23:43:13 +000048private:
49 bool ReportZeroByteAllocation(CheckerContext &C,
Ted Kremenek8bef8232012-01-26 21:29:00 +000050 ProgramStateRef falseState,
Ted Kremenekc1275da2012-01-03 23:43:13 +000051 const Expr *arg,
52 const char *fn_name) const;
Ted Kremenek3e977582012-01-11 08:13:21 +000053 void BasicAllocationCheck(CheckerContext &C,
54 const CallExpr *CE,
55 const unsigned numArgs,
56 const unsigned sizeArg,
57 const char *fn) const;
Ted Kremenek381d1bf2010-02-25 00:20:35 +000058};
59} //end anonymous namespace
60
Ted Kremenek381d1bf2010-02-25 00:20:35 +000061//===----------------------------------------------------------------------===//
62// Utility functions.
63//===----------------------------------------------------------------------===//
64
Jordy Roseaf5b0432011-07-15 06:28:59 +000065static inline void LazyInitialize(llvm::OwningPtr<BugType> &BT,
66 const char *name) {
Ted Kremenek381d1bf2010-02-25 00:20:35 +000067 if (BT)
68 return;
Jordy Roseaf5b0432011-07-15 06:28:59 +000069 BT.reset(new BugType(name, "Unix API"));
Ted Kremenek381d1bf2010-02-25 00:20:35 +000070}
71
72//===----------------------------------------------------------------------===//
73// "open" (man 2 open)
74//===----------------------------------------------------------------------===//
75
Jordy Roseaf5b0432011-07-15 06:28:59 +000076void UnixAPIChecker::CheckOpen(CheckerContext &C, const CallExpr *CE) const {
Ted Kremenekbace4ba2010-04-08 22:15:34 +000077 // The definition of O_CREAT is platform specific. We need a better way
78 // of querying this information from the checking environment.
Jordy Roseaf5b0432011-07-15 06:28:59 +000079 if (!Val_O_CREAT.hasValue()) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000080 if (C.getASTContext().getTargetInfo().getTriple().getVendor()
81 == llvm::Triple::Apple)
Jordy Roseaf5b0432011-07-15 06:28:59 +000082 Val_O_CREAT = 0x0200;
Ted Kremenekbace4ba2010-04-08 22:15:34 +000083 else {
84 // FIXME: We need a more general way of getting the O_CREAT value.
85 // We could possibly grovel through the preprocessor state, but
Argyrios Kyrtzidisd2592a32010-12-22 18:53:44 +000086 // that would require passing the Preprocessor object to the ExprEngine.
Ted Kremenekbace4ba2010-04-08 22:15:34 +000087 return;
88 }
89 }
90
Ted Kremenek381d1bf2010-02-25 00:20:35 +000091 // Look at the 'oflags' argument for the O_CREAT flag.
Ted Kremenek8bef8232012-01-26 21:29:00 +000092 ProgramStateRef state = C.getState();
Ted Kremenek381d1bf2010-02-25 00:20:35 +000093
94 if (CE->getNumArgs() < 2) {
95 // The frontend should issue a warning for this case, so this is a sanity
96 // check.
97 return;
98 }
99
100 // Now check if oflags has O_CREAT set.
101 const Expr *oflagsEx = CE->getArg(1);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000102 const SVal V = state->getSVal(oflagsEx, C.getLocationContext());
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000103 if (!isa<NonLoc>(V)) {
104 // The case where 'V' can be a location can only be due to a bad header,
105 // so in this case bail out.
106 return;
107 }
108 NonLoc oflags = cast<NonLoc>(V);
109 NonLoc ocreateFlag =
Jordy Roseaf5b0432011-07-15 06:28:59 +0000110 cast<NonLoc>(C.getSValBuilder().makeIntVal(Val_O_CREAT.getValue(),
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000111 oflagsEx->getType()));
Ted Kremenek9c149532010-12-01 21:57:22 +0000112 SVal maskedFlagsUC = C.getSValBuilder().evalBinOpNN(state, BO_And,
Ted Kremenek846eabd2010-12-01 21:28:31 +0000113 oflags, ocreateFlag,
114 oflagsEx->getType());
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000115 if (maskedFlagsUC.isUnknownOrUndef())
116 return;
117 DefinedSVal maskedFlags = cast<DefinedSVal>(maskedFlagsUC);
118
119 // Check if maskedFlags is non-zero.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000120 ProgramStateRef trueState, falseState;
Ted Kremenek28f47b92010-12-01 22:16:56 +0000121 llvm::tie(trueState, falseState) = state->assume(maskedFlags);
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000122
123 // Only emit an error if the value of 'maskedFlags' is properly
124 // constrained;
125 if (!(trueState && !falseState))
126 return;
127
128 if (CE->getNumArgs() < 3) {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000129 ExplodedNode *N = C.generateSink(trueState);
Ted Kremenekc757d792010-02-25 05:44:05 +0000130 if (!N)
131 return;
132
Jordy Roseaf5b0432011-07-15 06:28:59 +0000133 LazyInitialize(BT_open, "Improper use of 'open'");
134
Anna Zakse172e8b2011-08-17 23:00:25 +0000135 BugReport *report =
136 new BugReport(*BT_open,
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000137 "Call to 'open' requires a third argument when "
138 "the 'O_CREAT' flag is set", N);
139 report->addRange(oflagsEx->getSourceRange());
140 C.EmitReport(report);
141 }
142}
143
144//===----------------------------------------------------------------------===//
Ted Kremenek99d98382010-04-08 19:53:31 +0000145// pthread_once
146//===----------------------------------------------------------------------===//
147
Jordy Roseaf5b0432011-07-15 06:28:59 +0000148void UnixAPIChecker::CheckPthreadOnce(CheckerContext &C,
149 const CallExpr *CE) const {
Ted Kremenek99d98382010-04-08 19:53:31 +0000150
151 // This is similar to 'CheckDispatchOnce' in the MacOSXAPIChecker.
152 // They can possibly be refactored.
153
Ted Kremenek99d98382010-04-08 19:53:31 +0000154 if (CE->getNumArgs() < 1)
155 return;
156
157 // Check if the first argument is stack allocated. If so, issue a warning
158 // because that's likely to be bad news.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000159 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +0000160 const MemRegion *R =
161 state->getSVal(CE->getArg(0), C.getLocationContext()).getAsRegion();
Ted Kremenek99d98382010-04-08 19:53:31 +0000162 if (!R || !isa<StackSpaceRegion>(R->getMemorySpace()))
163 return;
164
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000165 ExplodedNode *N = C.generateSink(state);
Ted Kremenek99d98382010-04-08 19:53:31 +0000166 if (!N)
167 return;
168
169 llvm::SmallString<256> S;
170 llvm::raw_svector_ostream os(S);
171 os << "Call to 'pthread_once' uses";
172 if (const VarRegion *VR = dyn_cast<VarRegion>(R))
173 os << " the local variable '" << VR->getDecl()->getName() << '\'';
174 else
175 os << " stack allocated memory";
176 os << " for the \"control\" value. Using such transient memory for "
177 "the control value is potentially dangerous.";
178 if (isa<VarRegion>(R) && isa<StackLocalsSpaceRegion>(R->getMemorySpace()))
179 os << " Perhaps you intended to declare the variable as 'static'?";
180
Jordy Roseaf5b0432011-07-15 06:28:59 +0000181 LazyInitialize(BT_pthreadOnce, "Improper use of 'pthread_once'");
182
Anna Zakse172e8b2011-08-17 23:00:25 +0000183 BugReport *report = new BugReport(*BT_pthreadOnce, os.str(), N);
Ted Kremenek99d98382010-04-08 19:53:31 +0000184 report->addRange(CE->getArg(0)->getSourceRange());
185 C.EmitReport(report);
186}
187
188//===----------------------------------------------------------------------===//
Ted Kremenek3e977582012-01-11 08:13:21 +0000189// "calloc", "malloc", "realloc", "alloca" and "valloc" with allocation size 0
Ted Kremenekb12fbc22010-11-16 18:47:04 +0000190//===----------------------------------------------------------------------===//
Ted Kremenek3e977582012-01-11 08:13:21 +0000191// FIXME: Eventually these should be rolled into the MallocChecker, but right now
192// they're more basic and valuable for widespread use.
Ted Kremenekb12fbc22010-11-16 18:47:04 +0000193
Ted Kremenekc1275da2012-01-03 23:43:13 +0000194// Returns true if we try to do a zero byte allocation, false otherwise.
195// Fills in trueState and falseState.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000196static bool IsZeroByteAllocation(ProgramStateRef state,
Ted Kremenekc1275da2012-01-03 23:43:13 +0000197 const SVal argVal,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000198 ProgramStateRef *trueState,
199 ProgramStateRef *falseState) {
Ted Kremenek3e977582012-01-11 08:13:21 +0000200 llvm::tie(*trueState, *falseState) =
201 state->assume(cast<DefinedSVal>(argVal));
202
Ted Kremenekc1275da2012-01-03 23:43:13 +0000203 return (*falseState && !*trueState);
204}
205
206// Generates an error report, indicating that the function whose name is given
207// will perform a zero byte allocation.
208// Returns false if an error occured, true otherwise.
209bool UnixAPIChecker::ReportZeroByteAllocation(CheckerContext &C,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000210 ProgramStateRef falseState,
Ted Kremenekc1275da2012-01-03 23:43:13 +0000211 const Expr *arg,
212 const char *fn_name) const {
213 ExplodedNode *N = C.generateSink(falseState);
214 if (!N)
215 return false;
216
Ted Kremenek3e977582012-01-11 08:13:21 +0000217 LazyInitialize(BT_mallocZero,
218 "Undefined allocation of 0 bytes (CERT MEM04-C; CWE-131)");
Ted Kremenekc1275da2012-01-03 23:43:13 +0000219
220 llvm::SmallString<256> S;
221 llvm::raw_svector_ostream os(S);
222 os << "Call to '" << fn_name << "' has an allocation size of 0 bytes";
223 BugReport *report = new BugReport(*BT_mallocZero, os.str(), N);
224
225 report->addRange(arg->getSourceRange());
226 report->addVisitor(bugreporter::getTrackNullOrUndefValueVisitor(N, arg));
227 C.EmitReport(report);
228
229 return true;
230}
231
Ted Kremenek3e977582012-01-11 08:13:21 +0000232// Does a basic check for 0-sized allocations suitable for most of the below
233// functions (modulo "calloc")
234void UnixAPIChecker::BasicAllocationCheck(CheckerContext &C,
235 const CallExpr *CE,
236 const unsigned numArgs,
237 const unsigned sizeArg,
238 const char *fn) const {
239 // Sanity check for the correct number of arguments
240 if (CE->getNumArgs() != numArgs)
241 return;
242
243 // Check if the allocation size is 0.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000244 ProgramStateRef state = C.getState();
245 ProgramStateRef trueState = NULL, falseState = NULL;
Ted Kremenek3e977582012-01-11 08:13:21 +0000246 const Expr *arg = CE->getArg(sizeArg);
247 SVal argVal = state->getSVal(arg, C.getLocationContext());
248
249 if (argVal.isUnknownOrUndef())
250 return;
251
252 // Is the value perfectly constrained to zero?
253 if (IsZeroByteAllocation(state, argVal, &trueState, &falseState)) {
254 (void) ReportZeroByteAllocation(C, falseState, arg, fn);
255 return;
256 }
257 // Assume the the value is non-zero going forward.
258 assert(trueState);
259 if (trueState != state)
260 C.addTransition(trueState);
261}
262
Ted Kremenekc1275da2012-01-03 23:43:13 +0000263void UnixAPIChecker::CheckCallocZero(CheckerContext &C,
264 const CallExpr *CE) const {
265 unsigned int nArgs = CE->getNumArgs();
266 if (nArgs != 2)
267 return;
268
Ted Kremenek8bef8232012-01-26 21:29:00 +0000269 ProgramStateRef state = C.getState();
270 ProgramStateRef trueState = NULL, falseState = NULL;
Ted Kremenekc1275da2012-01-03 23:43:13 +0000271
272 unsigned int i;
273 for (i = 0; i < nArgs; i++) {
274 const Expr *arg = CE->getArg(i);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000275 SVal argVal = state->getSVal(arg, C.getLocationContext());
Ted Kremenekc1275da2012-01-03 23:43:13 +0000276 if (argVal.isUnknownOrUndef()) {
277 if (i == 0)
278 continue;
279 else
280 return;
281 }
282
283 if (IsZeroByteAllocation(state, argVal, &trueState, &falseState)) {
284 if (ReportZeroByteAllocation(C, falseState, arg, "calloc"))
285 return;
286 else if (i == 0)
287 continue;
288 else
289 return;
290 }
291 }
292
293 // Assume the the value is non-zero going forward.
294 assert(trueState);
295 if (trueState != state)
296 C.addTransition(trueState);
297}
298
Jordy Roseaf5b0432011-07-15 06:28:59 +0000299void UnixAPIChecker::CheckMallocZero(CheckerContext &C,
300 const CallExpr *CE) const {
Ted Kremenek3e977582012-01-11 08:13:21 +0000301 BasicAllocationCheck(C, CE, 1, 0, "malloc");
Ted Kremenekc1275da2012-01-03 23:43:13 +0000302}
303
304void UnixAPIChecker::CheckReallocZero(CheckerContext &C,
305 const CallExpr *CE) const {
Ted Kremenek3e977582012-01-11 08:13:21 +0000306 BasicAllocationCheck(C, CE, 2, 1, "realloc");
Ted Kremenekb12fbc22010-11-16 18:47:04 +0000307}
Ted Kremenek3e977582012-01-11 08:13:21 +0000308
309void UnixAPIChecker::CheckAllocaZero(CheckerContext &C,
310 const CallExpr *CE) const {
311 BasicAllocationCheck(C, CE, 1, 0, "alloca");
312}
313
314void UnixAPIChecker::CheckVallocZero(CheckerContext &C,
315 const CallExpr *CE) const {
316 BasicAllocationCheck(C, CE, 1, 0, "valloc");
317}
318
319
Ted Kremenekb12fbc22010-11-16 18:47:04 +0000320//===----------------------------------------------------------------------===//
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000321// Central dispatch function.
322//===----------------------------------------------------------------------===//
323
Ted Kremenek3e977582012-01-11 08:13:21 +0000324void UnixAPIChecker::checkPreStmt(const CallExpr *CE,
325 CheckerContext &C) const {
Anna Zaksb805c8f2011-12-01 05:57:37 +0000326 StringRef FName = C.getCalleeName(CE);
327 if (FName.empty())
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000328 return;
329
Jordy Roseaf5b0432011-07-15 06:28:59 +0000330 SubChecker SC =
Anna Zaksb805c8f2011-12-01 05:57:37 +0000331 llvm::StringSwitch<SubChecker>(FName)
Jordy Roseaf5b0432011-07-15 06:28:59 +0000332 .Case("open", &UnixAPIChecker::CheckOpen)
333 .Case("pthread_once", &UnixAPIChecker::CheckPthreadOnce)
Ted Kremenekc1275da2012-01-03 23:43:13 +0000334 .Case("calloc", &UnixAPIChecker::CheckCallocZero)
Jordy Roseaf5b0432011-07-15 06:28:59 +0000335 .Case("malloc", &UnixAPIChecker::CheckMallocZero)
Ted Kremenekc1275da2012-01-03 23:43:13 +0000336 .Case("realloc", &UnixAPIChecker::CheckReallocZero)
Ted Kremenek3e977582012-01-11 08:13:21 +0000337 .Cases("alloca", "__builtin_alloca", &UnixAPIChecker::CheckAllocaZero)
338 .Case("valloc", &UnixAPIChecker::CheckVallocZero)
Jordy Roseaf5b0432011-07-15 06:28:59 +0000339 .Default(NULL);
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000340
Jordy Roseaf5b0432011-07-15 06:28:59 +0000341 if (SC)
342 (this->*SC)(C, CE);
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000343}
Argyrios Kyrtzidis983326f2011-02-23 01:05:36 +0000344
345//===----------------------------------------------------------------------===//
346// Registration.
347//===----------------------------------------------------------------------===//
348
349void ento::registerUnixAPIChecker(CheckerManager &mgr) {
350 mgr.registerChecker<UnixAPIChecker>();
351}