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 DefaultBool CheckMisuse, CheckPortability;
50 void checkPreStmt(const CallExpr *CE, CheckerContext &C) const;
52 void CheckOpen(CheckerContext &C, const CallExpr *CE) const;
53 void CheckOpenAt(CheckerContext &C, const CallExpr *CE) const;
55 void CheckPthreadOnce(CheckerContext &C, const CallExpr *CE) const;
56 void CheckCallocZero(CheckerContext &C, const CallExpr *CE) const;
57 void CheckMallocZero(CheckerContext &C, const CallExpr *CE) const;
58 void CheckReallocZero(CheckerContext &C, const CallExpr *CE) const;
59 void CheckReallocfZero(CheckerContext &C, const CallExpr *CE) const;
60 void CheckAllocaZero(CheckerContext &C, const CallExpr *CE) const;
61 void CheckAllocaWithAlignZero(CheckerContext &C, const CallExpr *CE) const;
62 void CheckVallocZero(CheckerContext &C, const CallExpr *CE) const;
64 typedef void (UnixAPIChecker::*SubChecker)(CheckerContext &,
65 const CallExpr *) const;
68 void CheckOpenVariant(CheckerContext &C,
69 const CallExpr *CE, OpenVariant Variant) const;
71 bool ReportZeroByteAllocation(CheckerContext &C,
72 ProgramStateRef falseState,
74 const char *fn_name) const;
75 void BasicAllocationCheck(CheckerContext &C,
77 const unsigned numArgs,
78 const unsigned sizeArg,
79 const char *fn) const;
80 void LazyInitialize(std::unique_ptr<BugType> &BT, const char *name) const {
83 BT.reset(new BugType(this, name, categories::UnixAPI));
85 void ReportOpenBug(CheckerContext &C,
86 ProgramStateRef State,
88 SourceRange SR) const;
90 } //end anonymous namespace
92 //===----------------------------------------------------------------------===//
93 // "open" (man 2 open)
94 //===----------------------------------------------------------------------===//
96 void UnixAPIChecker::ReportOpenBug(CheckerContext &C,
97 ProgramStateRef State,
99 SourceRange SR) const {
100 ExplodedNode *N = C.generateErrorNode(State);
104 LazyInitialize(BT_open, "Improper use of 'open'");
106 auto Report = llvm::make_unique<BugReport>(*BT_open, Msg, N);
107 Report->addRange(SR);
108 C.emitReport(std::move(Report));
111 void UnixAPIChecker::CheckOpen(CheckerContext &C, const CallExpr *CE) const {
112 CheckOpenVariant(C, CE, OpenVariant::Open);
115 void UnixAPIChecker::CheckOpenAt(CheckerContext &C, const CallExpr *CE) const {
116 CheckOpenVariant(C, CE, OpenVariant::OpenAt);
119 void UnixAPIChecker::CheckOpenVariant(CheckerContext &C,
121 OpenVariant Variant) const {
122 // The index of the argument taking the flags open flags (O_RDONLY,
123 // O_WRONLY, O_CREAT, etc.),
124 unsigned int FlagsArgIndex;
125 const char *VariantName;
127 case OpenVariant::Open:
129 VariantName = "open";
131 case OpenVariant::OpenAt:
133 VariantName = "openat";
137 // All calls should at least provide arguments up to the 'flags' parameter.
138 unsigned int MinArgCount = FlagsArgIndex + 1;
140 // If the flags has O_CREAT set then open/openat() require an additional
141 // argument specifying the file mode (permission bits) for the created file.
142 unsigned int CreateModeArgIndex = FlagsArgIndex + 1;
144 // The create mode argument should be the last argument.
145 unsigned int MaxArgCount = CreateModeArgIndex + 1;
147 ProgramStateRef state = C.getState();
149 if (CE->getNumArgs() < MinArgCount) {
150 // The frontend should issue a warning for this case, so this is a sanity
153 } else if (CE->getNumArgs() == MaxArgCount) {
154 const Expr *Arg = CE->getArg(CreateModeArgIndex);
155 QualType QT = Arg->getType();
156 if (!QT->isIntegerType()) {
157 SmallString<256> SBuf;
158 llvm::raw_svector_ostream OS(SBuf);
159 OS << "The " << CreateModeArgIndex + 1
160 << llvm::getOrdinalSuffix(CreateModeArgIndex + 1)
161 << " argument to '" << VariantName << "' is not an integer";
163 ReportOpenBug(C, state,
165 Arg->getSourceRange());
168 } else if (CE->getNumArgs() > MaxArgCount) {
169 SmallString<256> SBuf;
170 llvm::raw_svector_ostream OS(SBuf);
171 OS << "Call to '" << VariantName << "' with more than " << MaxArgCount
174 ReportOpenBug(C, state,
176 CE->getArg(MaxArgCount)->getSourceRange());
180 // The definition of O_CREAT is platform specific. We need a better way
181 // of querying this information from the checking environment.
182 if (!Val_O_CREAT.hasValue()) {
183 if (C.getASTContext().getTargetInfo().getTriple().getVendor()
184 == llvm::Triple::Apple)
185 Val_O_CREAT = 0x0200;
187 // FIXME: We need a more general way of getting the O_CREAT value.
188 // We could possibly grovel through the preprocessor state, but
189 // that would require passing the Preprocessor object to the ExprEngine.
190 // See also: MallocChecker.cpp / M_ZERO.
195 // Now check if oflags has O_CREAT set.
196 const Expr *oflagsEx = CE->getArg(FlagsArgIndex);
197 const SVal V = state->getSVal(oflagsEx, C.getLocationContext());
198 if (!V.getAs<NonLoc>()) {
199 // The case where 'V' can be a location can only be due to a bad header,
200 // so in this case bail out.
203 NonLoc oflags = V.castAs<NonLoc>();
204 NonLoc ocreateFlag = C.getSValBuilder()
205 .makeIntVal(Val_O_CREAT.getValue(), oflagsEx->getType()).castAs<NonLoc>();
206 SVal maskedFlagsUC = C.getSValBuilder().evalBinOpNN(state, BO_And,
208 oflagsEx->getType());
209 if (maskedFlagsUC.isUnknownOrUndef())
211 DefinedSVal maskedFlags = maskedFlagsUC.castAs<DefinedSVal>();
213 // Check if maskedFlags is non-zero.
214 ProgramStateRef trueState, falseState;
215 std::tie(trueState, falseState) = state->assume(maskedFlags);
217 // Only emit an error if the value of 'maskedFlags' is properly
219 if (!(trueState && !falseState))
222 if (CE->getNumArgs() < MaxArgCount) {
223 SmallString<256> SBuf;
224 llvm::raw_svector_ostream OS(SBuf);
225 OS << "Call to '" << VariantName << "' requires a "
226 << CreateModeArgIndex + 1
227 << llvm::getOrdinalSuffix(CreateModeArgIndex + 1)
228 << " argument when the 'O_CREAT' flag is set";
229 ReportOpenBug(C, trueState,
231 oflagsEx->getSourceRange());
235 //===----------------------------------------------------------------------===//
237 //===----------------------------------------------------------------------===//
239 void UnixAPIChecker::CheckPthreadOnce(CheckerContext &C,
240 const CallExpr *CE) const {
242 // This is similar to 'CheckDispatchOnce' in the MacOSXAPIChecker.
243 // They can possibly be refactored.
245 if (CE->getNumArgs() < 1)
248 // Check if the first argument is stack allocated. If so, issue a warning
249 // because that's likely to be bad news.
250 ProgramStateRef state = C.getState();
252 state->getSVal(CE->getArg(0), C.getLocationContext()).getAsRegion();
253 if (!R || !isa<StackSpaceRegion>(R->getMemorySpace()))
256 ExplodedNode *N = C.generateErrorNode(state);
261 llvm::raw_svector_ostream os(S);
262 os << "Call to 'pthread_once' uses";
263 if (const VarRegion *VR = dyn_cast<VarRegion>(R))
264 os << " the local variable '" << VR->getDecl()->getName() << '\'';
266 os << " stack allocated memory";
267 os << " for the \"control\" value. Using such transient memory for "
268 "the control value is potentially dangerous.";
269 if (isa<VarRegion>(R) && isa<StackLocalsSpaceRegion>(R->getMemorySpace()))
270 os << " Perhaps you intended to declare the variable as 'static'?";
272 LazyInitialize(BT_pthreadOnce, "Improper use of 'pthread_once'");
274 auto report = llvm::make_unique<BugReport>(*BT_pthreadOnce, os.str(), N);
275 report->addRange(CE->getArg(0)->getSourceRange());
276 C.emitReport(std::move(report));
279 //===----------------------------------------------------------------------===//
280 // "calloc", "malloc", "realloc", "reallocf", "alloca" and "valloc"
281 // with allocation size 0
282 //===----------------------------------------------------------------------===//
283 // FIXME: Eventually these should be rolled into the MallocChecker, but right now
284 // they're more basic and valuable for widespread use.
286 // Returns true if we try to do a zero byte allocation, false otherwise.
287 // Fills in trueState and falseState.
288 static bool IsZeroByteAllocation(ProgramStateRef state,
290 ProgramStateRef *trueState,
291 ProgramStateRef *falseState) {
292 std::tie(*trueState, *falseState) =
293 state->assume(argVal.castAs<DefinedSVal>());
295 return (*falseState && !*trueState);
298 // Generates an error report, indicating that the function whose name is given
299 // will perform a zero byte allocation.
300 // Returns false if an error occurred, true otherwise.
301 bool UnixAPIChecker::ReportZeroByteAllocation(CheckerContext &C,
302 ProgramStateRef falseState,
304 const char *fn_name) const {
305 ExplodedNode *N = C.generateErrorNode(falseState);
309 LazyInitialize(BT_mallocZero,
310 "Undefined allocation of 0 bytes (CERT MEM04-C; CWE-131)");
313 llvm::raw_svector_ostream os(S);
314 os << "Call to '" << fn_name << "' has an allocation size of 0 bytes";
315 auto report = llvm::make_unique<BugReport>(*BT_mallocZero, os.str(), N);
317 report->addRange(arg->getSourceRange());
318 bugreporter::trackNullOrUndefValue(N, arg, *report);
319 C.emitReport(std::move(report));
324 // Does a basic check for 0-sized allocations suitable for most of the below
325 // functions (modulo "calloc")
326 void UnixAPIChecker::BasicAllocationCheck(CheckerContext &C,
328 const unsigned numArgs,
329 const unsigned sizeArg,
330 const char *fn) const {
331 // Sanity check for the correct number of arguments
332 if (CE->getNumArgs() != numArgs)
335 // Check if the allocation size is 0.
336 ProgramStateRef state = C.getState();
337 ProgramStateRef trueState = nullptr, falseState = nullptr;
338 const Expr *arg = CE->getArg(sizeArg);
339 SVal argVal = state->getSVal(arg, C.getLocationContext());
341 if (argVal.isUnknownOrUndef())
344 // Is the value perfectly constrained to zero?
345 if (IsZeroByteAllocation(state, argVal, &trueState, &falseState)) {
346 (void) ReportZeroByteAllocation(C, falseState, arg, fn);
349 // Assume the value is non-zero going forward.
351 if (trueState != state)
352 C.addTransition(trueState);
355 void UnixAPIChecker::CheckCallocZero(CheckerContext &C,
356 const CallExpr *CE) const {
357 unsigned int nArgs = CE->getNumArgs();
361 ProgramStateRef state = C.getState();
362 ProgramStateRef trueState = nullptr, falseState = nullptr;
365 for (i = 0; i < nArgs; i++) {
366 const Expr *arg = CE->getArg(i);
367 SVal argVal = state->getSVal(arg, C.getLocationContext());
368 if (argVal.isUnknownOrUndef()) {
375 if (IsZeroByteAllocation(state, argVal, &trueState, &falseState)) {
376 if (ReportZeroByteAllocation(C, falseState, arg, "calloc"))
385 // Assume the value is non-zero going forward.
387 if (trueState != state)
388 C.addTransition(trueState);
391 void UnixAPIChecker::CheckMallocZero(CheckerContext &C,
392 const CallExpr *CE) const {
393 BasicAllocationCheck(C, CE, 1, 0, "malloc");
396 void UnixAPIChecker::CheckReallocZero(CheckerContext &C,
397 const CallExpr *CE) const {
398 BasicAllocationCheck(C, CE, 2, 1, "realloc");
401 void UnixAPIChecker::CheckReallocfZero(CheckerContext &C,
402 const CallExpr *CE) const {
403 BasicAllocationCheck(C, CE, 2, 1, "reallocf");
406 void UnixAPIChecker::CheckAllocaZero(CheckerContext &C,
407 const CallExpr *CE) const {
408 BasicAllocationCheck(C, CE, 1, 0, "alloca");
411 void UnixAPIChecker::CheckAllocaWithAlignZero(CheckerContext &C,
412 const CallExpr *CE) const {
413 BasicAllocationCheck(C, CE, 2, 0, "__builtin_alloca_with_align");
416 void UnixAPIChecker::CheckVallocZero(CheckerContext &C,
417 const CallExpr *CE) const {
418 BasicAllocationCheck(C, CE, 1, 0, "valloc");
422 //===----------------------------------------------------------------------===//
423 // Central dispatch function.
424 //===----------------------------------------------------------------------===//
426 void UnixAPIChecker::checkPreStmt(const CallExpr *CE,
427 CheckerContext &C) const {
428 const FunctionDecl *FD = C.getCalleeDecl(CE);
429 if (!FD || FD->getKind() != Decl::Function)
432 // Don't treat functions in namespaces with the same name a Unix function
433 // as a call to the Unix function.
434 const DeclContext *NamespaceCtx = FD->getEnclosingNamespaceContext();
435 if (NamespaceCtx && isa<NamespaceDecl>(NamespaceCtx))
438 StringRef FName = C.getCalleeName(FD);
444 llvm::StringSwitch<SubChecker>(FName)
445 .Case("open", &UnixAPIChecker::CheckOpen)
446 .Case("openat", &UnixAPIChecker::CheckOpenAt)
447 .Case("pthread_once", &UnixAPIChecker::CheckPthreadOnce)
452 if (CheckPortability) {
454 llvm::StringSwitch<SubChecker>(FName)
455 .Case("calloc", &UnixAPIChecker::CheckCallocZero)
456 .Case("malloc", &UnixAPIChecker::CheckMallocZero)
457 .Case("realloc", &UnixAPIChecker::CheckReallocZero)
458 .Case("reallocf", &UnixAPIChecker::CheckReallocfZero)
459 .Cases("alloca", "__builtin_alloca",
460 &UnixAPIChecker::CheckAllocaZero)
461 .Case("__builtin_alloca_with_align",
462 &UnixAPIChecker::CheckAllocaWithAlignZero)
463 .Case("valloc", &UnixAPIChecker::CheckVallocZero)
470 //===----------------------------------------------------------------------===//
472 //===----------------------------------------------------------------------===//
474 #define REGISTER_CHECKER(Name) \
475 void ento::registerUnixAPI##Name##Checker(CheckerManager &mgr) { \
476 mgr.registerChecker<UnixAPIChecker>()->Check##Name = true; \
479 REGISTER_CHECKER(Misuse)
480 REGISTER_CHECKER(Portability)