1 //= 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
15 #include "ClangSACheckers.h"
16 #include "clang/Basic/TargetInfo.h"
17 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
18 #include "clang/StaticAnalyzer/Core/Checker.h"
19 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
20 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
21 #include "llvm/ADT/Optional.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/SmallString.h"
24 #include "llvm/ADT/StringSwitch.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include <fcntl.h>
27
28 using namespace clang;
29 using namespace ento;
30
31 namespace {
32 class UnixAPIChecker : public Checker< check::PreStmt<CallExpr> > {
33 mutable std::unique_ptr<BugType> BT_open, BT_pthreadOnce, BT_mallocZero;
34 mutable Optional<uint64_t> Val_O_CREAT;
35
36 public:
37 void checkPreStmt(const CallExpr *CE, CheckerContext &C) const;
38
39 void CheckOpen(CheckerContext &C, const CallExpr *CE) const;
40 void CheckPthreadOnce(CheckerContext &C, const CallExpr *CE) const;
41 void CheckCallocZero(CheckerContext &C, const CallExpr *CE) const;
42 void CheckMallocZero(CheckerContext &C, const CallExpr *CE) const;
43 void CheckReallocZero(CheckerContext &C, const CallExpr *CE) const;
44 void CheckReallocfZero(CheckerContext &C, const CallExpr *CE) const;
45 void CheckAllocaZero(CheckerContext &C, const CallExpr *CE) const;
46 void CheckVallocZero(CheckerContext &C, const CallExpr *CE) const;
47
48 typedef void (UnixAPIChecker::*SubChecker)(CheckerContext &,
49 const CallExpr *) const;
50 private:
51 bool ReportZeroByteAllocation(CheckerContext &C,
52 ProgramStateRef falseState,
53 const Expr *arg,
54 const char *fn_name) const;
55 void BasicAllocationCheck(CheckerContext &C,
56 const CallExpr *CE,
57 const unsigned numArgs,
58 const unsigned sizeArg,
59 const char *fn) const;
LazyInitialize(std::unique_ptr<BugType> & BT,const char * name) const60 void LazyInitialize(std::unique_ptr<BugType> &BT, const char *name) const {
61 if (BT)
62 return;
63 BT.reset(new BugType(this, name, categories::UnixAPI));
64 }
65 };
66 } //end anonymous namespace
67
68 //===----------------------------------------------------------------------===//
69 // "open" (man 2 open)
70 //===----------------------------------------------------------------------===//
71
CheckOpen(CheckerContext & C,const CallExpr * CE) const72 void UnixAPIChecker::CheckOpen(CheckerContext &C, const CallExpr *CE) const {
73 // The definition of O_CREAT is platform specific. We need a better way
74 // of querying this information from the checking environment.
75 if (!Val_O_CREAT.hasValue()) {
76 if (C.getASTContext().getTargetInfo().getTriple().getVendor()
77 == llvm::Triple::Apple)
78 Val_O_CREAT = 0x0200;
79 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
82 // that would require passing the Preprocessor object to the ExprEngine.
83 // See also: MallocChecker.cpp / M_ZERO.
84 return;
85 }
86 }
87
88 // Look at the 'oflags' argument for the O_CREAT flag.
89 ProgramStateRef state = C.getState();
90
91 if (CE->getNumArgs() < 2) {
92 // The frontend should issue a warning for this case, so this is a sanity
93 // check.
94 return;
95 }
96
97 // Now check if oflags has O_CREAT set.
98 const Expr *oflagsEx = CE->getArg(1);
99 const SVal V = state->getSVal(oflagsEx, C.getLocationContext());
100 if (!V.getAs<NonLoc>()) {
101 // The case where 'V' can be a location can only be due to a bad header,
102 // so in this case bail out.
103 return;
104 }
105 NonLoc oflags = V.castAs<NonLoc>();
106 NonLoc ocreateFlag = C.getSValBuilder()
107 .makeIntVal(Val_O_CREAT.getValue(), oflagsEx->getType()).castAs<NonLoc>();
108 SVal maskedFlagsUC = C.getSValBuilder().evalBinOpNN(state, BO_And,
109 oflags, ocreateFlag,
110 oflagsEx->getType());
111 if (maskedFlagsUC.isUnknownOrUndef())
112 return;
113 DefinedSVal maskedFlags = maskedFlagsUC.castAs<DefinedSVal>();
114
115 // Check if maskedFlags is non-zero.
116 ProgramStateRef trueState, falseState;
117 std::tie(trueState, falseState) = state->assume(maskedFlags);
118
119 // Only emit an error if the value of 'maskedFlags' is properly
120 // constrained;
121 if (!(trueState && !falseState))
122 return;
123
124 if (CE->getNumArgs() < 3) {
125 ExplodedNode *N = C.generateSink(trueState);
126 if (!N)
127 return;
128
129 LazyInitialize(BT_open, "Improper use of 'open'");
130
131 BugReport *report =
132 new BugReport(*BT_open,
133 "Call to 'open' requires a third argument when "
134 "the 'O_CREAT' flag is set", N);
135 report->addRange(oflagsEx->getSourceRange());
136 C.emitReport(report);
137 }
138 }
139
140 //===----------------------------------------------------------------------===//
141 // pthread_once
142 //===----------------------------------------------------------------------===//
143
CheckPthreadOnce(CheckerContext & C,const CallExpr * CE) const144 void UnixAPIChecker::CheckPthreadOnce(CheckerContext &C,
145 const CallExpr *CE) const {
146
147 // This is similar to 'CheckDispatchOnce' in the MacOSXAPIChecker.
148 // They can possibly be refactored.
149
150 if (CE->getNumArgs() < 1)
151 return;
152
153 // Check if the first argument is stack allocated. If so, issue a warning
154 // because that's likely to be bad news.
155 ProgramStateRef state = C.getState();
156 const MemRegion *R =
157 state->getSVal(CE->getArg(0), C.getLocationContext()).getAsRegion();
158 if (!R || !isa<StackSpaceRegion>(R->getMemorySpace()))
159 return;
160
161 ExplodedNode *N = C.generateSink(state);
162 if (!N)
163 return;
164
165 SmallString<256> S;
166 llvm::raw_svector_ostream os(S);
167 os << "Call to 'pthread_once' uses";
168 if (const VarRegion *VR = dyn_cast<VarRegion>(R))
169 os << " the local variable '" << VR->getDecl()->getName() << '\'';
170 else
171 os << " stack allocated memory";
172 os << " for the \"control\" value. Using such transient memory for "
173 "the control value is potentially dangerous.";
174 if (isa<VarRegion>(R) && isa<StackLocalsSpaceRegion>(R->getMemorySpace()))
175 os << " Perhaps you intended to declare the variable as 'static'?";
176
177 LazyInitialize(BT_pthreadOnce, "Improper use of 'pthread_once'");
178
179 BugReport *report = new BugReport(*BT_pthreadOnce, os.str(), N);
180 report->addRange(CE->getArg(0)->getSourceRange());
181 C.emitReport(report);
182 }
183
184 //===----------------------------------------------------------------------===//
185 // "calloc", "malloc", "realloc", "reallocf", "alloca" and "valloc"
186 // with allocation size 0
187 //===----------------------------------------------------------------------===//
188 // FIXME: Eventually these should be rolled into the MallocChecker, but right now
189 // they're more basic and valuable for widespread use.
190
191 // Returns true if we try to do a zero byte allocation, false otherwise.
192 // Fills in trueState and falseState.
IsZeroByteAllocation(ProgramStateRef state,const SVal argVal,ProgramStateRef * trueState,ProgramStateRef * falseState)193 static bool IsZeroByteAllocation(ProgramStateRef state,
194 const SVal argVal,
195 ProgramStateRef *trueState,
196 ProgramStateRef *falseState) {
197 std::tie(*trueState, *falseState) =
198 state->assume(argVal.castAs<DefinedSVal>());
199
200 return (*falseState && !*trueState);
201 }
202
203 // Generates an error report, indicating that the function whose name is given
204 // will perform a zero byte allocation.
205 // Returns false if an error occurred, true otherwise.
ReportZeroByteAllocation(CheckerContext & C,ProgramStateRef falseState,const Expr * arg,const char * fn_name) const206 bool UnixAPIChecker::ReportZeroByteAllocation(CheckerContext &C,
207 ProgramStateRef falseState,
208 const Expr *arg,
209 const char *fn_name) const {
210 ExplodedNode *N = C.generateSink(falseState);
211 if (!N)
212 return false;
213
214 LazyInitialize(BT_mallocZero,
215 "Undefined allocation of 0 bytes (CERT MEM04-C; CWE-131)");
216
217 SmallString<256> S;
218 llvm::raw_svector_ostream os(S);
219 os << "Call to '" << fn_name << "' has an allocation size of 0 bytes";
220 BugReport *report = new BugReport(*BT_mallocZero, os.str(), N);
221
222 report->addRange(arg->getSourceRange());
223 bugreporter::trackNullOrUndefValue(N, arg, *report);
224 C.emitReport(report);
225
226 return true;
227 }
228
229 // Does a basic check for 0-sized allocations suitable for most of the below
230 // functions (modulo "calloc")
BasicAllocationCheck(CheckerContext & C,const CallExpr * CE,const unsigned numArgs,const unsigned sizeArg,const char * fn) const231 void UnixAPIChecker::BasicAllocationCheck(CheckerContext &C,
232 const CallExpr *CE,
233 const unsigned numArgs,
234 const unsigned sizeArg,
235 const char *fn) const {
236 // Sanity check for the correct number of arguments
237 if (CE->getNumArgs() != numArgs)
238 return;
239
240 // Check if the allocation size is 0.
241 ProgramStateRef state = C.getState();
242 ProgramStateRef trueState = nullptr, falseState = nullptr;
243 const Expr *arg = CE->getArg(sizeArg);
244 SVal argVal = state->getSVal(arg, C.getLocationContext());
245
246 if (argVal.isUnknownOrUndef())
247 return;
248
249 // Is the value perfectly constrained to zero?
250 if (IsZeroByteAllocation(state, argVal, &trueState, &falseState)) {
251 (void) ReportZeroByteAllocation(C, falseState, arg, fn);
252 return;
253 }
254 // Assume the value is non-zero going forward.
255 assert(trueState);
256 if (trueState != state)
257 C.addTransition(trueState);
258 }
259
CheckCallocZero(CheckerContext & C,const CallExpr * CE) const260 void UnixAPIChecker::CheckCallocZero(CheckerContext &C,
261 const CallExpr *CE) const {
262 unsigned int nArgs = CE->getNumArgs();
263 if (nArgs != 2)
264 return;
265
266 ProgramStateRef state = C.getState();
267 ProgramStateRef trueState = nullptr, falseState = nullptr;
268
269 unsigned int i;
270 for (i = 0; i < nArgs; i++) {
271 const Expr *arg = CE->getArg(i);
272 SVal argVal = state->getSVal(arg, C.getLocationContext());
273 if (argVal.isUnknownOrUndef()) {
274 if (i == 0)
275 continue;
276 else
277 return;
278 }
279
280 if (IsZeroByteAllocation(state, argVal, &trueState, &falseState)) {
281 if (ReportZeroByteAllocation(C, falseState, arg, "calloc"))
282 return;
283 else if (i == 0)
284 continue;
285 else
286 return;
287 }
288 }
289
290 // Assume the value is non-zero going forward.
291 assert(trueState);
292 if (trueState != state)
293 C.addTransition(trueState);
294 }
295
CheckMallocZero(CheckerContext & C,const CallExpr * CE) const296 void UnixAPIChecker::CheckMallocZero(CheckerContext &C,
297 const CallExpr *CE) const {
298 BasicAllocationCheck(C, CE, 1, 0, "malloc");
299 }
300
CheckReallocZero(CheckerContext & C,const CallExpr * CE) const301 void UnixAPIChecker::CheckReallocZero(CheckerContext &C,
302 const CallExpr *CE) const {
303 BasicAllocationCheck(C, CE, 2, 1, "realloc");
304 }
305
CheckReallocfZero(CheckerContext & C,const CallExpr * CE) const306 void UnixAPIChecker::CheckReallocfZero(CheckerContext &C,
307 const CallExpr *CE) const {
308 BasicAllocationCheck(C, CE, 2, 1, "reallocf");
309 }
310
CheckAllocaZero(CheckerContext & C,const CallExpr * CE) const311 void UnixAPIChecker::CheckAllocaZero(CheckerContext &C,
312 const CallExpr *CE) const {
313 BasicAllocationCheck(C, CE, 1, 0, "alloca");
314 }
315
CheckVallocZero(CheckerContext & C,const CallExpr * CE) const316 void UnixAPIChecker::CheckVallocZero(CheckerContext &C,
317 const CallExpr *CE) const {
318 BasicAllocationCheck(C, CE, 1, 0, "valloc");
319 }
320
321
322 //===----------------------------------------------------------------------===//
323 // Central dispatch function.
324 //===----------------------------------------------------------------------===//
325
checkPreStmt(const CallExpr * CE,CheckerContext & C) const326 void UnixAPIChecker::checkPreStmt(const CallExpr *CE,
327 CheckerContext &C) const {
328 const FunctionDecl *FD = C.getCalleeDecl(CE);
329 if (!FD || FD->getKind() != Decl::Function)
330 return;
331
332 StringRef FName = C.getCalleeName(FD);
333 if (FName.empty())
334 return;
335
336 SubChecker SC =
337 llvm::StringSwitch<SubChecker>(FName)
338 .Case("open", &UnixAPIChecker::CheckOpen)
339 .Case("pthread_once", &UnixAPIChecker::CheckPthreadOnce)
340 .Case("calloc", &UnixAPIChecker::CheckCallocZero)
341 .Case("malloc", &UnixAPIChecker::CheckMallocZero)
342 .Case("realloc", &UnixAPIChecker::CheckReallocZero)
343 .Case("reallocf", &UnixAPIChecker::CheckReallocfZero)
344 .Cases("alloca", "__builtin_alloca", &UnixAPIChecker::CheckAllocaZero)
345 .Case("valloc", &UnixAPIChecker::CheckVallocZero)
346 .Default(nullptr);
347
348 if (SC)
349 (this->*SC)(C, CE);
350 }
351
352 //===----------------------------------------------------------------------===//
353 // Registration.
354 //===----------------------------------------------------------------------===//
355
registerUnixAPIChecker(CheckerManager & mgr)356 void ento::registerUnixAPIChecker(CheckerManager &mgr) {
357 mgr.registerChecker<UnixAPIChecker>();
358 }
359