1 //= UnixAPIChecker.h - Checks preconditions for various Unix APIs --*- C++ -*-//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This defines UnixAPIChecker, which is an assortment of checks on calls
11 // to various, widely used UNIX/Posix functions.
13 //===----------------------------------------------------------------------===//
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/StringExtras.h"
25 #include "llvm/ADT/StringSwitch.h"
26 #include "llvm/Support/raw_ostream.h"
29 using namespace clang;
32 enum class OpenVariant {
33 /// The standard open() call:
34 /// int open(const char *path, int oflag, ...);
37 /// The variant taking a directory file descriptor and a relative path:
38 /// int openat(int fd, const char *path, int oflag, ...);
43 class UnixAPIChecker : public Checker< check::PreStmt<CallExpr> > {
44 mutable std::unique_ptr<BugType> BT_open, BT_pthreadOnce, BT_mallocZero;
45 mutable Optional<uint64_t> Val_O_CREAT;
48 void checkPreStmt(const CallExpr *CE, CheckerContext &C) const;
50 void CheckOpen(CheckerContext &C, const CallExpr *CE) const;
51 void CheckOpenAt(CheckerContext &C, const CallExpr *CE) const;
53 void CheckPthreadOnce(CheckerContext &C, const CallExpr *CE) const;
54 void CheckCallocZero(CheckerContext &C, const CallExpr *CE) const;
55 void CheckMallocZero(CheckerContext &C, const CallExpr *CE) const;
56 void CheckReallocZero(CheckerContext &C, const CallExpr *CE) const;
57 void CheckReallocfZero(CheckerContext &C, const CallExpr *CE) const;
58 void CheckAllocaZero(CheckerContext &C, const CallExpr *CE) const;
59 void CheckAllocaWithAlignZero(CheckerContext &C, const CallExpr *CE) const;
60 void CheckVallocZero(CheckerContext &C, const CallExpr *CE) const;
62 typedef void (UnixAPIChecker::*SubChecker)(CheckerContext &,
63 const CallExpr *) const;
66 void CheckOpenVariant(CheckerContext &C,
67 const CallExpr *CE, OpenVariant Variant) const;
69 bool ReportZeroByteAllocation(CheckerContext &C,
70 ProgramStateRef falseState,
72 const char *fn_name) const;
73 void BasicAllocationCheck(CheckerContext &C,
75 const unsigned numArgs,
76 const unsigned sizeArg,
77 const char *fn) const;
78 void LazyInitialize(std::unique_ptr<BugType> &BT, const char *name) const {
81 BT.reset(new BugType(this, name, categories::UnixAPI));
83 void ReportOpenBug(CheckerContext &C,
84 ProgramStateRef State,
86 SourceRange SR) const;
88 } //end anonymous namespace
90 //===----------------------------------------------------------------------===//
91 // "open" (man 2 open)
92 //===----------------------------------------------------------------------===//
94 void UnixAPIChecker::ReportOpenBug(CheckerContext &C,
95 ProgramStateRef State,
97 SourceRange SR) const {
98 ExplodedNode *N = C.generateErrorNode(State);
102 LazyInitialize(BT_open, "Improper use of 'open'");
104 auto Report = llvm::make_unique<BugReport>(*BT_open, Msg, N);
105 Report->addRange(SR);
106 C.emitReport(std::move(Report));
109 void UnixAPIChecker::CheckOpen(CheckerContext &C, const CallExpr *CE) const {
110 CheckOpenVariant(C, CE, OpenVariant::Open);
113 void UnixAPIChecker::CheckOpenAt(CheckerContext &C, const CallExpr *CE) const {
114 CheckOpenVariant(C, CE, OpenVariant::OpenAt);
117 void UnixAPIChecker::CheckOpenVariant(CheckerContext &C,
119 OpenVariant Variant) const {
120 // The index of the argument taking the flags open flags (O_RDONLY,
121 // O_WRONLY, O_CREAT, etc.),
122 unsigned int FlagsArgIndex;
123 const char *VariantName;
125 case OpenVariant::Open:
127 VariantName = "open";
129 case OpenVariant::OpenAt:
131 VariantName = "openat";
135 // All calls should at least provide arguments up to the 'flags' parameter.
136 unsigned int MinArgCount = FlagsArgIndex + 1;
138 // If the flags has O_CREAT set then open/openat() require an additional
139 // argument specifying the file mode (permission bits) for the created file.
140 unsigned int CreateModeArgIndex = FlagsArgIndex + 1;
142 // The create mode argument should be the last argument.
143 unsigned int MaxArgCount = CreateModeArgIndex + 1;
145 ProgramStateRef state = C.getState();
147 if (CE->getNumArgs() < MinArgCount) {
148 // The frontend should issue a warning for this case, so this is a sanity
151 } else if (CE->getNumArgs() == MaxArgCount) {
152 const Expr *Arg = CE->getArg(CreateModeArgIndex);
153 QualType QT = Arg->getType();
154 if (!QT->isIntegerType()) {
155 SmallString<256> SBuf;
156 llvm::raw_svector_ostream OS(SBuf);
157 OS << "The " << CreateModeArgIndex + 1
158 << llvm::getOrdinalSuffix(CreateModeArgIndex + 1)
159 << " argument to '" << VariantName << "' is not an integer";
161 ReportOpenBug(C, state,
163 Arg->getSourceRange());
166 } else if (CE->getNumArgs() > MaxArgCount) {
167 SmallString<256> SBuf;
168 llvm::raw_svector_ostream OS(SBuf);
169 OS << "Call to '" << VariantName << "' with more than " << MaxArgCount
172 ReportOpenBug(C, state,
174 CE->getArg(MaxArgCount)->getSourceRange());
178 // The definition of O_CREAT is platform specific. We need a better way
179 // of querying this information from the checking environment.
180 if (!Val_O_CREAT.hasValue()) {
181 if (C.getASTContext().getTargetInfo().getTriple().getVendor()
182 == llvm::Triple::Apple)
183 Val_O_CREAT = 0x0200;
185 // FIXME: We need a more general way of getting the O_CREAT value.
186 // We could possibly grovel through the preprocessor state, but
187 // that would require passing the Preprocessor object to the ExprEngine.
188 // See also: MallocChecker.cpp / M_ZERO.
193 // Now check if oflags has O_CREAT set.
194 const Expr *oflagsEx = CE->getArg(FlagsArgIndex);
195 const SVal V = state->getSVal(oflagsEx, C.getLocationContext());
196 if (!V.getAs<NonLoc>()) {
197 // The case where 'V' can be a location can only be due to a bad header,
198 // so in this case bail out.
201 NonLoc oflags = V.castAs<NonLoc>();
202 NonLoc ocreateFlag = C.getSValBuilder()
203 .makeIntVal(Val_O_CREAT.getValue(), oflagsEx->getType()).castAs<NonLoc>();
204 SVal maskedFlagsUC = C.getSValBuilder().evalBinOpNN(state, BO_And,
206 oflagsEx->getType());
207 if (maskedFlagsUC.isUnknownOrUndef())
209 DefinedSVal maskedFlags = maskedFlagsUC.castAs<DefinedSVal>();
211 // Check if maskedFlags is non-zero.
212 ProgramStateRef trueState, falseState;
213 std::tie(trueState, falseState) = state->assume(maskedFlags);
215 // Only emit an error if the value of 'maskedFlags' is properly
217 if (!(trueState && !falseState))
220 if (CE->getNumArgs() < MaxArgCount) {
221 SmallString<256> SBuf;
222 llvm::raw_svector_ostream OS(SBuf);
223 OS << "Call to '" << VariantName << "' requires a "
224 << CreateModeArgIndex + 1
225 << llvm::getOrdinalSuffix(CreateModeArgIndex + 1)
226 << " argument when the 'O_CREAT' flag is set";
227 ReportOpenBug(C, trueState,
229 oflagsEx->getSourceRange());
233 //===----------------------------------------------------------------------===//
235 //===----------------------------------------------------------------------===//
237 void UnixAPIChecker::CheckPthreadOnce(CheckerContext &C,
238 const CallExpr *CE) const {
240 // This is similar to 'CheckDispatchOnce' in the MacOSXAPIChecker.
241 // They can possibly be refactored.
243 if (CE->getNumArgs() < 1)
246 // Check if the first argument is stack allocated. If so, issue a warning
247 // because that's likely to be bad news.
248 ProgramStateRef state = C.getState();
250 state->getSVal(CE->getArg(0), C.getLocationContext()).getAsRegion();
251 if (!R || !isa<StackSpaceRegion>(R->getMemorySpace()))
254 ExplodedNode *N = C.generateErrorNode(state);
259 llvm::raw_svector_ostream os(S);
260 os << "Call to 'pthread_once' uses";
261 if (const VarRegion *VR = dyn_cast<VarRegion>(R))
262 os << " the local variable '" << VR->getDecl()->getName() << '\'';
264 os << " stack allocated memory";
265 os << " for the \"control\" value. Using such transient memory for "
266 "the control value is potentially dangerous.";
267 if (isa<VarRegion>(R) && isa<StackLocalsSpaceRegion>(R->getMemorySpace()))
268 os << " Perhaps you intended to declare the variable as 'static'?";
270 LazyInitialize(BT_pthreadOnce, "Improper use of 'pthread_once'");
272 auto report = llvm::make_unique<BugReport>(*BT_pthreadOnce, os.str(), N);
273 report->addRange(CE->getArg(0)->getSourceRange());
274 C.emitReport(std::move(report));
277 //===----------------------------------------------------------------------===//
278 // "calloc", "malloc", "realloc", "reallocf", "alloca" and "valloc"
279 // with allocation size 0
280 //===----------------------------------------------------------------------===//
281 // FIXME: Eventually these should be rolled into the MallocChecker, but right now
282 // they're more basic and valuable for widespread use.
284 // Returns true if we try to do a zero byte allocation, false otherwise.
285 // Fills in trueState and falseState.
286 static bool IsZeroByteAllocation(ProgramStateRef state,
288 ProgramStateRef *trueState,
289 ProgramStateRef *falseState) {
290 std::tie(*trueState, *falseState) =
291 state->assume(argVal.castAs<DefinedSVal>());
293 return (*falseState && !*trueState);
296 // Generates an error report, indicating that the function whose name is given
297 // will perform a zero byte allocation.
298 // Returns false if an error occurred, true otherwise.
299 bool UnixAPIChecker::ReportZeroByteAllocation(CheckerContext &C,
300 ProgramStateRef falseState,
302 const char *fn_name) const {
303 ExplodedNode *N = C.generateErrorNode(falseState);
307 LazyInitialize(BT_mallocZero,
308 "Undefined allocation of 0 bytes (CERT MEM04-C; CWE-131)");
311 llvm::raw_svector_ostream os(S);
312 os << "Call to '" << fn_name << "' has an allocation size of 0 bytes";
313 auto report = llvm::make_unique<BugReport>(*BT_mallocZero, os.str(), N);
315 report->addRange(arg->getSourceRange());
316 bugreporter::trackNullOrUndefValue(N, arg, *report);
317 C.emitReport(std::move(report));
322 // Does a basic check for 0-sized allocations suitable for most of the below
323 // functions (modulo "calloc")
324 void UnixAPIChecker::BasicAllocationCheck(CheckerContext &C,
326 const unsigned numArgs,
327 const unsigned sizeArg,
328 const char *fn) const {
329 // Sanity check for the correct number of arguments
330 if (CE->getNumArgs() != numArgs)
333 // Check if the allocation size is 0.
334 ProgramStateRef state = C.getState();
335 ProgramStateRef trueState = nullptr, falseState = nullptr;
336 const Expr *arg = CE->getArg(sizeArg);
337 SVal argVal = state->getSVal(arg, C.getLocationContext());
339 if (argVal.isUnknownOrUndef())
342 // Is the value perfectly constrained to zero?
343 if (IsZeroByteAllocation(state, argVal, &trueState, &falseState)) {
344 (void) ReportZeroByteAllocation(C, falseState, arg, fn);
347 // Assume the value is non-zero going forward.
349 if (trueState != state)
350 C.addTransition(trueState);
353 void UnixAPIChecker::CheckCallocZero(CheckerContext &C,
354 const CallExpr *CE) const {
355 unsigned int nArgs = CE->getNumArgs();
359 ProgramStateRef state = C.getState();
360 ProgramStateRef trueState = nullptr, falseState = nullptr;
363 for (i = 0; i < nArgs; i++) {
364 const Expr *arg = CE->getArg(i);
365 SVal argVal = state->getSVal(arg, C.getLocationContext());
366 if (argVal.isUnknownOrUndef()) {
373 if (IsZeroByteAllocation(state, argVal, &trueState, &falseState)) {
374 if (ReportZeroByteAllocation(C, falseState, arg, "calloc"))
383 // Assume the value is non-zero going forward.
385 if (trueState != state)
386 C.addTransition(trueState);
389 void UnixAPIChecker::CheckMallocZero(CheckerContext &C,
390 const CallExpr *CE) const {
391 BasicAllocationCheck(C, CE, 1, 0, "malloc");
394 void UnixAPIChecker::CheckReallocZero(CheckerContext &C,
395 const CallExpr *CE) const {
396 BasicAllocationCheck(C, CE, 2, 1, "realloc");
399 void UnixAPIChecker::CheckReallocfZero(CheckerContext &C,
400 const CallExpr *CE) const {
401 BasicAllocationCheck(C, CE, 2, 1, "reallocf");
404 void UnixAPIChecker::CheckAllocaZero(CheckerContext &C,
405 const CallExpr *CE) const {
406 BasicAllocationCheck(C, CE, 1, 0, "alloca");
409 void UnixAPIChecker::CheckAllocaWithAlignZero(CheckerContext &C,
410 const CallExpr *CE) const {
411 BasicAllocationCheck(C, CE, 2, 0, "__builtin_alloca_with_align");
414 void UnixAPIChecker::CheckVallocZero(CheckerContext &C,
415 const CallExpr *CE) const {
416 BasicAllocationCheck(C, CE, 1, 0, "valloc");
420 //===----------------------------------------------------------------------===//
421 // Central dispatch function.
422 //===----------------------------------------------------------------------===//
424 void UnixAPIChecker::checkPreStmt(const CallExpr *CE,
425 CheckerContext &C) const {
426 const FunctionDecl *FD = C.getCalleeDecl(CE);
427 if (!FD || FD->getKind() != Decl::Function)
430 // Don't treat functions in namespaces with the same name a Unix function
431 // as a call to the Unix function.
432 const DeclContext *NamespaceCtx = FD->getEnclosingNamespaceContext();
433 if (NamespaceCtx && isa<NamespaceDecl>(NamespaceCtx))
436 StringRef FName = C.getCalleeName(FD);
441 llvm::StringSwitch<SubChecker>(FName)
442 .Case("open", &UnixAPIChecker::CheckOpen)
443 .Case("openat", &UnixAPIChecker::CheckOpenAt)
444 .Case("pthread_once", &UnixAPIChecker::CheckPthreadOnce)
445 .Case("calloc", &UnixAPIChecker::CheckCallocZero)
446 .Case("malloc", &UnixAPIChecker::CheckMallocZero)
447 .Case("realloc", &UnixAPIChecker::CheckReallocZero)
448 .Case("reallocf", &UnixAPIChecker::CheckReallocfZero)
449 .Cases("alloca", "__builtin_alloca", &UnixAPIChecker::CheckAllocaZero)
450 .Case("__builtin_alloca_with_align",
451 &UnixAPIChecker::CheckAllocaWithAlignZero)
452 .Case("valloc", &UnixAPIChecker::CheckVallocZero)
459 //===----------------------------------------------------------------------===//
461 //===----------------------------------------------------------------------===//
463 void ento::registerUnixAPIChecker(CheckerManager &mgr) {
464 mgr.registerChecker<UnixAPIChecker>();