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 "GRExprEngineInternalChecks.h"
16 #include "clang/Basic/TargetInfo.h"
17 #include "clang/Checker/BugReporter/BugType.h"
18 #include "clang/Checker/PathSensitive/CheckerVisitor.h"
19 #include "llvm/ADT/Optional.h"
20 #include "llvm/ADT/StringSwitch.h"
23 using namespace clang
;
27 class UnixAPIChecker
: public CheckerVisitor
<UnixAPIChecker
> {
35 BugType
*BTypes
[NumChecks
];
38 Optional
<uint64_t> Val_O_CREAT
;
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 //===----------------------------------------------------------------------===//
54 //===----------------------------------------------------------------------===//
56 static inline void LazyInitialize(BugType
*&BT
, const char *name
) {
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;
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.
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
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.
100 NonLoc oflags
= cast
<NonLoc
>(V
);
102 cast
<NonLoc
>(C
.getValueManager().makeIntVal(UC
.Val_O_CREAT
.getValue(),
103 oflagsEx
->getType()));
104 SVal maskedFlagsUC
= C
.getSValuator().EvalBinOpNN(state
, BO_And
,
106 oflagsEx
->getType());
107 if (maskedFlagsUC
.isUnknownOrUndef())
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
117 if (!(trueState
&& !falseState
))
120 if (CE
->getNumArgs() < 3) {
121 ExplodedNode
*N
= C
.GenerateSink(trueState
);
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 //===----------------------------------------------------------------------===//
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)
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()))
156 ExplodedNode
*N
= C
.GenerateSink(state
);
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() << '\'';
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)
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())
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
);
206 // FIXME: Add reference to CERT advisory, and/or C99 standard in bug
209 LazyInitialize(BT
, "Undefined allocation of 0 bytes");
211 EnhancedBugReport
*report
=
212 new EnhancedBugReport(*BT
, "Call to 'malloc' has an allocation size"
214 report
->addRange(CE
->getArg(0)->getSourceRange());
215 report
->addVisitorCreator(bugreporter::registerTrackNullOrUndefValue
,
217 C
.EmitReport(report
);
220 // Assume the the value is non-zero going forward.
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
);
239 SubCheck(SubChecker sc
, UnixAPIChecker
*uc
, BugType
*& bt
) : SC(sc
), UC(uc
),
241 SubCheck() : SC(NULL
), UC(NULL
), BT(NULL
) {}
243 void run(CheckerContext
&C
, const CallExpr
*CE
) const {
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());
261 const IdentifierInfo
*FI
= Fn
->getDecl()->getIdentifier();
266 llvm::StringSwitch
<SubCheck
>(FI
->getName())
268 SubCheck(CheckOpen
, this, BTypes
[OpenFn
]))
269 .Case("pthread_once",
270 SubCheck(CheckPthreadOnce
, this, BTypes
[PthreadOnceFn
]))
272 SubCheck(CheckMallocZero
, this, BTypes
[MallocZero
]))
273 .Default(SubCheck());