[analyzer] Refactoring: include/clang/Checker -> include/clang/GR
[clang.git] / lib / Checker / UnixAPIChecker.cpp
blob4f1b25f4d85d85ce9355a12efe0e5df233f61a30
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.
13 //===----------------------------------------------------------------------===//
15 #include "GRExprEngineInternalChecks.h"
16 #include "clang/Basic/TargetInfo.h"
17 #include "clang/GR/BugReporter/BugType.h"
18 #include "clang/GR/PathSensitive/CheckerVisitor.h"
19 #include "llvm/ADT/Optional.h"
20 #include "llvm/ADT/StringSwitch.h"
21 #include <fcntl.h>
23 using namespace clang;
24 using llvm::Optional;
26 namespace {
27 class UnixAPIChecker : public CheckerVisitor<UnixAPIChecker> {
28 enum SubChecks {
29 OpenFn = 0,
30 PthreadOnceFn = 1,
31 MallocZero = 2,
32 NumChecks
35 BugType *BTypes[NumChecks];
37 public:
38 Optional<uint64_t> Val_O_CREAT;
40 public:
41 UnixAPIChecker() { memset(BTypes, 0, sizeof(*BTypes) * NumChecks); }
42 static void *getTag() { static unsigned tag = 0; return &tag; }
44 void PreVisitCallExpr(CheckerContext &C, const CallExpr *CE);
46 } //end anonymous namespace
48 void clang::RegisterUnixAPIChecker(GRExprEngine &Eng) {
49 Eng.registerCheck(new UnixAPIChecker());
52 //===----------------------------------------------------------------------===//
53 // Utility functions.
54 //===----------------------------------------------------------------------===//
56 static inline void LazyInitialize(BugType *&BT, const char *name) {
57 if (BT)
58 return;
59 BT = new BugType(name, "Unix API");
62 //===----------------------------------------------------------------------===//
63 // "open" (man 2 open)
64 //===----------------------------------------------------------------------===//
66 static 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;
81 LazyInitialize(BT, "Improper use of 'open'");
83 // Look at the 'oflags' argument for the O_CREAT flag.
84 const GRState *state = C.getState();
86 if (CE->getNumArgs() < 2) {
87 // The frontend should issue a warning for this case, so this is a sanity
88 // check.
89 return;
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;
100 NonLoc oflags = cast<NonLoc>(V);
101 NonLoc ocreateFlag =
102 cast<NonLoc>(C.getSValBuilder().makeIntVal(UC.Val_O_CREAT.getValue(),
103 oflagsEx->getType()));
104 SVal maskedFlagsUC = C.getSValBuilder().evalBinOpNN(state, BO_And,
105 oflags, ocreateFlag,
106 oflagsEx->getType());
107 if (maskedFlagsUC.isUnknownOrUndef())
108 return;
109 DefinedSVal maskedFlags = cast<DefinedSVal>(maskedFlagsUC);
111 // Check if maskedFlags is non-zero.
112 const GRState *trueState, *falseState;
113 llvm::tie(trueState, falseState) = state->assume(maskedFlags);
115 // Only emit an error if the value of 'maskedFlags' is properly
116 // constrained;
117 if (!(trueState && !falseState))
118 return;
120 if (CE->getNumArgs() < 3) {
121 ExplodedNode *N = C.generateSink(trueState);
122 if (!N)
123 return;
125 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);
134 //===----------------------------------------------------------------------===//
135 // pthread_once
136 //===----------------------------------------------------------------------===//
138 static void CheckPthreadOnce(CheckerContext &C, UnixAPIChecker &,
139 const CallExpr *CE, BugType *&BT) {
141 // This is similar to 'CheckDispatchOnce' in the MacOSXAPIChecker.
142 // They can possibly be refactored.
144 LazyInitialize(BT, "Improper use of 'pthread_once'");
146 if (CE->getNumArgs() < 1)
147 return;
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;
156 ExplodedNode *N = C.generateSink(state);
157 if (!N)
158 return;
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'?";
172 EnhancedBugReport *report = new EnhancedBugReport(*BT, os.str(), N);
173 report->addRange(CE->getArg(0)->getSourceRange());
174 C.EmitReport(report);
177 //===----------------------------------------------------------------------===//
178 // "malloc" with allocation size 0
179 //===----------------------------------------------------------------------===//
181 // FIXME: Eventually this should be rolled into the MallocChecker, but this
182 // check is more basic and is valuable for widespread use.
183 static void CheckMallocZero(CheckerContext &C, UnixAPIChecker &UC,
184 const CallExpr *CE, BugType *&BT) {
186 // Sanity check that malloc takes one argument.
187 if (CE->getNumArgs() != 1)
188 return;
190 // Check if the allocation size is 0.
191 const GRState *state = C.getState();
192 SVal argVal = state->getSVal(CE->getArg(0));
194 if (argVal.isUnknownOrUndef())
195 return;
197 const GRState *trueState, *falseState;
198 llvm::tie(trueState, falseState) = state->assume(cast<DefinedSVal>(argVal));
200 // Is the value perfectly constrained to zero?
201 if (falseState && !trueState) {
202 ExplodedNode *N = C.generateSink(falseState);
203 if (!N)
204 return;
206 // FIXME: Add reference to CERT advisory, and/or C99 standard in bug
207 // output.
209 LazyInitialize(BT, "Undefined allocation of 0 bytes");
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;
220 // Assume the the value is non-zero going forward.
221 assert(trueState);
222 if (trueState != state) {
223 C.addTransition(trueState);
227 //===----------------------------------------------------------------------===//
228 // Central dispatch function.
229 //===----------------------------------------------------------------------===//
231 typedef void (*SubChecker)(CheckerContext &C, UnixAPIChecker &UC,
232 const CallExpr *CE, BugType *&BT);
233 namespace {
234 class SubCheck {
235 SubChecker SC;
236 UnixAPIChecker *UC;
237 BugType **BT;
238 public:
239 SubCheck(SubChecker sc, UnixAPIChecker *uc, BugType *& bt) : SC(sc), UC(uc),
240 BT(&bt) {}
241 SubCheck() : SC(NULL), UC(NULL), BT(NULL) {}
243 void run(CheckerContext &C, const CallExpr *CE) const {
244 if (SC)
245 SC(C, *UC, CE, *BT);
248 } // end anonymous namespace
250 void 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());
258 if (!Fn)
259 return;
261 const IdentifierInfo *FI = Fn->getDecl()->getIdentifier();
262 if (!FI)
263 return;
265 const SubCheck &SC =
266 llvm::StringSwitch<SubCheck>(FI->getName())
267 .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]))
273 .Default(SubCheck());
275 SC.run(C, CE);