blob: 28ff6971a24d13cd9c42c02d2aaa3ae9b180b51a [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);
94 const SVal V = state->getSVal(oflagsEx);
95 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 Kremenek99d98382010-04-08 19:53:31 +0000152 const MemRegion *R = state->getSVal(CE->getArg(0)).getAsRegion();
153 if (!R || !isa<StackSpaceRegion>(R->getMemorySpace()))
154 return;
155
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000156 ExplodedNode *N = C.generateSink(state);
Ted Kremenek99d98382010-04-08 19:53:31 +0000157 if (!N)
158 return;
159
160 llvm::SmallString<256> S;
161 llvm::raw_svector_ostream os(S);
162 os << "Call to 'pthread_once' uses";
163 if (const VarRegion *VR = dyn_cast<VarRegion>(R))
164 os << " the local variable '" << VR->getDecl()->getName() << '\'';
165 else
166 os << " stack allocated memory";
167 os << " for the \"control\" value. Using such transient memory for "
168 "the control value is potentially dangerous.";
169 if (isa<VarRegion>(R) && isa<StackLocalsSpaceRegion>(R->getMemorySpace()))
170 os << " Perhaps you intended to declare the variable as 'static'?";
171
Jordy Roseaf5b0432011-07-15 06:28:59 +0000172 LazyInitialize(BT_pthreadOnce, "Improper use of 'pthread_once'");
173
Anna Zakse172e8b2011-08-17 23:00:25 +0000174 BugReport *report = new BugReport(*BT_pthreadOnce, os.str(), N);
Ted Kremenek99d98382010-04-08 19:53:31 +0000175 report->addRange(CE->getArg(0)->getSourceRange());
176 C.EmitReport(report);
177}
178
179//===----------------------------------------------------------------------===//
Ted Kremenekc1275da2012-01-03 23:43:13 +0000180// "calloc", "malloc" and "realloc" with allocation size 0
Ted Kremenekb12fbc22010-11-16 18:47:04 +0000181//===----------------------------------------------------------------------===//
182
Ted Kremenekc1275da2012-01-03 23:43:13 +0000183// Returns true if we try to do a zero byte allocation, false otherwise.
184// Fills in trueState and falseState.
185static bool IsZeroByteAllocation(const ProgramState *state,
186 const SVal argVal,
187 const ProgramState **trueState,
188 const ProgramState **falseState) {
189 llvm::tie(*trueState, *falseState) = state->assume(cast<DefinedSVal>(argVal));
190 return (*falseState && !*trueState);
191}
192
193// Generates an error report, indicating that the function whose name is given
194// will perform a zero byte allocation.
195// Returns false if an error occured, true otherwise.
196bool UnixAPIChecker::ReportZeroByteAllocation(CheckerContext &C,
197 const ProgramState *falseState,
198 const Expr *arg,
199 const char *fn_name) const {
200 ExplodedNode *N = C.generateSink(falseState);
201 if (!N)
202 return false;
203
204 // FIXME: Add reference to CERT advisory, and/or C99 standard in bug
205 // output.
206 LazyInitialize(BT_mallocZero, "Undefined allocation of 0 bytes");
207
208 llvm::SmallString<256> S;
209 llvm::raw_svector_ostream os(S);
210 os << "Call to '" << fn_name << "' has an allocation size of 0 bytes";
211 BugReport *report = new BugReport(*BT_mallocZero, os.str(), N);
212
213 report->addRange(arg->getSourceRange());
214 report->addVisitor(bugreporter::getTrackNullOrUndefValueVisitor(N, arg));
215 C.EmitReport(report);
216
217 return true;
218}
219
220void UnixAPIChecker::CheckCallocZero(CheckerContext &C,
221 const CallExpr *CE) const {
222 unsigned int nArgs = CE->getNumArgs();
223 if (nArgs != 2)
224 return;
225
226 const ProgramState *state = C.getState();
227 const ProgramState *trueState = NULL, *falseState = NULL;
228
229 unsigned int i;
230 for (i = 0; i < nArgs; i++) {
231 const Expr *arg = CE->getArg(i);
232 SVal argVal = state->getSVal(arg);
233 if (argVal.isUnknownOrUndef()) {
234 if (i == 0)
235 continue;
236 else
237 return;
238 }
239
240 if (IsZeroByteAllocation(state, argVal, &trueState, &falseState)) {
241 if (ReportZeroByteAllocation(C, falseState, arg, "calloc"))
242 return;
243 else if (i == 0)
244 continue;
245 else
246 return;
247 }
248 }
249
250 // Assume the the value is non-zero going forward.
251 assert(trueState);
252 if (trueState != state)
253 C.addTransition(trueState);
254}
255
Ted Kremenekb12fbc22010-11-16 18:47:04 +0000256// FIXME: Eventually this should be rolled into the MallocChecker, but this
257// check is more basic and is valuable for widespread use.
Jordy Roseaf5b0432011-07-15 06:28:59 +0000258void UnixAPIChecker::CheckMallocZero(CheckerContext &C,
259 const CallExpr *CE) const {
Ted Kremenekb12fbc22010-11-16 18:47:04 +0000260 // Sanity check that malloc takes one argument.
261 if (CE->getNumArgs() != 1)
262 return;
263
264 // Check if the allocation size is 0.
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000265 const ProgramState *state = C.getState();
Ted Kremenekc1275da2012-01-03 23:43:13 +0000266 const ProgramState *trueState = NULL, *falseState = NULL;
267 const Expr *arg = CE->getArg(0);
268 SVal argVal = state->getSVal(arg);
Ted Kremenekb12fbc22010-11-16 18:47:04 +0000269
270 if (argVal.isUnknownOrUndef())
271 return;
Ted Kremenek8fec9722010-11-17 00:50:34 +0000272
Ted Kremenekc1275da2012-01-03 23:43:13 +0000273 // Is the value perfectly constrained to zero?
274 if (IsZeroByteAllocation(state, argVal, &trueState, &falseState)) {
275 (void) ReportZeroByteAllocation(C, falseState, arg, "malloc");
Ted Kremenekb12fbc22010-11-16 18:47:04 +0000276 return;
277 }
278 // Assume the the value is non-zero going forward.
279 assert(trueState);
Ted Kremenekc1275da2012-01-03 23:43:13 +0000280 if (trueState != state)
Anna Zaks0bd6b112011-10-26 21:06:34 +0000281 C.addTransition(trueState);
Ted Kremenekc1275da2012-01-03 23:43:13 +0000282}
283
284void UnixAPIChecker::CheckReallocZero(CheckerContext &C,
285 const CallExpr *CE) const {
286 if (CE->getNumArgs() != 2)
287 return;
288
289 const ProgramState *state = C.getState();
290 const ProgramState *trueState = NULL, *falseState = NULL;
291 const Expr *arg = CE->getArg(1);
292 SVal argVal = state->getSVal(arg);
293
294 if (argVal.isUnknownOrUndef())
295 return;
296
297 if (IsZeroByteAllocation(state, argVal, &trueState, &falseState)) {
298 ReportZeroByteAllocation(C, falseState, arg, "realloc");
299 return;
Ted Kremenekb12fbc22010-11-16 18:47:04 +0000300 }
Ted Kremenekc1275da2012-01-03 23:43:13 +0000301
302 // Assume the the value is non-zero going forward.
303 assert(trueState);
304 if (trueState != state)
305 C.addTransition(trueState);
Ted Kremenekb12fbc22010-11-16 18:47:04 +0000306}
307
308//===----------------------------------------------------------------------===//
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000309// Central dispatch function.
310//===----------------------------------------------------------------------===//
311
Argyrios Kyrtzidis983326f2011-02-23 01:05:36 +0000312void UnixAPIChecker::checkPreStmt(const CallExpr *CE, CheckerContext &C) const {
Anna Zaksb805c8f2011-12-01 05:57:37 +0000313 StringRef FName = C.getCalleeName(CE);
314 if (FName.empty())
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000315 return;
316
Jordy Roseaf5b0432011-07-15 06:28:59 +0000317 SubChecker SC =
Anna Zaksb805c8f2011-12-01 05:57:37 +0000318 llvm::StringSwitch<SubChecker>(FName)
Jordy Roseaf5b0432011-07-15 06:28:59 +0000319 .Case("open", &UnixAPIChecker::CheckOpen)
320 .Case("pthread_once", &UnixAPIChecker::CheckPthreadOnce)
Ted Kremenekc1275da2012-01-03 23:43:13 +0000321 .Case("calloc", &UnixAPIChecker::CheckCallocZero)
Jordy Roseaf5b0432011-07-15 06:28:59 +0000322 .Case("malloc", &UnixAPIChecker::CheckMallocZero)
Ted Kremenekc1275da2012-01-03 23:43:13 +0000323 .Case("realloc", &UnixAPIChecker::CheckReallocZero)
Jordy Roseaf5b0432011-07-15 06:28:59 +0000324 .Default(NULL);
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000325
Jordy Roseaf5b0432011-07-15 06:28:59 +0000326 if (SC)
327 (this->*SC)(C, CE);
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000328}
Argyrios Kyrtzidis983326f2011-02-23 01:05:36 +0000329
330//===----------------------------------------------------------------------===//
331// Registration.
332//===----------------------------------------------------------------------===//
333
334void ento::registerUnixAPIChecker(CheckerManager &mgr) {
335 mgr.registerChecker<UnixAPIChecker>();
336}