blob: 48d7c367a96db22d473b94618ff34b1aa7bfd765 [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> > {
Ted Kremenek381d1bf2010-02-25 00:20:35 +000031 enum SubChecks {
32 OpenFn = 0,
Ted Kremenek99d98382010-04-08 19:53:31 +000033 PthreadOnceFn = 1,
Ted Kremenekb12fbc22010-11-16 18:47:04 +000034 MallocZero = 2,
Ted Kremenek381d1bf2010-02-25 00:20:35 +000035 NumChecks
36 };
37
Argyrios Kyrtzidis983326f2011-02-23 01:05:36 +000038 mutable BugType *BTypes[NumChecks];
Ted Kremenek381d1bf2010-02-25 00:20:35 +000039
40public:
Argyrios Kyrtzidis983326f2011-02-23 01:05:36 +000041 mutable Optional<uint64_t> Val_O_CREAT;
Ted Kremenekbace4ba2010-04-08 22:15:34 +000042
43public:
Ted Kremenek381d1bf2010-02-25 00:20:35 +000044 UnixAPIChecker() { memset(BTypes, 0, sizeof(*BTypes) * NumChecks); }
Argyrios Kyrtzidis983326f2011-02-23 01:05:36 +000045 ~UnixAPIChecker() {
46 for (unsigned i=0; i != NumChecks; ++i)
47 delete BTypes[i];
48 }
Ted Kremenek381d1bf2010-02-25 00:20:35 +000049
Argyrios Kyrtzidis983326f2011-02-23 01:05:36 +000050 void checkPreStmt(const CallExpr *CE, CheckerContext &C) const;
Ted Kremenek381d1bf2010-02-25 00:20:35 +000051};
52} //end anonymous namespace
53
Ted Kremenek381d1bf2010-02-25 00:20:35 +000054//===----------------------------------------------------------------------===//
55// Utility functions.
56//===----------------------------------------------------------------------===//
57
58static inline void LazyInitialize(BugType *&BT, const char *name) {
59 if (BT)
60 return;
61 BT = new BugType(name, "Unix API");
62}
63
64//===----------------------------------------------------------------------===//
65// "open" (man 2 open)
66//===----------------------------------------------------------------------===//
67
Argyrios Kyrtzidis983326f2011-02-23 01:05:36 +000068static void CheckOpen(CheckerContext &C, const UnixAPIChecker &UC,
Ted Kremenekbace4ba2010-04-08 22:15:34 +000069 const CallExpr *CE, BugType *&BT) {
70 // The definition of O_CREAT is platform specific. We need a better way
71 // of querying this information from the checking environment.
72 if (!UC.Val_O_CREAT.hasValue()) {
73 if (C.getASTContext().Target.getTriple().getVendor() == llvm::Triple::Apple)
74 UC.Val_O_CREAT = 0x0200;
75 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 LazyInitialize(BT, "Improper use of 'open'");
84
85 // Look at the 'oflags' argument for the O_CREAT flag.
86 const GRState *state = C.getState();
87
88 if (CE->getNumArgs() < 2) {
89 // The frontend should issue a warning for this case, so this is a sanity
90 // check.
91 return;
92 }
93
94 // Now check if oflags has O_CREAT set.
95 const Expr *oflagsEx = CE->getArg(1);
96 const SVal V = state->getSVal(oflagsEx);
97 if (!isa<NonLoc>(V)) {
98 // The case where 'V' can be a location can only be due to a bad header,
99 // so in this case bail out.
100 return;
101 }
102 NonLoc oflags = cast<NonLoc>(V);
103 NonLoc ocreateFlag =
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000104 cast<NonLoc>(C.getSValBuilder().makeIntVal(UC.Val_O_CREAT.getValue(),
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000105 oflagsEx->getType()));
Ted Kremenek9c149532010-12-01 21:57:22 +0000106 SVal maskedFlagsUC = C.getSValBuilder().evalBinOpNN(state, BO_And,
Ted Kremenek846eabd2010-12-01 21:28:31 +0000107 oflags, ocreateFlag,
108 oflagsEx->getType());
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000109 if (maskedFlagsUC.isUnknownOrUndef())
110 return;
111 DefinedSVal maskedFlags = cast<DefinedSVal>(maskedFlagsUC);
112
113 // Check if maskedFlags is non-zero.
114 const GRState *trueState, *falseState;
Ted Kremenek28f47b92010-12-01 22:16:56 +0000115 llvm::tie(trueState, falseState) = state->assume(maskedFlags);
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000116
117 // Only emit an error if the value of 'maskedFlags' is properly
118 // constrained;
119 if (!(trueState && !falseState))
120 return;
121
122 if (CE->getNumArgs() < 3) {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000123 ExplodedNode *N = C.generateSink(trueState);
Ted Kremenekc757d792010-02-25 05:44:05 +0000124 if (!N)
125 return;
126
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000127 EnhancedBugReport *report =
128 new EnhancedBugReport(*BT,
129 "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
Argyrios Kyrtzidis983326f2011-02-23 01:05:36 +0000140static void CheckPthreadOnce(CheckerContext &C, const UnixAPIChecker &,
Ted Kremenekbace4ba2010-04-08 22:15:34 +0000141 const CallExpr *CE, BugType *&BT) {
Ted Kremenek99d98382010-04-08 19:53:31 +0000142
143 // This is similar to 'CheckDispatchOnce' in the MacOSXAPIChecker.
144 // They can possibly be refactored.
145
146 LazyInitialize(BT, "Improper use of 'pthread_once'");
147
148 if (CE->getNumArgs() < 1)
149 return;
150
151 // Check if the first argument is stack allocated. If so, issue a warning
152 // because that's likely to be bad news.
153 const GRState *state = C.getState();
154 const MemRegion *R = state->getSVal(CE->getArg(0)).getAsRegion();
155 if (!R || !isa<StackSpaceRegion>(R->getMemorySpace()))
156 return;
157
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000158 ExplodedNode *N = C.generateSink(state);
Ted Kremenek99d98382010-04-08 19:53:31 +0000159 if (!N)
160 return;
161
162 llvm::SmallString<256> S;
163 llvm::raw_svector_ostream os(S);
164 os << "Call to 'pthread_once' uses";
165 if (const VarRegion *VR = dyn_cast<VarRegion>(R))
166 os << " the local variable '" << VR->getDecl()->getName() << '\'';
167 else
168 os << " stack allocated memory";
169 os << " for the \"control\" value. Using such transient memory for "
170 "the control value is potentially dangerous.";
171 if (isa<VarRegion>(R) && isa<StackLocalsSpaceRegion>(R->getMemorySpace()))
172 os << " Perhaps you intended to declare the variable as 'static'?";
173
174 EnhancedBugReport *report = new EnhancedBugReport(*BT, os.str(), N);
175 report->addRange(CE->getArg(0)->getSourceRange());
176 C.EmitReport(report);
177}
178
179//===----------------------------------------------------------------------===//
Ted Kremenekb12fbc22010-11-16 18:47:04 +0000180// "malloc" with allocation size 0
181//===----------------------------------------------------------------------===//
182
183// FIXME: Eventually this should be rolled into the MallocChecker, but this
184// check is more basic and is valuable for widespread use.
Argyrios Kyrtzidis983326f2011-02-23 01:05:36 +0000185static void CheckMallocZero(CheckerContext &C, const UnixAPIChecker &UC,
Ted Kremenekb12fbc22010-11-16 18:47:04 +0000186 const CallExpr *CE, BugType *&BT) {
187
188 // Sanity check that malloc takes one argument.
189 if (CE->getNumArgs() != 1)
190 return;
191
192 // Check if the allocation size is 0.
193 const GRState *state = C.getState();
194 SVal argVal = state->getSVal(CE->getArg(0));
195
196 if (argVal.isUnknownOrUndef())
197 return;
198
199 const GRState *trueState, *falseState;
Ted Kremenek28f47b92010-12-01 22:16:56 +0000200 llvm::tie(trueState, falseState) = state->assume(cast<DefinedSVal>(argVal));
Ted Kremenekb12fbc22010-11-16 18:47:04 +0000201
202 // Is the value perfectly constrained to zero?
203 if (falseState && !trueState) {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000204 ExplodedNode *N = C.generateSink(falseState);
Ted Kremenekb12fbc22010-11-16 18:47:04 +0000205 if (!N)
206 return;
207
Ted Kremenek8fec9722010-11-17 00:50:34 +0000208 // FIXME: Add reference to CERT advisory, and/or C99 standard in bug
209 // output.
210
211 LazyInitialize(BT, "Undefined allocation of 0 bytes");
Ted Kremenekb12fbc22010-11-16 18:47:04 +0000212
213 EnhancedBugReport *report =
214 new EnhancedBugReport(*BT, "Call to 'malloc' has an allocation size"
215 " of 0 bytes", N);
216 report->addRange(CE->getArg(0)->getSourceRange());
217 report->addVisitorCreator(bugreporter::registerTrackNullOrUndefValue,
218 CE->getArg(0));
219 C.EmitReport(report);
220 return;
221 }
222 // Assume the the value is non-zero going forward.
223 assert(trueState);
224 if (trueState != state) {
225 C.addTransition(trueState);
226 }
227}
228
229//===----------------------------------------------------------------------===//
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000230// Central dispatch function.
231//===----------------------------------------------------------------------===//
232
Argyrios Kyrtzidis983326f2011-02-23 01:05:36 +0000233typedef void (*SubChecker)(CheckerContext &C, const UnixAPIChecker &UC,
Ted Kremenekbace4ba2010-04-08 22:15:34 +0000234 const CallExpr *CE, BugType *&BT);
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000235namespace {
236 class SubCheck {
237 SubChecker SC;
Argyrios Kyrtzidis983326f2011-02-23 01:05:36 +0000238 const UnixAPIChecker *UC;
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000239 BugType **BT;
240 public:
Argyrios Kyrtzidis983326f2011-02-23 01:05:36 +0000241 SubCheck(SubChecker sc, const UnixAPIChecker *uc, BugType *& bt)
242 : SC(sc), UC(uc), BT(&bt) {}
Ted Kremenekbace4ba2010-04-08 22:15:34 +0000243 SubCheck() : SC(NULL), UC(NULL), BT(NULL) {}
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000244
245 void run(CheckerContext &C, const CallExpr *CE) const {
246 if (SC)
Ted Kremenekbace4ba2010-04-08 22:15:34 +0000247 SC(C, *UC, CE, *BT);
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000248 }
249 };
250} // end anonymous namespace
251
Argyrios Kyrtzidis983326f2011-02-23 01:05:36 +0000252void UnixAPIChecker::checkPreStmt(const CallExpr *CE, CheckerContext &C) const {
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000253 // Get the callee. All the functions we care about are C functions
254 // with simple identifiers.
255 const GRState *state = C.getState();
256 const Expr *Callee = CE->getCallee();
257 const FunctionTextRegion *Fn =
258 dyn_cast_or_null<FunctionTextRegion>(state->getSVal(Callee).getAsRegion());
259
260 if (!Fn)
261 return;
262
263 const IdentifierInfo *FI = Fn->getDecl()->getIdentifier();
264 if (!FI)
265 return;
266
267 const SubCheck &SC =
268 llvm::StringSwitch<SubCheck>(FI->getName())
Ted Kremenekb12fbc22010-11-16 18:47:04 +0000269 .Case("open",
270 SubCheck(CheckOpen, this, BTypes[OpenFn]))
271 .Case("pthread_once",
272 SubCheck(CheckPthreadOnce, this, BTypes[PthreadOnceFn]))
273 .Case("malloc",
274 SubCheck(CheckMallocZero, this, BTypes[MallocZero]))
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000275 .Default(SubCheck());
276
277 SC.run(C, CE);
278}
Argyrios Kyrtzidis983326f2011-02-23 01:05:36 +0000279
280//===----------------------------------------------------------------------===//
281// Registration.
282//===----------------------------------------------------------------------===//
283
284void ento::registerUnixAPIChecker(CheckerManager &mgr) {
285 mgr.registerChecker<UnixAPIChecker>();
286}