blob: 46ae858a08d3434154cf12d02a7e9beb6689a7eb [file] [log] [blame]
Ted Kremenekd55522f2010-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 Kyrtzidisa6d04d52011-02-15 07:42:33 +000015#include "ClangSACheckers.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000016#include "clang/Basic/TargetInfo.h"
17#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
Argyrios Kyrtzidis6a5674f2011-03-01 01:16:21 +000018#include "clang/StaticAnalyzer/Core/Checker.h"
Argyrios Kyrtzidis507ff532011-02-17 21:39:17 +000019#include "clang/StaticAnalyzer/Core/CheckerManager.h"
Argyrios Kyrtzidisdff865d2011-02-23 01:05:36 +000020#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
Ted Kremenek26984fb2010-04-09 20:26:58 +000021#include "llvm/ADT/Optional.h"
Benjamin Kramer3307c5082012-02-04 12:31:12 +000022#include "llvm/ADT/STLExtras.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000023#include "llvm/ADT/SmallString.h"
Benjamin Kramerc0483222010-03-27 21:19:47 +000024#include "llvm/ADT/StringSwitch.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000025#include "llvm/Support/raw_ostream.h"
Ted Kremenekd55522f2010-02-25 00:20:35 +000026#include <fcntl.h>
27
28using namespace clang;
Ted Kremenek98857c92010-12-23 07:20:52 +000029using namespace ento;
Ted Kremenekd55522f2010-02-25 00:20:35 +000030
31namespace {
Argyrios Kyrtzidis6a5674f2011-03-01 01:16:21 +000032class UnixAPIChecker : public Checker< check::PreStmt<CallExpr> > {
Dylan Noblesmithe2778992012-02-05 02:12:40 +000033 mutable OwningPtr<BugType> BT_open, BT_pthreadOnce, BT_mallocZero;
Argyrios Kyrtzidisdff865d2011-02-23 01:05:36 +000034 mutable Optional<uint64_t> Val_O_CREAT;
Ted Kremenek212182d2010-04-08 22:15:34 +000035
36public:
Argyrios Kyrtzidisdff865d2011-02-23 01:05:36 +000037 void checkPreStmt(const CallExpr *CE, CheckerContext &C) const;
Jordy Rosef3dd00a2011-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 Kremenek134a83a2012-01-03 23:43:13 +000041 void CheckCallocZero(CheckerContext &C, const CallExpr *CE) const;
Jordy Rosef3dd00a2011-07-15 06:28:59 +000042 void CheckMallocZero(CheckerContext &C, const CallExpr *CE) const;
Ted Kremenek134a83a2012-01-03 23:43:13 +000043 void CheckReallocZero(CheckerContext &C, const CallExpr *CE) const;
Jordan Rose9e068aa2012-10-30 01:37:16 +000044 void CheckReallocfZero(CheckerContext &C, const CallExpr *CE) const;
Ted Kremenek940e00f2012-01-11 08:13:21 +000045 void CheckAllocaZero(CheckerContext &C, const CallExpr *CE) const;
46 void CheckVallocZero(CheckerContext &C, const CallExpr *CE) const;
Jordy Rosef3dd00a2011-07-15 06:28:59 +000047
48 typedef void (UnixAPIChecker::*SubChecker)(CheckerContext &,
49 const CallExpr *) const;
Ted Kremenek134a83a2012-01-03 23:43:13 +000050private:
51 bool ReportZeroByteAllocation(CheckerContext &C,
Ted Kremenek49b1e382012-01-26 21:29:00 +000052 ProgramStateRef falseState,
Ted Kremenek134a83a2012-01-03 23:43:13 +000053 const Expr *arg,
54 const char *fn_name) const;
Ted Kremenek940e00f2012-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;
Alexander Kornienko4aca9b12014-02-11 21:49:21 +000060 void LazyInitialize(OwningPtr<BugType> &BT, const char *name) const {
61 if (BT)
62 return;
63 BT.reset(new BugType(this, name, categories::UnixAPI));
64 }
Ted Kremenekd55522f2010-02-25 00:20:35 +000065};
66} //end anonymous namespace
67
Ted Kremenekd55522f2010-02-25 00:20:35 +000068//===----------------------------------------------------------------------===//
Ted Kremenekd55522f2010-02-25 00:20:35 +000069// "open" (man 2 open)
70//===----------------------------------------------------------------------===//
71
Jordy Rosef3dd00a2011-07-15 06:28:59 +000072void UnixAPIChecker::CheckOpen(CheckerContext &C, const CallExpr *CE) const {
Ted Kremenek212182d2010-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 Rosef3dd00a2011-07-15 06:28:59 +000075 if (!Val_O_CREAT.hasValue()) {
Douglas Gregore8bbc122011-09-02 00:18:52 +000076 if (C.getASTContext().getTargetInfo().getTriple().getVendor()
77 == llvm::Triple::Apple)
Jordy Rosef3dd00a2011-07-15 06:28:59 +000078 Val_O_CREAT = 0x0200;
Ted Kremenek212182d2010-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 Kyrtzidis1696f502010-12-22 18:53:44 +000082 // that would require passing the Preprocessor object to the ExprEngine.
Ted Kremenek212182d2010-04-08 22:15:34 +000083 return;
84 }
85 }
86
Ted Kremenekd55522f2010-02-25 00:20:35 +000087 // Look at the 'oflags' argument for the O_CREAT flag.
Ted Kremenek49b1e382012-01-26 21:29:00 +000088 ProgramStateRef state = C.getState();
Ted Kremenekd55522f2010-02-25 00:20:35 +000089
90 if (CE->getNumArgs() < 2) {
91 // The frontend should issue a warning for this case, so this is a sanity
92 // check.
93 return;
94 }
95
96 // Now check if oflags has O_CREAT set.
97 const Expr *oflagsEx = CE->getArg(1);
Ted Kremenek632e3b72012-01-06 22:09:28 +000098 const SVal V = state->getSVal(oflagsEx, C.getLocationContext());
David Blaikie2fdacbc2013-02-20 05:52:05 +000099 if (!V.getAs<NonLoc>()) {
Ted Kremenekd55522f2010-02-25 00:20:35 +0000100 // The case where 'V' can be a location can only be due to a bad header,
101 // so in this case bail out.
102 return;
103 }
David Blaikie2fdacbc2013-02-20 05:52:05 +0000104 NonLoc oflags = V.castAs<NonLoc>();
105 NonLoc ocreateFlag = C.getSValBuilder()
106 .makeIntVal(Val_O_CREAT.getValue(), oflagsEx->getType()).castAs<NonLoc>();
Ted Kremenekdc891422010-12-01 21:57:22 +0000107 SVal maskedFlagsUC = C.getSValBuilder().evalBinOpNN(state, BO_And,
Ted Kremenek9d0bb1e2010-12-01 21:28:31 +0000108 oflags, ocreateFlag,
109 oflagsEx->getType());
Ted Kremenekd55522f2010-02-25 00:20:35 +0000110 if (maskedFlagsUC.isUnknownOrUndef())
111 return;
David Blaikie2fdacbc2013-02-20 05:52:05 +0000112 DefinedSVal maskedFlags = maskedFlagsUC.castAs<DefinedSVal>();
Ted Kremenekd55522f2010-02-25 00:20:35 +0000113
114 // Check if maskedFlags is non-zero.
Ted Kremenek49b1e382012-01-26 21:29:00 +0000115 ProgramStateRef trueState, falseState;
Ted Kremenekc5bea1e2010-12-01 22:16:56 +0000116 llvm::tie(trueState, falseState) = state->assume(maskedFlags);
Ted Kremenekd55522f2010-02-25 00:20:35 +0000117
118 // Only emit an error if the value of 'maskedFlags' is properly
119 // constrained;
120 if (!(trueState && !falseState))
121 return;
122
123 if (CE->getNumArgs() < 3) {
Ted Kremenek750b7ac2010-12-20 21:19:09 +0000124 ExplodedNode *N = C.generateSink(trueState);
Ted Kremenek5563dea2010-02-25 05:44:05 +0000125 if (!N)
126 return;
127
Jordy Rosef3dd00a2011-07-15 06:28:59 +0000128 LazyInitialize(BT_open, "Improper use of 'open'");
129
Anna Zaks3a6bdf82011-08-17 23:00:25 +0000130 BugReport *report =
131 new BugReport(*BT_open,
Ted Kremenekd55522f2010-02-25 00:20:35 +0000132 "Call to 'open' requires a third argument when "
133 "the 'O_CREAT' flag is set", N);
134 report->addRange(oflagsEx->getSourceRange());
Jordan Rosee10d5a72012-11-02 01:53:40 +0000135 C.emitReport(report);
Ted Kremenekd55522f2010-02-25 00:20:35 +0000136 }
137}
138
139//===----------------------------------------------------------------------===//
Ted Kremenekea4a5ab2010-04-08 19:53:31 +0000140// pthread_once
141//===----------------------------------------------------------------------===//
142
Jordy Rosef3dd00a2011-07-15 06:28:59 +0000143void UnixAPIChecker::CheckPthreadOnce(CheckerContext &C,
144 const CallExpr *CE) const {
Ted Kremenekea4a5ab2010-04-08 19:53:31 +0000145
146 // This is similar to 'CheckDispatchOnce' in the MacOSXAPIChecker.
147 // They can possibly be refactored.
148
Ted Kremenekea4a5ab2010-04-08 19:53:31 +0000149 if (CE->getNumArgs() < 1)
150 return;
151
152 // Check if the first argument is stack allocated. If so, issue a warning
153 // because that's likely to be bad news.
Ted Kremenek49b1e382012-01-26 21:29:00 +0000154 ProgramStateRef state = C.getState();
Ted Kremenek632e3b72012-01-06 22:09:28 +0000155 const MemRegion *R =
156 state->getSVal(CE->getArg(0), C.getLocationContext()).getAsRegion();
Ted Kremenekea4a5ab2010-04-08 19:53:31 +0000157 if (!R || !isa<StackSpaceRegion>(R->getMemorySpace()))
158 return;
159
Ted Kremenek750b7ac2010-12-20 21:19:09 +0000160 ExplodedNode *N = C.generateSink(state);
Ted Kremenekea4a5ab2010-04-08 19:53:31 +0000161 if (!N)
162 return;
163
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000164 SmallString<256> S;
Ted Kremenekea4a5ab2010-04-08 19:53:31 +0000165 llvm::raw_svector_ostream os(S);
166 os << "Call to 'pthread_once' uses";
167 if (const VarRegion *VR = dyn_cast<VarRegion>(R))
168 os << " the local variable '" << VR->getDecl()->getName() << '\'';
169 else
170 os << " stack allocated memory";
171 os << " for the \"control\" value. Using such transient memory for "
172 "the control value is potentially dangerous.";
173 if (isa<VarRegion>(R) && isa<StackLocalsSpaceRegion>(R->getMemorySpace()))
174 os << " Perhaps you intended to declare the variable as 'static'?";
175
Jordy Rosef3dd00a2011-07-15 06:28:59 +0000176 LazyInitialize(BT_pthreadOnce, "Improper use of 'pthread_once'");
177
Anna Zaks3a6bdf82011-08-17 23:00:25 +0000178 BugReport *report = new BugReport(*BT_pthreadOnce, os.str(), N);
Ted Kremenekea4a5ab2010-04-08 19:53:31 +0000179 report->addRange(CE->getArg(0)->getSourceRange());
Jordan Rosee10d5a72012-11-02 01:53:40 +0000180 C.emitReport(report);
Ted Kremenekea4a5ab2010-04-08 19:53:31 +0000181}
182
183//===----------------------------------------------------------------------===//
Jordan Rose9e068aa2012-10-30 01:37:16 +0000184// "calloc", "malloc", "realloc", "reallocf", "alloca" and "valloc"
185// with allocation size 0
Ted Kremenek0c27bcf2010-11-16 18:47:04 +0000186//===----------------------------------------------------------------------===//
Ted Kremenek940e00f2012-01-11 08:13:21 +0000187// FIXME: Eventually these should be rolled into the MallocChecker, but right now
188// they're more basic and valuable for widespread use.
Ted Kremenek0c27bcf2010-11-16 18:47:04 +0000189
Ted Kremenek134a83a2012-01-03 23:43:13 +0000190// Returns true if we try to do a zero byte allocation, false otherwise.
191// Fills in trueState and falseState.
Ted Kremenek49b1e382012-01-26 21:29:00 +0000192static bool IsZeroByteAllocation(ProgramStateRef state,
Ted Kremenek134a83a2012-01-03 23:43:13 +0000193 const SVal argVal,
Ted Kremenek49b1e382012-01-26 21:29:00 +0000194 ProgramStateRef *trueState,
195 ProgramStateRef *falseState) {
Ted Kremenek940e00f2012-01-11 08:13:21 +0000196 llvm::tie(*trueState, *falseState) =
David Blaikie2fdacbc2013-02-20 05:52:05 +0000197 state->assume(argVal.castAs<DefinedSVal>());
Ted Kremenek940e00f2012-01-11 08:13:21 +0000198
Ted Kremenek134a83a2012-01-03 23:43:13 +0000199 return (*falseState && !*trueState);
200}
201
202// Generates an error report, indicating that the function whose name is given
203// will perform a zero byte allocation.
Alp Tokerf6a24ce2013-12-05 16:25:25 +0000204// Returns false if an error occurred, true otherwise.
Ted Kremenek134a83a2012-01-03 23:43:13 +0000205bool UnixAPIChecker::ReportZeroByteAllocation(CheckerContext &C,
Ted Kremenek49b1e382012-01-26 21:29:00 +0000206 ProgramStateRef falseState,
Ted Kremenek134a83a2012-01-03 23:43:13 +0000207 const Expr *arg,
208 const char *fn_name) const {
209 ExplodedNode *N = C.generateSink(falseState);
210 if (!N)
211 return false;
212
Ted Kremenek940e00f2012-01-11 08:13:21 +0000213 LazyInitialize(BT_mallocZero,
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000214 "Undefined allocation of 0 bytes (CERT MEM04-C; CWE-131)");
Ted Kremenek134a83a2012-01-03 23:43:13 +0000215
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000216 SmallString<256> S;
Ted Kremenek134a83a2012-01-03 23:43:13 +0000217 llvm::raw_svector_ostream os(S);
218 os << "Call to '" << fn_name << "' has an allocation size of 0 bytes";
219 BugReport *report = new BugReport(*BT_mallocZero, os.str(), N);
220
221 report->addRange(arg->getSourceRange());
Jordan Rosea0f7d352012-08-28 00:50:51 +0000222 bugreporter::trackNullOrUndefValue(N, arg, *report);
Jordan Rosee10d5a72012-11-02 01:53:40 +0000223 C.emitReport(report);
Ted Kremenek134a83a2012-01-03 23:43:13 +0000224
225 return true;
226}
227
Ted Kremenek940e00f2012-01-11 08:13:21 +0000228// Does a basic check for 0-sized allocations suitable for most of the below
229// functions (modulo "calloc")
230void UnixAPIChecker::BasicAllocationCheck(CheckerContext &C,
231 const CallExpr *CE,
232 const unsigned numArgs,
233 const unsigned sizeArg,
234 const char *fn) const {
235 // Sanity check for the correct number of arguments
236 if (CE->getNumArgs() != numArgs)
237 return;
238
239 // Check if the allocation size is 0.
Ted Kremenek49b1e382012-01-26 21:29:00 +0000240 ProgramStateRef state = C.getState();
241 ProgramStateRef trueState = NULL, falseState = NULL;
Ted Kremenek940e00f2012-01-11 08:13:21 +0000242 const Expr *arg = CE->getArg(sizeArg);
243 SVal argVal = state->getSVal(arg, C.getLocationContext());
244
245 if (argVal.isUnknownOrUndef())
246 return;
247
248 // Is the value perfectly constrained to zero?
249 if (IsZeroByteAllocation(state, argVal, &trueState, &falseState)) {
250 (void) ReportZeroByteAllocation(C, falseState, arg, fn);
251 return;
252 }
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000253 // Assume the value is non-zero going forward.
Ted Kremenek940e00f2012-01-11 08:13:21 +0000254 assert(trueState);
255 if (trueState != state)
256 C.addTransition(trueState);
257}
258
Ted Kremenek134a83a2012-01-03 23:43:13 +0000259void UnixAPIChecker::CheckCallocZero(CheckerContext &C,
260 const CallExpr *CE) const {
261 unsigned int nArgs = CE->getNumArgs();
262 if (nArgs != 2)
263 return;
264
Ted Kremenek49b1e382012-01-26 21:29:00 +0000265 ProgramStateRef state = C.getState();
266 ProgramStateRef trueState = NULL, falseState = NULL;
Ted Kremenek134a83a2012-01-03 23:43:13 +0000267
268 unsigned int i;
269 for (i = 0; i < nArgs; i++) {
270 const Expr *arg = CE->getArg(i);
Ted Kremenek632e3b72012-01-06 22:09:28 +0000271 SVal argVal = state->getSVal(arg, C.getLocationContext());
Ted Kremenek134a83a2012-01-03 23:43:13 +0000272 if (argVal.isUnknownOrUndef()) {
273 if (i == 0)
274 continue;
275 else
276 return;
277 }
278
279 if (IsZeroByteAllocation(state, argVal, &trueState, &falseState)) {
280 if (ReportZeroByteAllocation(C, falseState, arg, "calloc"))
281 return;
282 else if (i == 0)
283 continue;
284 else
285 return;
286 }
287 }
288
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000289 // Assume the value is non-zero going forward.
Ted Kremenek134a83a2012-01-03 23:43:13 +0000290 assert(trueState);
291 if (trueState != state)
292 C.addTransition(trueState);
293}
294
Jordy Rosef3dd00a2011-07-15 06:28:59 +0000295void UnixAPIChecker::CheckMallocZero(CheckerContext &C,
296 const CallExpr *CE) const {
Ted Kremenek940e00f2012-01-11 08:13:21 +0000297 BasicAllocationCheck(C, CE, 1, 0, "malloc");
Ted Kremenek134a83a2012-01-03 23:43:13 +0000298}
299
300void UnixAPIChecker::CheckReallocZero(CheckerContext &C,
301 const CallExpr *CE) const {
Ted Kremenek940e00f2012-01-11 08:13:21 +0000302 BasicAllocationCheck(C, CE, 2, 1, "realloc");
Ted Kremenek0c27bcf2010-11-16 18:47:04 +0000303}
Ted Kremenek940e00f2012-01-11 08:13:21 +0000304
Jordan Rose9e068aa2012-10-30 01:37:16 +0000305void UnixAPIChecker::CheckReallocfZero(CheckerContext &C,
306 const CallExpr *CE) const {
307 BasicAllocationCheck(C, CE, 2, 1, "reallocf");
308}
309
Ted Kremenek940e00f2012-01-11 08:13:21 +0000310void UnixAPIChecker::CheckAllocaZero(CheckerContext &C,
311 const CallExpr *CE) const {
312 BasicAllocationCheck(C, CE, 1, 0, "alloca");
313}
314
315void UnixAPIChecker::CheckVallocZero(CheckerContext &C,
316 const CallExpr *CE) const {
317 BasicAllocationCheck(C, CE, 1, 0, "valloc");
318}
319
320
Ted Kremenek0c27bcf2010-11-16 18:47:04 +0000321//===----------------------------------------------------------------------===//
Ted Kremenekd55522f2010-02-25 00:20:35 +0000322// Central dispatch function.
323//===----------------------------------------------------------------------===//
324
Ted Kremenek940e00f2012-01-11 08:13:21 +0000325void UnixAPIChecker::checkPreStmt(const CallExpr *CE,
326 CheckerContext &C) const {
Jordan Rose6cd16c52012-07-10 23:13:01 +0000327 const FunctionDecl *FD = C.getCalleeDecl(CE);
328 if (!FD || FD->getKind() != Decl::Function)
329 return;
330
331 StringRef FName = C.getCalleeName(FD);
Anna Zaksc6aa5312011-12-01 05:57:37 +0000332 if (FName.empty())
Ted Kremenekd55522f2010-02-25 00:20:35 +0000333 return;
334
Jordy Rosef3dd00a2011-07-15 06:28:59 +0000335 SubChecker SC =
Anna Zaksc6aa5312011-12-01 05:57:37 +0000336 llvm::StringSwitch<SubChecker>(FName)
Jordy Rosef3dd00a2011-07-15 06:28:59 +0000337 .Case("open", &UnixAPIChecker::CheckOpen)
338 .Case("pthread_once", &UnixAPIChecker::CheckPthreadOnce)
Ted Kremenek134a83a2012-01-03 23:43:13 +0000339 .Case("calloc", &UnixAPIChecker::CheckCallocZero)
Jordy Rosef3dd00a2011-07-15 06:28:59 +0000340 .Case("malloc", &UnixAPIChecker::CheckMallocZero)
Ted Kremenek134a83a2012-01-03 23:43:13 +0000341 .Case("realloc", &UnixAPIChecker::CheckReallocZero)
Jordan Rose9e068aa2012-10-30 01:37:16 +0000342 .Case("reallocf", &UnixAPIChecker::CheckReallocfZero)
Ted Kremenek940e00f2012-01-11 08:13:21 +0000343 .Cases("alloca", "__builtin_alloca", &UnixAPIChecker::CheckAllocaZero)
344 .Case("valloc", &UnixAPIChecker::CheckVallocZero)
Jordy Rosef3dd00a2011-07-15 06:28:59 +0000345 .Default(NULL);
Ted Kremenekd55522f2010-02-25 00:20:35 +0000346
Jordy Rosef3dd00a2011-07-15 06:28:59 +0000347 if (SC)
348 (this->*SC)(C, CE);
Ted Kremenekd55522f2010-02-25 00:20:35 +0000349}
Argyrios Kyrtzidisdff865d2011-02-23 01:05:36 +0000350
351//===----------------------------------------------------------------------===//
352// Registration.
353//===----------------------------------------------------------------------===//
354
355void ento::registerUnixAPIChecker(CheckerManager &mgr) {
356 mgr.registerChecker<UnixAPIChecker>();
357}