blob: 93d1de24d24189491e2080a24aef9ad522e18a60 [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
Ted Kremenek381d1bf2010-02-25 00:20:35 +000015#include "GRExprEngineInternalChecks.h"
Ted Kremenekbace4ba2010-04-08 22:15:34 +000016#include "clang/Basic/TargetInfo.h"
17#include "clang/Checker/BugReporter/BugType.h"
18#include "clang/Checker/PathSensitive/CheckerVisitor.h"
Ted Kremenek66d51422010-04-09 20:26:58 +000019#include "llvm/ADT/Optional.h"
Benjamin Kramer5e2d2c22010-03-27 21:19:47 +000020#include "llvm/ADT/StringSwitch.h"
Ted Kremenek381d1bf2010-02-25 00:20:35 +000021#include <fcntl.h>
22
23using namespace clang;
Ted Kremenek66d51422010-04-09 20:26:58 +000024using llvm::Optional;
Ted Kremenek381d1bf2010-02-25 00:20:35 +000025
26namespace {
27class UnixAPIChecker : public CheckerVisitor<UnixAPIChecker> {
28 enum SubChecks {
29 OpenFn = 0,
Ted Kremenek99d98382010-04-08 19:53:31 +000030 PthreadOnceFn = 1,
Ted Kremenekb12fbc22010-11-16 18:47:04 +000031 MallocZero = 2,
Ted Kremenek381d1bf2010-02-25 00:20:35 +000032 NumChecks
33 };
34
35 BugType *BTypes[NumChecks];
36
37public:
Ted Kremenekbace4ba2010-04-08 22:15:34 +000038 Optional<uint64_t> Val_O_CREAT;
39
40public:
Ted Kremenek381d1bf2010-02-25 00:20:35 +000041 UnixAPIChecker() { memset(BTypes, 0, sizeof(*BTypes) * NumChecks); }
42 static void *getTag() { static unsigned tag = 0; return &tag; }
43
44 void PreVisitCallExpr(CheckerContext &C, const CallExpr *CE);
45};
46} //end anonymous namespace
47
48void clang::RegisterUnixAPIChecker(GRExprEngine &Eng) {
49 Eng.registerCheck(new UnixAPIChecker());
50}
51
52//===----------------------------------------------------------------------===//
53// Utility functions.
54//===----------------------------------------------------------------------===//
55
56static inline void LazyInitialize(BugType *&BT, const char *name) {
57 if (BT)
58 return;
59 BT = new BugType(name, "Unix API");
60}
61
62//===----------------------------------------------------------------------===//
63// "open" (man 2 open)
64//===----------------------------------------------------------------------===//
65
Ted Kremenekbace4ba2010-04-08 22:15:34 +000066static void CheckOpen(CheckerContext &C, UnixAPIChecker &UC,
67 const CallExpr *CE, BugType *&BT) {
68 // The definition of O_CREAT is platform specific. We need a better way
69 // of querying this information from the checking environment.
70 if (!UC.Val_O_CREAT.hasValue()) {
71 if (C.getASTContext().Target.getTriple().getVendor() == llvm::Triple::Apple)
72 UC.Val_O_CREAT = 0x0200;
73 else {
74 // FIXME: We need a more general way of getting the O_CREAT value.
75 // We could possibly grovel through the preprocessor state, but
76 // that would require passing the Preprocessor object to the GRExprEngine.
77 return;
78 }
79 }
80
Ted Kremenek381d1bf2010-02-25 00:20:35 +000081 LazyInitialize(BT, "Improper use of 'open'");
82
83 // Look at the 'oflags' argument for the O_CREAT flag.
84 const GRState *state = C.getState();
85
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 =
Ted Kremenekbace4ba2010-04-08 22:15:34 +0000102 cast<NonLoc>(C.getValueManager().makeIntVal(UC.Val_O_CREAT.getValue(),
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000103 oflagsEx->getType()));
Ted Kremenek846eabd2010-12-01 21:28:31 +0000104 SVal maskedFlagsUC = C.getSValBuilder().EvalBinOpNN(state, BO_And,
105 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.
112 const GRState *trueState, *falseState;
113 llvm::tie(trueState, falseState) = state->Assume(maskedFlags);
114
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) {
121 ExplodedNode *N = C.GenerateSink(trueState);
Ted Kremenekc757d792010-02-25 05:44:05 +0000122 if (!N)
123 return;
124
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000125 EnhancedBugReport *report =
126 new EnhancedBugReport(*BT,
127 "Call to 'open' requires a third argument when "
128 "the 'O_CREAT' flag is set", N);
129 report->addRange(oflagsEx->getSourceRange());
130 C.EmitReport(report);
131 }
132}
133
134//===----------------------------------------------------------------------===//
Ted Kremenek99d98382010-04-08 19:53:31 +0000135// pthread_once
136//===----------------------------------------------------------------------===//
137
Ted Kremenekbace4ba2010-04-08 22:15:34 +0000138static void CheckPthreadOnce(CheckerContext &C, UnixAPIChecker &,
139 const CallExpr *CE, BugType *&BT) {
Ted Kremenek99d98382010-04-08 19:53:31 +0000140
141 // This is similar to 'CheckDispatchOnce' in the MacOSXAPIChecker.
142 // They can possibly be refactored.
143
144 LazyInitialize(BT, "Improper use of 'pthread_once'");
145
146 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.
151 const GRState *state = C.getState();
152 const MemRegion *R = state->getSVal(CE->getArg(0)).getAsRegion();
153 if (!R || !isa<StackSpaceRegion>(R->getMemorySpace()))
154 return;
155
156 ExplodedNode *N = C.GenerateSink(state);
157 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
172 EnhancedBugReport *report = new EnhancedBugReport(*BT, os.str(), N);
173 report->addRange(CE->getArg(0)->getSourceRange());
174 C.EmitReport(report);
175}
176
177//===----------------------------------------------------------------------===//
Ted Kremenekb12fbc22010-11-16 18:47:04 +0000178// "malloc" with allocation size 0
179//===----------------------------------------------------------------------===//
180
181// FIXME: Eventually this should be rolled into the MallocChecker, but this
182// check is more basic and is valuable for widespread use.
183static void CheckMallocZero(CheckerContext &C, UnixAPIChecker &UC,
184 const CallExpr *CE, BugType *&BT) {
185
186 // Sanity check that malloc takes one argument.
187 if (CE->getNumArgs() != 1)
188 return;
189
190 // Check if the allocation size is 0.
191 const GRState *state = C.getState();
192 SVal argVal = state->getSVal(CE->getArg(0));
193
194 if (argVal.isUnknownOrUndef())
195 return;
196
197 const GRState *trueState, *falseState;
198 llvm::tie(trueState, falseState) = state->Assume(cast<DefinedSVal>(argVal));
199
200 // Is the value perfectly constrained to zero?
201 if (falseState && !trueState) {
202 ExplodedNode *N = C.GenerateSink(falseState);
203 if (!N)
204 return;
205
Ted Kremenek8fec9722010-11-17 00:50:34 +0000206 // FIXME: Add reference to CERT advisory, and/or C99 standard in bug
207 // output.
208
209 LazyInitialize(BT, "Undefined allocation of 0 bytes");
Ted Kremenekb12fbc22010-11-16 18:47:04 +0000210
211 EnhancedBugReport *report =
212 new EnhancedBugReport(*BT, "Call to 'malloc' has an allocation size"
213 " of 0 bytes", N);
214 report->addRange(CE->getArg(0)->getSourceRange());
215 report->addVisitorCreator(bugreporter::registerTrackNullOrUndefValue,
216 CE->getArg(0));
217 C.EmitReport(report);
218 return;
219 }
220 // Assume the the value is non-zero going forward.
221 assert(trueState);
222 if (trueState != state) {
223 C.addTransition(trueState);
224 }
225}
226
227//===----------------------------------------------------------------------===//
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000228// Central dispatch function.
229//===----------------------------------------------------------------------===//
230
Ted Kremenekbace4ba2010-04-08 22:15:34 +0000231typedef void (*SubChecker)(CheckerContext &C, UnixAPIChecker &UC,
232 const CallExpr *CE, BugType *&BT);
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000233namespace {
234 class SubCheck {
235 SubChecker SC;
Ted Kremenekbace4ba2010-04-08 22:15:34 +0000236 UnixAPIChecker *UC;
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000237 BugType **BT;
238 public:
Ted Kremenekbace4ba2010-04-08 22:15:34 +0000239 SubCheck(SubChecker sc, UnixAPIChecker *uc, BugType *& bt) : SC(sc), UC(uc),
240 BT(&bt) {}
241 SubCheck() : SC(NULL), UC(NULL), BT(NULL) {}
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000242
243 void run(CheckerContext &C, const CallExpr *CE) const {
244 if (SC)
Ted Kremenekbace4ba2010-04-08 22:15:34 +0000245 SC(C, *UC, CE, *BT);
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000246 }
247 };
248} // end anonymous namespace
249
250void UnixAPIChecker::PreVisitCallExpr(CheckerContext &C, const CallExpr *CE) {
251 // Get the callee. All the functions we care about are C functions
252 // with simple identifiers.
253 const GRState *state = C.getState();
254 const Expr *Callee = CE->getCallee();
255 const FunctionTextRegion *Fn =
256 dyn_cast_or_null<FunctionTextRegion>(state->getSVal(Callee).getAsRegion());
257
258 if (!Fn)
259 return;
260
261 const IdentifierInfo *FI = Fn->getDecl()->getIdentifier();
262 if (!FI)
263 return;
264
265 const SubCheck &SC =
266 llvm::StringSwitch<SubCheck>(FI->getName())
Ted Kremenekb12fbc22010-11-16 18:47:04 +0000267 .Case("open",
268 SubCheck(CheckOpen, this, BTypes[OpenFn]))
269 .Case("pthread_once",
270 SubCheck(CheckPthreadOnce, this, BTypes[PthreadOnceFn]))
271 .Case("malloc",
272 SubCheck(CheckMallocZero, this, BTypes[MallocZero]))
Ted Kremenek381d1bf2010-02-25 00:20:35 +0000273 .Default(SubCheck());
274
275 SC.run(C, CE);
276}