blob: 328e8a650df1d65ae72fd3f34f3f1eb754bc00f6 [file] [log] [blame]
Ted Kremenek53500662009-07-22 17:55:28 +00001// BugReporterVisitors.cpp - Helpers for reporting bugs -----------*- 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 file defines a set of BugReporter "visitors" which can be used to
11// enhance the diagnostics reported for a bug.
12//
13//===----------------------------------------------------------------------===//
Anna Zaks50bbc162011-08-19 22:33:38 +000014#include "clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitor.h"
Ted Kremenek53500662009-07-22 17:55:28 +000015
16#include "clang/AST/Expr.h"
17#include "clang/AST/ExprObjC.h"
Ted Kremenek9b663712011-02-10 01:03:03 +000018#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
19#include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
Anna Zaks80de4872012-08-29 21:22:37 +000020#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
Ted Kremenek9b663712011-02-10 01:03:03 +000021#include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
Ted Kremenek18c66fd2011-08-15 22:09:50 +000022#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
Ted Kremenek681bc112011-08-16 01:53:41 +000023#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
Jordan Rose7aba1172012-08-28 00:50:42 +000024#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
Benjamin Kramer8fe83e12012-02-04 13:45:25 +000025#include "llvm/ADT/SmallString.h"
Jordan Rose85e99372012-09-22 01:24:46 +000026#include "llvm/ADT/StringExtras.h"
Ted Kremenek53500662009-07-22 17:55:28 +000027
28using namespace clang;
Ted Kremenek9ef65372010-12-23 07:20:52 +000029using namespace ento;
Ted Kremenek53500662009-07-22 17:55:28 +000030
31//===----------------------------------------------------------------------===//
32// Utility functions.
33//===----------------------------------------------------------------------===//
34
Anna Zaks9b925ac2012-09-05 23:41:54 +000035bool bugreporter::isDeclRefExprToReference(const Expr *E) {
36 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
37 return DRE->getDecl()->getType()->isReferenceType();
38 }
39 return false;
40}
41
Argyrios Kyrtzidis5a4f98f2010-12-22 18:53:20 +000042const Stmt *bugreporter::GetDerefExpr(const ExplodedNode *N) {
Ted Kremenek53500662009-07-22 17:55:28 +000043 // Pattern match for a few useful cases (do something smarter later):
44 // a[0], p->f, *p
Jordan Rose3682f1e2012-08-25 01:06:23 +000045 const PostStmt *Loc = N->getLocationAs<PostStmt>();
46 if (!Loc)
47 return 0;
48
Jordan Rose364b9f92012-08-27 20:18:30 +000049 const Expr *S = dyn_cast<Expr>(Loc->getStmt());
50 if (!S)
51 return 0;
52 S = S->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +000053
Ted Kremenek11abcec2012-05-02 00:31:29 +000054 while (true) {
55 if (const BinaryOperator *B = dyn_cast<BinaryOperator>(S)) {
56 assert(B->isAssignmentOp());
57 S = B->getLHS()->IgnoreParenCasts();
58 continue;
59 }
60 else if (const UnaryOperator *U = dyn_cast<UnaryOperator>(S)) {
61 if (U->getOpcode() == UO_Deref)
62 return U->getSubExpr()->IgnoreParenCasts();
63 }
64 else if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
Anna Zaks9b925ac2012-09-05 23:41:54 +000065 if (ME->isArrow() || isDeclRefExprToReference(ME->getBase())) {
Anna Zaksd91696e2012-09-05 22:31:55 +000066 return ME->getBase()->IgnoreParenCasts();
67 }
Ted Kremenek11abcec2012-05-02 00:31:29 +000068 }
Jordan Rose991bcb42012-09-22 01:24:38 +000069 else if (const ObjCIvarRefExpr *IvarRef = dyn_cast<ObjCIvarRefExpr>(S)) {
70 return IvarRef->getBase()->IgnoreParenCasts();
71 }
Ted Kremenek11abcec2012-05-02 00:31:29 +000072 else if (const ArraySubscriptExpr *AE = dyn_cast<ArraySubscriptExpr>(S)) {
73 return AE->getBase();
74 }
75 break;
Ted Kremenek53500662009-07-22 17:55:28 +000076 }
Mike Stump1eb44332009-09-09 15:08:12 +000077
78 return NULL;
Ted Kremenek53500662009-07-22 17:55:28 +000079}
80
Argyrios Kyrtzidis5a4f98f2010-12-22 18:53:20 +000081const Stmt *bugreporter::GetDenomExpr(const ExplodedNode *N) {
Zhongxing Xu6403b572009-09-02 13:26:26 +000082 const Stmt *S = N->getLocationAs<PreStmt>()->getStmt();
Ted Kremenek53500662009-07-22 17:55:28 +000083 if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(S))
84 return BE->getRHS();
85 return NULL;
86}
87
Argyrios Kyrtzidis5a4f98f2010-12-22 18:53:20 +000088const Stmt *bugreporter::GetRetValExpr(const ExplodedNode *N) {
Ted Kremenek53500662009-07-22 17:55:28 +000089 const Stmt *S = N->getLocationAs<PostStmt>()->getStmt();
90 if (const ReturnStmt *RS = dyn_cast<ReturnStmt>(S))
91 return RS->getRetValue();
92 return NULL;
93}
94
95//===----------------------------------------------------------------------===//
96// Definitions for bug reporter visitors.
97//===----------------------------------------------------------------------===//
Anna Zaks23f395e2011-08-20 01:27:22 +000098
99PathDiagnosticPiece*
100BugReporterVisitor::getEndPath(BugReporterContext &BRC,
101 const ExplodedNode *EndPathNode,
102 BugReport &BR) {
103 return 0;
104}
105
106PathDiagnosticPiece*
107BugReporterVisitor::getDefaultEndPath(BugReporterContext &BRC,
108 const ExplodedNode *EndPathNode,
109 BugReport &BR) {
Anna Zaks5a0917d2012-02-16 03:41:01 +0000110 PathDiagnosticLocation L =
111 PathDiagnosticLocation::createEndOfPath(EndPathNode,BRC.getSourceManager());
Anna Zaks23f395e2011-08-20 01:27:22 +0000112
113 BugReport::ranges_iterator Beg, End;
114 llvm::tie(Beg, End) = BR.getRanges();
115
116 // Only add the statement itself as a range if we didn't specify any
117 // special ranges for this report.
118 PathDiagnosticPiece *P = new PathDiagnosticEventPiece(L,
119 BR.getDescription(),
120 Beg == End);
121 for (; Beg != End; ++Beg)
122 P->addRange(*Beg);
123
124 return P;
125}
126
127
Jordan Rose7aba1172012-08-28 00:50:42 +0000128namespace {
129/// Emits an extra note at the return statement of an interesting stack frame.
130///
131/// The returned value is marked as an interesting value, and if it's null,
132/// adds a visitor to track where it became null.
133///
134/// This visitor is intended to be used when another visitor discovers that an
135/// interesting value comes from an inlined function call.
136class ReturnVisitor : public BugReporterVisitorImpl<ReturnVisitor> {
137 const StackFrameContext *StackFrame;
Jordan Rose6a329ee2012-10-29 17:31:59 +0000138 enum {
139 Initial,
140 MaybeSuppress,
141 Satisfied
142 } Mode;
143
Jordan Rose7aba1172012-08-28 00:50:42 +0000144public:
145 ReturnVisitor(const StackFrameContext *Frame)
Jordan Rose6a329ee2012-10-29 17:31:59 +0000146 : StackFrame(Frame), Mode(Initial) {}
Jordan Rose7aba1172012-08-28 00:50:42 +0000147
Jordan Roseb9d4e5e2012-09-22 01:25:06 +0000148 static void *getTag() {
Jordan Rose7aba1172012-08-28 00:50:42 +0000149 static int Tag = 0;
Jordan Roseb9d4e5e2012-09-22 01:25:06 +0000150 return static_cast<void *>(&Tag);
151 }
152
153 virtual void Profile(llvm::FoldingSetNodeID &ID) const {
154 ID.AddPointer(ReturnVisitor::getTag());
Jordan Rose7aba1172012-08-28 00:50:42 +0000155 ID.AddPointer(StackFrame);
156 }
157
158 /// Adds a ReturnVisitor if the given statement represents a call that was
159 /// inlined.
160 ///
161 /// This will search back through the ExplodedGraph, starting from the given
162 /// node, looking for when the given statement was processed. If it turns out
163 /// the statement is a call that was inlined, we add the visitor to the
164 /// bug report, so it can print a note later.
165 static void addVisitorIfNecessary(const ExplodedNode *Node, const Stmt *S,
166 BugReport &BR) {
167 if (!CallEvent::isCallStmt(S))
168 return;
169
170 // First, find when we processed the statement.
171 do {
172 if (const CallExitEnd *CEE = Node->getLocationAs<CallExitEnd>())
173 if (CEE->getCalleeContext()->getCallSite() == S)
174 break;
175 if (const StmtPoint *SP = Node->getLocationAs<StmtPoint>())
176 if (SP->getStmt() == S)
177 break;
178
179 Node = Node->getFirstPred();
180 } while (Node);
181
182 // Next, step over any post-statement checks.
183 while (Node && isa<PostStmt>(Node->getLocation()))
184 Node = Node->getFirstPred();
185
186 // Finally, see if we inlined the call.
Jordan Rose53221da2012-09-22 01:25:00 +0000187 if (Node) {
188 if (const CallExitEnd *CEE = Node->getLocationAs<CallExitEnd>()) {
189 const StackFrameContext *CalleeContext = CEE->getCalleeContext();
190 if (CalleeContext->getCallSite() == S) {
191 BR.markInteresting(CalleeContext);
192 BR.addVisitor(new ReturnVisitor(CalleeContext));
193 }
194 }
195 }
Jordan Rose7aba1172012-08-28 00:50:42 +0000196 }
197
Jordan Rose6a329ee2012-10-29 17:31:59 +0000198 /// Returns true if any counter-suppression heuristics are enabled for
199 /// ReturnVisitor.
200 static bool hasCounterSuppression(AnalyzerOptions &Options) {
201 return Options.shouldAvoidSuppressingNullArgumentPaths();
202 }
Jordan Rose7aba1172012-08-28 00:50:42 +0000203
Jordan Rose6a329ee2012-10-29 17:31:59 +0000204 PathDiagnosticPiece *visitNodeInitial(const ExplodedNode *N,
205 const ExplodedNode *PrevN,
206 BugReporterContext &BRC,
207 BugReport &BR) {
Jordan Rose7aba1172012-08-28 00:50:42 +0000208 // Only print a message at the interesting return statement.
209 if (N->getLocationContext() != StackFrame)
210 return 0;
211
212 const StmtPoint *SP = N->getLocationAs<StmtPoint>();
213 if (!SP)
214 return 0;
215
216 const ReturnStmt *Ret = dyn_cast<ReturnStmt>(SP->getStmt());
217 if (!Ret)
218 return 0;
219
220 // Okay, we're at the right return statement, but do we have the return
221 // value available?
222 ProgramStateRef State = N->getState();
223 SVal V = State->getSVal(Ret, StackFrame);
224 if (V.isUnknownOrUndef())
225 return 0;
226
227 // Don't print any more notes after this one.
Jordan Rose6a329ee2012-10-29 17:31:59 +0000228 Mode = Satisfied;
Jordan Rose7aba1172012-08-28 00:50:42 +0000229
Jordan Rose7aba1172012-08-28 00:50:42 +0000230 const Expr *RetE = Ret->getRetValue();
231 assert(RetE && "Tracking a return value for a void function");
232 RetE = RetE->IgnoreParenCasts();
233
Jordan Rose53221da2012-09-22 01:25:00 +0000234 // If we can't prove the return value is 0, just mark it interesting, and
235 // make sure to track it into any further inner functions.
236 if (State->assume(cast<DefinedSVal>(V), true)) {
Jordan Rose7aba1172012-08-28 00:50:42 +0000237 BR.markInteresting(V);
Jordan Rose53221da2012-09-22 01:25:00 +0000238 ReturnVisitor::addVisitorIfNecessary(N, RetE, BR);
239 return 0;
240 }
241
242 // If we're returning 0, we should track where that 0 came from.
243 bugreporter::trackNullOrUndefValue(N, RetE, BR);
244
Jordan Roseb9d4e5e2012-09-22 01:25:06 +0000245 // Build an appropriate message based on the return value.
246 SmallString<64> Msg;
247 llvm::raw_svector_ostream Out(Msg);
248
Jordan Rose53221da2012-09-22 01:25:00 +0000249 if (isa<Loc>(V)) {
Jordan Roseb9d4e5e2012-09-22 01:25:06 +0000250 // If we are pruning null-return paths as unlikely error paths, mark the
251 // report invalid. We still want to emit a path note, however, in case
252 // the report is resurrected as valid later on.
253 ExprEngine &Eng = BRC.getBugReporter().getEngine();
Jordan Rose6a329ee2012-10-29 17:31:59 +0000254 AnalyzerOptions &Options = Eng.getAnalysisManager().options;
255 if (Options.shouldPruneNullReturnPaths()) {
256 if (hasCounterSuppression(Options))
257 Mode = MaybeSuppress;
258 else
259 BR.markInvalid(ReturnVisitor::getTag(), StackFrame);
260 }
Jordan Roseb9d4e5e2012-09-22 01:25:06 +0000261
Jordan Rose53221da2012-09-22 01:25:00 +0000262 if (RetE->getType()->isObjCObjectPointerType())
263 Out << "Returning nil";
264 else
265 Out << "Returning null pointer";
266 } else {
267 Out << "Returning zero";
Jordan Rose7aba1172012-08-28 00:50:42 +0000268 }
269
270 // FIXME: We should have a more generalized location printing mechanism.
271 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(RetE))
272 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(DR->getDecl()))
273 Out << " (loaded from '" << *DD << "')";
274
275 PathDiagnosticLocation L(Ret, BRC.getSourceManager(), StackFrame);
276 return new PathDiagnosticEventPiece(L, Out.str());
277 }
Jordan Rose6a329ee2012-10-29 17:31:59 +0000278
279 PathDiagnosticPiece *visitNodeMaybeSuppress(const ExplodedNode *N,
280 const ExplodedNode *PrevN,
281 BugReporterContext &BRC,
282 BugReport &BR) {
283 // Are we at the entry node for this call?
284 const CallEnter *CE = N->getLocationAs<CallEnter>();
285 if (!CE)
286 return 0;
287
288 if (CE->getCalleeContext() != StackFrame)
289 return 0;
290
291 Mode = Satisfied;
292
293 ExprEngine &Eng = BRC.getBugReporter().getEngine();
294 AnalyzerOptions &Options = Eng.getAnalysisManager().options;
295 if (Options.shouldAvoidSuppressingNullArgumentPaths()) {
296 // Don't automatically suppress a report if one of the arguments is
297 // known to be a null pointer. Instead, start tracking /that/ null
298 // value back to its origin.
299 ProgramStateManager &StateMgr = BRC.getStateManager();
300 CallEventManager &CallMgr = StateMgr.getCallEventManager();
301
302 ProgramStateRef State = N->getState();
303 CallEventRef<> Call = CallMgr.getCaller(StackFrame, State);
304 for (unsigned I = 0, E = Call->getNumArgs(); I != E; ++I) {
305 SVal ArgV = Call->getArgSVal(I);
306 if (!isa<Loc>(ArgV))
307 continue;
308
309 const Expr *ArgE = Call->getArgExpr(I);
310 if (!ArgE)
311 continue;
312
313 // Is it possible for this argument to be non-null?
314 if (State->assume(cast<Loc>(ArgV), true))
315 continue;
316
317 if (bugreporter::trackNullOrUndefValue(N, ArgE, BR, /*IsArg=*/true))
318 return 0;
319
320 // If we /can't/ track the null pointer, we should err on the side of
321 // false negatives, and continue towards marking this report invalid.
322 // (We will still look at the other arguments, though.)
323 }
324 }
325
326 // There is no reason not to suppress this report; go ahead and do it.
327 BR.markInvalid(ReturnVisitor::getTag(), StackFrame);
328 return 0;
329 }
330
331 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
332 const ExplodedNode *PrevN,
333 BugReporterContext &BRC,
334 BugReport &BR) {
335 switch (Mode) {
336 case Initial:
337 return visitNodeInitial(N, PrevN, BRC, BR);
338 case MaybeSuppress:
339 return visitNodeMaybeSuppress(N, PrevN, BRC, BR);
340 case Satisfied:
341 return 0;
342 }
343
344 llvm_unreachable("Invalid visit mode!");
345 }
Jordan Rose7aba1172012-08-28 00:50:42 +0000346};
347} // end anonymous namespace
348
349
Anna Zaks50bbc162011-08-19 22:33:38 +0000350void FindLastStoreBRVisitor ::Profile(llvm::FoldingSetNodeID &ID) const {
351 static int tag = 0;
352 ID.AddPointer(&tag);
353 ID.AddPointer(R);
354 ID.Add(V);
355}
Ted Kremenek53500662009-07-22 17:55:28 +0000356
Jordan Rose166b7bd2012-08-28 00:50:45 +0000357PathDiagnosticPiece *FindLastStoreBRVisitor::VisitNode(const ExplodedNode *Succ,
358 const ExplodedNode *Pred,
359 BugReporterContext &BRC,
360 BugReport &BR) {
Mike Stump1eb44332009-09-09 15:08:12 +0000361
Anna Zaks50bbc162011-08-19 22:33:38 +0000362 if (satisfied)
363 return NULL;
364
Jordan Rose166b7bd2012-08-28 00:50:45 +0000365 const ExplodedNode *StoreSite = 0;
366 const Expr *InitE = 0;
Jordan Rose09f7bf12012-10-29 17:31:53 +0000367 bool IsParam = false;
Anna Zaks50bbc162011-08-19 22:33:38 +0000368
Jordan Rose166b7bd2012-08-28 00:50:45 +0000369 // First see if we reached the declaration of the region.
370 if (const VarRegion *VR = dyn_cast<VarRegion>(R)) {
371 if (const PostStmt *P = Pred->getLocationAs<PostStmt>()) {
372 if (const DeclStmt *DS = P->getStmtAs<DeclStmt>()) {
373 if (DS->getSingleDecl() == VR->getDecl()) {
374 StoreSite = Pred;
375 InitE = VR->getDecl()->getInit();
Jordan Rose7aba1172012-08-28 00:50:42 +0000376 }
Jordan Rose7aba1172012-08-28 00:50:42 +0000377 }
Jordan Rose7aba1172012-08-28 00:50:42 +0000378 }
Ted Kremenek1b431022010-03-20 18:01:57 +0000379 }
380
Jordan Rose166b7bd2012-08-28 00:50:45 +0000381 // Otherwise, check that Succ has this binding and Pred does not, i.e. this is
382 // where the binding first occurred.
383 if (!StoreSite) {
384 if (Succ->getState()->getSVal(R) != V)
385 return NULL;
386 if (Pred->getState()->getSVal(R) == V)
387 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +0000388
Jordan Rose166b7bd2012-08-28 00:50:45 +0000389 StoreSite = Succ;
390
391 // If this is an assignment expression, we can track the value
392 // being assigned.
393 if (const PostStmt *P = Succ->getLocationAs<PostStmt>())
394 if (const BinaryOperator *BO = P->getStmtAs<BinaryOperator>())
395 if (BO->isAssignmentOp())
396 InitE = BO->getRHS();
Jordan Rose85e99372012-09-22 01:24:46 +0000397
398 // If this is a call entry, the variable should be a parameter.
399 // FIXME: Handle CXXThisRegion as well. (This is not a priority because
400 // 'this' should never be NULL, but this visitor isn't just for NULL and
401 // UndefinedVal.)
402 if (const CallEnter *CE = Succ->getLocationAs<CallEnter>()) {
403 const VarRegion *VR = cast<VarRegion>(R);
404 const ParmVarDecl *Param = cast<ParmVarDecl>(VR->getDecl());
405
406 ProgramStateManager &StateMgr = BRC.getStateManager();
407 CallEventManager &CallMgr = StateMgr.getCallEventManager();
408
409 CallEventRef<> Call = CallMgr.getCaller(CE->getCalleeContext(),
410 Succ->getState());
411 InitE = Call->getArgExpr(Param->getFunctionScopeIndex());
Jordan Rose09f7bf12012-10-29 17:31:53 +0000412 IsParam = true;
Jordan Rose85e99372012-09-22 01:24:46 +0000413 }
Jordan Rose166b7bd2012-08-28 00:50:45 +0000414 }
415
416 if (!StoreSite)
417 return NULL;
Anna Zaks50bbc162011-08-19 22:33:38 +0000418 satisfied = true;
Jordan Rose166b7bd2012-08-28 00:50:45 +0000419
Jordan Rose53221da2012-09-22 01:25:00 +0000420 // If we have an expression that provided the value, try to track where it
421 // came from.
Jordan Rose166b7bd2012-08-28 00:50:45 +0000422 if (InitE) {
Jordan Rose09f7bf12012-10-29 17:31:53 +0000423 if (V.isUndef() || isa<loc::ConcreteInt>(V)) {
424 if (!IsParam)
425 InitE = InitE->IgnoreParenCasts();
426 bugreporter::trackNullOrUndefValue(StoreSite, InitE, BR, IsParam);
427 } else {
428 ReturnVisitor::addVisitorIfNecessary(StoreSite, InitE->IgnoreParenCasts(),
429 BR);
430 }
Jordan Rose166b7bd2012-08-28 00:50:45 +0000431 }
432
Jordan Rose85e99372012-09-22 01:24:46 +0000433 if (!R->canPrintPretty())
434 return 0;
435
Jordan Rose166b7bd2012-08-28 00:50:45 +0000436 // Okay, we've found the binding. Emit an appropriate message.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000437 SmallString<256> sbuf;
Anna Zaks50bbc162011-08-19 22:33:38 +0000438 llvm::raw_svector_ostream os(sbuf);
Mike Stump1eb44332009-09-09 15:08:12 +0000439
Jordan Rose166b7bd2012-08-28 00:50:45 +0000440 if (const PostStmt *PS = StoreSite->getLocationAs<PostStmt>()) {
Anna Zaks50bbc162011-08-19 22:33:38 +0000441 if (const DeclStmt *DS = PS->getStmtAs<DeclStmt>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000442
Anna Zaks50bbc162011-08-19 22:33:38 +0000443 if (const VarRegion *VR = dyn_cast<VarRegion>(R)) {
Benjamin Kramerb8989f22011-10-14 18:45:37 +0000444 os << "Variable '" << *VR->getDecl() << "' ";
Ted Kremenek53500662009-07-22 17:55:28 +0000445 }
Anna Zaks50bbc162011-08-19 22:33:38 +0000446 else
Ted Kremenek53500662009-07-22 17:55:28 +0000447 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +0000448
Ted Kremenek53500662009-07-22 17:55:28 +0000449 if (isa<loc::ConcreteInt>(V)) {
450 bool b = false;
Ted Kremenek53500662009-07-22 17:55:28 +0000451 if (R->isBoundable()) {
Ted Kremenek96979342011-08-12 20:02:48 +0000452 if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R)) {
Zhongxing Xu018220c2010-08-11 06:10:55 +0000453 if (TR->getValueType()->isObjCObjectPointerType()) {
Anna Zaks50bbc162011-08-19 22:33:38 +0000454 os << "initialized to nil";
Ted Kremenek53500662009-07-22 17:55:28 +0000455 b = true;
456 }
457 }
458 }
Mike Stump1eb44332009-09-09 15:08:12 +0000459
Ted Kremenek53500662009-07-22 17:55:28 +0000460 if (!b)
Anna Zaks50bbc162011-08-19 22:33:38 +0000461 os << "initialized to a null pointer value";
Ted Kremenek53500662009-07-22 17:55:28 +0000462 }
Ted Kremenek592362b2009-08-18 01:05:30 +0000463 else if (isa<nonloc::ConcreteInt>(V)) {
Anna Zaks50bbc162011-08-19 22:33:38 +0000464 os << "initialized to " << cast<nonloc::ConcreteInt>(V).getValue();
Ted Kremenek592362b2009-08-18 01:05:30 +0000465 }
Anna Zaks50bbc162011-08-19 22:33:38 +0000466 else if (V.isUndef()) {
467 if (isa<VarRegion>(R)) {
468 const VarDecl *VD = cast<VarDecl>(DS->getSingleDecl());
469 if (VD->getInit())
470 os << "initialized to a garbage value";
471 else
472 os << "declared without an initial value";
473 }
Ted Kremenek53500662009-07-22 17:55:28 +0000474 }
Jordan Rose68537992012-08-03 23:09:01 +0000475 else {
476 os << "initialized here";
477 }
Ted Kremenek53500662009-07-22 17:55:28 +0000478 }
Jordan Rose85e99372012-09-22 01:24:46 +0000479 } else if (isa<CallEnter>(StoreSite->getLocation())) {
480 const ParmVarDecl *Param = cast<ParmVarDecl>(cast<VarRegion>(R)->getDecl());
481
482 os << "Passing ";
483
484 if (isa<loc::ConcreteInt>(V)) {
485 if (Param->getType()->isObjCObjectPointerType())
486 os << "nil object reference";
487 else
488 os << "null pointer value";
489 } else if (V.isUndef()) {
490 os << "uninitialized value";
491 } else if (isa<nonloc::ConcreteInt>(V)) {
492 os << "the value " << cast<nonloc::ConcreteInt>(V).getValue();
493 } else {
494 os << "value";
495 }
496
497 // Printed parameter indexes are 1-based, not 0-based.
498 unsigned Idx = Param->getFunctionScopeIndex() + 1;
499 os << " via " << Idx << llvm::getOrdinalSuffix(Idx) << " parameter '";
500
501 R->printPretty(os);
502 os << '\'';
Anna Zaks50bbc162011-08-19 22:33:38 +0000503 }
504
505 if (os.str().empty()) {
506 if (isa<loc::ConcreteInt>(V)) {
507 bool b = false;
508 if (R->isBoundable()) {
509 if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R)) {
510 if (TR->getValueType()->isObjCObjectPointerType()) {
511 os << "nil object reference stored to ";
512 b = true;
513 }
514 }
515 }
516
517 if (!b)
518 os << "Null pointer value stored to ";
519 }
520 else if (V.isUndef()) {
521 os << "Uninitialized value stored to ";
522 }
523 else if (isa<nonloc::ConcreteInt>(V)) {
524 os << "The value " << cast<nonloc::ConcreteInt>(V).getValue()
525 << " is assigned to ";
526 }
527 else
Jordan Rose68537992012-08-03 23:09:01 +0000528 os << "Value assigned to ";
Anna Zaks50bbc162011-08-19 22:33:38 +0000529
Jordan Rose85e99372012-09-22 01:24:46 +0000530 os << '\'';
531 R->printPretty(os);
532 os << '\'';
Anna Zaks50bbc162011-08-19 22:33:38 +0000533 }
534
Anna Zaks50bbc162011-08-19 22:33:38 +0000535 // Construct a new PathDiagnosticPiece.
Jordan Rose166b7bd2012-08-28 00:50:45 +0000536 ProgramPoint P = StoreSite->getLocation();
Jordan Rose85e99372012-09-22 01:24:46 +0000537 PathDiagnosticLocation L;
538 if (isa<CallEnter>(P))
539 L = PathDiagnosticLocation(InitE, BRC.getSourceManager(),
540 P.getLocationContext());
541 else
542 L = PathDiagnosticLocation::create(P, BRC.getSourceManager());
Anna Zaks4fdf97b2011-09-15 18:56:07 +0000543 if (!L.isValid())
544 return NULL;
Anna Zaks50bbc162011-08-19 22:33:38 +0000545 return new PathDiagnosticEventPiece(L, os.str());
546}
547
548void TrackConstraintBRVisitor::Profile(llvm::FoldingSetNodeID &ID) const {
549 static int tag = 0;
550 ID.AddPointer(&tag);
551 ID.AddBoolean(Assumption);
552 ID.Add(Constraint);
553}
554
Ted Kremenekb85cce02012-10-25 22:07:10 +0000555/// Return the tag associated with this visitor. This tag will be used
556/// to make all PathDiagnosticPieces created by this visitor.
557const char *TrackConstraintBRVisitor::getTag() {
558 return "TrackConstraintBRVisitor";
559}
560
Anna Zaks50bbc162011-08-19 22:33:38 +0000561PathDiagnosticPiece *
562TrackConstraintBRVisitor::VisitNode(const ExplodedNode *N,
563 const ExplodedNode *PrevN,
564 BugReporterContext &BRC,
565 BugReport &BR) {
566 if (isSatisfied)
567 return NULL;
568
569 // Check if in the previous state it was feasible for this constraint
570 // to *not* be true.
571 if (PrevN->getState()->assume(Constraint, !Assumption)) {
572
573 isSatisfied = true;
574
575 // As a sanity check, make sure that the negation of the constraint
576 // was infeasible in the current state. If it is feasible, we somehow
577 // missed the transition point.
578 if (N->getState()->assume(Constraint, !Assumption))
579 return NULL;
580
581 // We found the transition point for the constraint. We now need to
582 // pretty-print the constraint. (work-in-progress)
583 std::string sbuf;
584 llvm::raw_string_ostream os(sbuf);
585
586 if (isa<Loc>(Constraint)) {
587 os << "Assuming pointer value is ";
588 os << (Assumption ? "non-null" : "null");
589 }
590
591 if (os.str().empty())
592 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +0000593
Ted Kremenek53500662009-07-22 17:55:28 +0000594 // Construct a new PathDiagnosticPiece.
Anna Zaks4fdf97b2011-09-15 18:56:07 +0000595 ProgramPoint P = N->getLocation();
Anna Zaks1531bb02011-09-20 01:38:47 +0000596 PathDiagnosticLocation L =
597 PathDiagnosticLocation::create(P, BRC.getSourceManager());
Anna Zaks4fdf97b2011-09-15 18:56:07 +0000598 if (!L.isValid())
599 return NULL;
Ted Kremenekb85cce02012-10-25 22:07:10 +0000600
601 PathDiagnosticEventPiece *X = new PathDiagnosticEventPiece(L, os.str());
602 X->setTag(getTag());
603 return X;
Ted Kremenek53500662009-07-22 17:55:28 +0000604 }
Ted Kremenek53500662009-07-22 17:55:28 +0000605
Anna Zaks50bbc162011-08-19 22:33:38 +0000606 return NULL;
Ted Kremenek53500662009-07-22 17:55:28 +0000607}
608
Jordan Rose6a329ee2012-10-29 17:31:59 +0000609bool bugreporter::trackNullOrUndefValue(const ExplodedNode *N, const Stmt *S,
Jordan Rose09f7bf12012-10-29 17:31:53 +0000610 BugReport &report, bool IsArg) {
Anna Zaks50bbc162011-08-19 22:33:38 +0000611 if (!S || !N)
Jordan Rose6a329ee2012-10-29 17:31:59 +0000612 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000613
Jordan Rose6686b662012-09-22 01:24:49 +0000614 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(S))
615 S = OVE->getSourceExpr();
616
Jordan Rose09f7bf12012-10-29 17:31:53 +0000617 if (IsArg) {
618 assert(isa<CallEnter>(N->getLocation()) && "Tracking arg but not at call");
619 } else {
620 // Walk through nodes until we get one that matches the statement exactly.
621 do {
622 const ProgramPoint &pp = N->getLocation();
623 if (const PostStmt *ps = dyn_cast<PostStmt>(&pp)) {
624 if (ps->getStmt() == S)
625 break;
626 } else if (const CallExitEnd *CEE = dyn_cast<CallExitEnd>(&pp)) {
627 if (CEE->getCalleeContext()->getCallSite() == S)
628 break;
629 }
630 N = N->getFirstPred();
631 } while (N);
Anna Zaks8e6431a2011-08-18 22:37:56 +0000632
Jordan Rose09f7bf12012-10-29 17:31:53 +0000633 if (!N)
Jordan Rose6a329ee2012-10-29 17:31:59 +0000634 return false;
Ted Kremenek88299892011-07-28 23:07:59 +0000635 }
Ted Kremenek88299892011-07-28 23:07:59 +0000636
Ted Kremenek8bef8232012-01-26 21:29:00 +0000637 ProgramStateRef state = N->getState();
Mike Stump1eb44332009-09-09 15:08:12 +0000638
Jordan Rose364b9f92012-08-27 20:18:30 +0000639 // See if the expression we're interested refers to a variable.
640 // If so, we can track both its contents and constraints on its value.
641 if (const Expr *Ex = dyn_cast<Expr>(S)) {
642 // Strip off parens and casts. Note that this will never have issues with
643 // C++ user-defined implicit conversions, because those have a constructor
644 // or function call inside.
Jordan Rosee6cd0542012-08-16 00:03:33 +0000645 Ex = Ex->IgnoreParenCasts();
Ted Kremenek76aadc32012-03-09 01:13:14 +0000646 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Ex)) {
Jordan Rose364b9f92012-08-27 20:18:30 +0000647 // FIXME: Right now we only track VarDecls because it's non-trivial to
648 // get a MemRegion for any other DeclRefExprs. <rdar://problem/12114812>
Ted Kremenek76aadc32012-03-09 01:13:14 +0000649 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
Jordan Rose09f7bf12012-10-29 17:31:53 +0000650 ProgramStateManager &StateMgr = state->getStateManager();
651 MemRegionManager &MRMgr = StateMgr.getRegionManager();
652 const VarRegion *R = MRMgr.getVarRegion(VD, N->getLocationContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000653
Jordan Rose364b9f92012-08-27 20:18:30 +0000654 // Mark both the variable region and its contents as interesting.
Ted Kremenek11abcec2012-05-02 00:31:29 +0000655 SVal V = state->getRawSVal(loc::MemRegionVal(R));
Jordan Rose09f7bf12012-10-29 17:31:53 +0000656
657 // If the value matches the default for the variable region, that
658 // might mean that it's been cleared out of the state. Fall back to
659 // the full argument expression (with casts and such intact).
660 if (IsArg) {
661 bool UseArgValue = V.isUnknownOrUndef() || V.isZeroConstant();
662 if (!UseArgValue) {
663 const SymbolRegionValue *SRV =
664 dyn_cast_or_null<SymbolRegionValue>(V.getAsLocSymbol());
665 if (SRV)
666 UseArgValue = (SRV->getRegion() == R);
667 }
668 if (UseArgValue)
669 V = state->getSValAsScalarOrLoc(S, N->getLocationContext());
670 }
671
Jordan Rosea1f81bb2012-08-28 00:50:51 +0000672 report.markInteresting(R);
673 report.markInteresting(V);
Anna Zaks80de4872012-08-29 21:22:37 +0000674 report.addVisitor(new UndefOrNullArgVisitor(R));
Jordan Rose68537992012-08-03 23:09:01 +0000675
Jordan Rose364b9f92012-08-27 20:18:30 +0000676 // If the contents are symbolic, find out when they became null.
Jordan Rose68537992012-08-03 23:09:01 +0000677 if (V.getAsLocSymbol()) {
678 BugReporterVisitor *ConstraintTracker
Jordan Rose53221da2012-09-22 01:25:00 +0000679 = new TrackConstraintBRVisitor(cast<DefinedSVal>(V), false);
Jordan Rosea1f81bb2012-08-28 00:50:51 +0000680 report.addVisitor(ConstraintTracker);
Jordan Rose68537992012-08-03 23:09:01 +0000681 }
682
Jordan Rosea1f81bb2012-08-28 00:50:51 +0000683 report.addVisitor(new FindLastStoreBRVisitor(V, R));
Jordan Rose6a329ee2012-10-29 17:31:59 +0000684 return true;
Ted Kremenek53500662009-07-22 17:55:28 +0000685 }
686 }
687 }
Mike Stump1eb44332009-09-09 15:08:12 +0000688
Jordan Rose364b9f92012-08-27 20:18:30 +0000689 // If the expression does NOT refer to a variable, we can still track
690 // constraints on its contents.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000691 SVal V = state->getSValAsScalarOrLoc(S, N->getLocationContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000692
Ted Kremenek53500662009-07-22 17:55:28 +0000693 // Uncomment this to find cases where we aren't properly getting the
694 // base value that was dereferenced.
695 // assert(!V.isUnknownOrUndef());
Mike Stump1eb44332009-09-09 15:08:12 +0000696
Ted Kremenek53500662009-07-22 17:55:28 +0000697 // Is it a symbolic value?
698 if (loc::MemRegionVal *L = dyn_cast<loc::MemRegionVal>(&V)) {
Anna Zaksd91696e2012-09-05 22:31:55 +0000699 // At this point we are dealing with the region's LValue.
700 // However, if the rvalue is a symbolic region, we should track it as well.
701 SVal RVal = state->getSVal(L->getRegion());
702 const MemRegion *RegionRVal = RVal.getAsRegion();
Anna Zaks522fc212012-09-12 22:57:30 +0000703 report.addVisitor(new UndefOrNullArgVisitor(L->getRegion()));
704
Anna Zaksd91696e2012-09-05 22:31:55 +0000705
706 if (RegionRVal && isa<SymbolicRegion>(RegionRVal)) {
707 report.markInteresting(RegionRVal);
708 report.addVisitor(new TrackConstraintBRVisitor(
709 loc::MemRegionVal(RegionRVal), false));
Ted Kremenek53500662009-07-22 17:55:28 +0000710 }
Jordan Rose7aba1172012-08-28 00:50:42 +0000711 } else {
712 // Otherwise, if the value came from an inlined function call,
713 // we should at least make sure that function isn't pruned in our output.
Jordan Rose53221da2012-09-22 01:25:00 +0000714 if (const Expr *E = dyn_cast<Expr>(S))
715 S = E->IgnoreParenCasts();
Jordan Rosea1f81bb2012-08-28 00:50:51 +0000716 ReturnVisitor::addVisitorIfNecessary(N, S, report);
Ted Kremenek53500662009-07-22 17:55:28 +0000717 }
Jordan Rose6a329ee2012-10-29 17:31:59 +0000718
719 return true;
Ted Kremenek53500662009-07-22 17:55:28 +0000720}
Ted Kremenek94fd0b82010-02-16 08:33:59 +0000721
Anna Zaks50bbc162011-08-19 22:33:38 +0000722BugReporterVisitor *
723FindLastStoreBRVisitor::createVisitorObject(const ExplodedNode *N,
724 const MemRegion *R) {
725 assert(R && "The memory region is null.");
Ted Kremenek94fd0b82010-02-16 08:33:59 +0000726
Ted Kremenek8bef8232012-01-26 21:29:00 +0000727 ProgramStateRef state = N->getState();
Ted Kremenek94fd0b82010-02-16 08:33:59 +0000728 SVal V = state->getSVal(R);
Ted Kremenek94fd0b82010-02-16 08:33:59 +0000729 if (V.isUnknown())
Anna Zaks50bbc162011-08-19 22:33:38 +0000730 return 0;
Ted Kremenek94fd0b82010-02-16 08:33:59 +0000731
Anna Zaks50bbc162011-08-19 22:33:38 +0000732 return new FindLastStoreBRVisitor(V, R);
Ted Kremenek94fd0b82010-02-16 08:33:59 +0000733}
Ted Kremenekff7f7362010-03-20 18:02:01 +0000734
735
Anna Zaks50bbc162011-08-19 22:33:38 +0000736PathDiagnosticPiece *NilReceiverBRVisitor::VisitNode(const ExplodedNode *N,
737 const ExplodedNode *PrevN,
738 BugReporterContext &BRC,
739 BugReport &BR) {
740 const PostStmt *P = N->getLocationAs<PostStmt>();
741 if (!P)
742 return 0;
743 const ObjCMessageExpr *ME = P->getStmtAs<ObjCMessageExpr>();
744 if (!ME)
745 return 0;
746 const Expr *Receiver = ME->getInstanceReceiver();
747 if (!Receiver)
748 return 0;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000749 ProgramStateRef state = N->getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +0000750 const SVal &V = state->getSVal(Receiver, N->getLocationContext());
Anna Zaks50bbc162011-08-19 22:33:38 +0000751 const DefinedOrUnknownSVal *DV = dyn_cast<DefinedOrUnknownSVal>(&V);
752 if (!DV)
753 return 0;
754 state = state->assume(*DV, true);
755 if (state)
756 return 0;
Ted Kremenekff7f7362010-03-20 18:02:01 +0000757
Anna Zaks50bbc162011-08-19 22:33:38 +0000758 // The receiver was nil, and hence the method was skipped.
759 // Register a BugReporterVisitor to issue a message telling us how
760 // the receiver was null.
Jordan Rosea1f81bb2012-08-28 00:50:51 +0000761 bugreporter::trackNullOrUndefValue(N, Receiver, BR);
Anna Zaks50bbc162011-08-19 22:33:38 +0000762 // Issue a message saying that the method was skipped.
Anna Zaks220ac8c2011-09-15 01:08:34 +0000763 PathDiagnosticLocation L(Receiver, BRC.getSourceManager(),
764 N->getLocationContext());
Anna Zaks907344e2012-04-05 02:10:19 +0000765 return new PathDiagnosticEventPiece(L, "No method is called "
Anna Zaks50bbc162011-08-19 22:33:38 +0000766 "because the receiver is nil");
Ted Kremenekff7f7362010-03-20 18:02:01 +0000767}
Tom Care2bbbe502010-09-02 23:30:22 +0000768
Anna Zaks8e6431a2011-08-18 22:37:56 +0000769// Registers every VarDecl inside a Stmt with a last store visitor.
Anna Zaks50bbc162011-08-19 22:33:38 +0000770void FindLastStoreBRVisitor::registerStatementVarDecls(BugReport &BR,
771 const Stmt *S) {
Anna Zaks8e6431a2011-08-18 22:37:56 +0000772 const ExplodedNode *N = BR.getErrorNode();
Tom Care2bbbe502010-09-02 23:30:22 +0000773 std::deque<const Stmt *> WorkList;
Tom Care2bbbe502010-09-02 23:30:22 +0000774 WorkList.push_back(S);
775
776 while (!WorkList.empty()) {
777 const Stmt *Head = WorkList.front();
778 WorkList.pop_front();
779
Ted Kremenek8bef8232012-01-26 21:29:00 +0000780 ProgramStateRef state = N->getState();
Anna Zaks8e6431a2011-08-18 22:37:56 +0000781 ProgramStateManager &StateMgr = state->getStateManager();
Tom Care2bbbe502010-09-02 23:30:22 +0000782
783 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Head)) {
784 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
785 const VarRegion *R =
786 StateMgr.getRegionManager().getVarRegion(VD, N->getLocationContext());
787
788 // What did we load?
Ted Kremenek5eca4822012-01-06 22:09:28 +0000789 SVal V = state->getSVal(S, N->getLocationContext());
Tom Care2bbbe502010-09-02 23:30:22 +0000790
791 if (isa<loc::ConcreteInt>(V) || isa<nonloc::ConcreteInt>(V)) {
Anna Zaks50bbc162011-08-19 22:33:38 +0000792 // Register a new visitor with the BugReport.
793 BR.addVisitor(new FindLastStoreBRVisitor(V, R));
Tom Care2bbbe502010-09-02 23:30:22 +0000794 }
795 }
796 }
797
798 for (Stmt::const_child_iterator I = Head->child_begin();
799 I != Head->child_end(); ++I)
800 WorkList.push_back(*I);
801 }
802}
Ted Kremenek993124e2011-08-06 06:54:45 +0000803
804//===----------------------------------------------------------------------===//
805// Visitor that tries to report interesting diagnostics from conditions.
806//===----------------------------------------------------------------------===//
Ted Kremenekb85cce02012-10-25 22:07:10 +0000807
808/// Return the tag associated with this visitor. This tag will be used
809/// to make all PathDiagnosticPieces created by this visitor.
810const char *ConditionBRVisitor::getTag() {
811 return "ConditionBRVisitor";
812}
813
Anna Zaks50bbc162011-08-19 22:33:38 +0000814PathDiagnosticPiece *ConditionBRVisitor::VisitNode(const ExplodedNode *N,
815 const ExplodedNode *Prev,
816 BugReporterContext &BRC,
817 BugReport &BR) {
Ted Kremenekc89f4b02012-02-28 23:06:21 +0000818 PathDiagnosticPiece *piece = VisitNodeImpl(N, Prev, BRC, BR);
Ted Kremenekb85cce02012-10-25 22:07:10 +0000819 if (piece) {
820 piece->setTag(getTag());
821 if (PathDiagnosticEventPiece *ev=dyn_cast<PathDiagnosticEventPiece>(piece))
822 ev->setPrunable(true, /* override */ false);
823 }
Ted Kremenekc89f4b02012-02-28 23:06:21 +0000824 return piece;
825}
826
827PathDiagnosticPiece *ConditionBRVisitor::VisitNodeImpl(const ExplodedNode *N,
828 const ExplodedNode *Prev,
829 BugReporterContext &BRC,
830 BugReport &BR) {
Ted Kremenek993124e2011-08-06 06:54:45 +0000831
Ted Kremenek22505ef2012-09-08 07:18:18 +0000832 ProgramPoint progPoint = N->getLocation();
Ted Kremenek8bef8232012-01-26 21:29:00 +0000833 ProgramStateRef CurrentState = N->getState();
834 ProgramStateRef PrevState = Prev->getState();
Ted Kremenek681bc112011-08-16 01:53:41 +0000835
836 // Compare the GDMs of the state, because that is where constraints
837 // are managed. Note that ensure that we only look at nodes that
838 // were generated by the analyzer engine proper, not checkers.
839 if (CurrentState->getGDM().getRoot() ==
840 PrevState->getGDM().getRoot())
841 return 0;
Ted Kremenek993124e2011-08-06 06:54:45 +0000842
843 // If an assumption was made on a branch, it should be caught
844 // here by looking at the state transition.
845 if (const BlockEdge *BE = dyn_cast<BlockEdge>(&progPoint)) {
Ted Kremenek681bc112011-08-16 01:53:41 +0000846 const CFGBlock *srcBlk = BE->getSrc();
847 if (const Stmt *term = srcBlk->getTerminator())
Ted Kremenek76aadc32012-03-09 01:13:14 +0000848 return VisitTerminator(term, N, srcBlk, BE->getDst(), BR, BRC);
Ted Kremenek681bc112011-08-16 01:53:41 +0000849 return 0;
850 }
851
852 if (const PostStmt *PS = dyn_cast<PostStmt>(&progPoint)) {
853 // FIXME: Assuming that BugReporter is a GRBugReporter is a layering
854 // violation.
855 const std::pair<const ProgramPointTag *, const ProgramPointTag *> &tags =
856 cast<GRBugReporter>(BRC.getBugReporter()).
Ted Kremenek0caa2d42012-08-30 19:26:48 +0000857 getEngine().geteagerlyAssumeBinOpBifurcationTags();
Ted Kremenek681bc112011-08-16 01:53:41 +0000858
859 const ProgramPointTag *tag = PS->getTag();
860 if (tag == tags.first)
Anna Zaks220ac8c2011-09-15 01:08:34 +0000861 return VisitTrueTest(cast<Expr>(PS->getStmt()), true,
Ted Kremenek76aadc32012-03-09 01:13:14 +0000862 BRC, BR, N);
Ted Kremenek681bc112011-08-16 01:53:41 +0000863 if (tag == tags.second)
Anna Zaks220ac8c2011-09-15 01:08:34 +0000864 return VisitTrueTest(cast<Expr>(PS->getStmt()), false,
Ted Kremenek76aadc32012-03-09 01:13:14 +0000865 BRC, BR, N);
Ted Kremenek681bc112011-08-16 01:53:41 +0000866
Ted Kremenek993124e2011-08-06 06:54:45 +0000867 return 0;
868 }
869
870 return 0;
871}
872
873PathDiagnosticPiece *
Anna Zaks50bbc162011-08-19 22:33:38 +0000874ConditionBRVisitor::VisitTerminator(const Stmt *Term,
Anna Zaks220ac8c2011-09-15 01:08:34 +0000875 const ExplodedNode *N,
Anna Zaks50bbc162011-08-19 22:33:38 +0000876 const CFGBlock *srcBlk,
877 const CFGBlock *dstBlk,
Ted Kremenek76aadc32012-03-09 01:13:14 +0000878 BugReport &R,
Anna Zaks50bbc162011-08-19 22:33:38 +0000879 BugReporterContext &BRC) {
Ted Kremenek993124e2011-08-06 06:54:45 +0000880 const Expr *Cond = 0;
881
882 switch (Term->getStmtClass()) {
883 default:
884 return 0;
885 case Stmt::IfStmtClass:
886 Cond = cast<IfStmt>(Term)->getCond();
887 break;
888 case Stmt::ConditionalOperatorClass:
889 Cond = cast<ConditionalOperator>(Term)->getCond();
890 break;
891 }
892
893 assert(Cond);
894 assert(srcBlk->succ_size() == 2);
895 const bool tookTrue = *(srcBlk->succ_begin()) == dstBlk;
Ted Kremenekc47dc1b2012-09-07 06:51:37 +0000896 return VisitTrueTest(Cond, tookTrue, BRC, R, N);
Ted Kremenek993124e2011-08-06 06:54:45 +0000897}
898
899PathDiagnosticPiece *
Anna Zaks50bbc162011-08-19 22:33:38 +0000900ConditionBRVisitor::VisitTrueTest(const Expr *Cond,
901 bool tookTrue,
Anna Zaks220ac8c2011-09-15 01:08:34 +0000902 BugReporterContext &BRC,
Ted Kremenek76aadc32012-03-09 01:13:14 +0000903 BugReport &R,
904 const ExplodedNode *N) {
Ted Kremenek993124e2011-08-06 06:54:45 +0000905
906 const Expr *Ex = Cond;
907
Ted Kremenek681bc112011-08-16 01:53:41 +0000908 while (true) {
Ted Kremenekc47dc1b2012-09-07 06:51:37 +0000909 Ex = Ex->IgnoreParenCasts();
Ted Kremenek993124e2011-08-06 06:54:45 +0000910 switch (Ex->getStmtClass()) {
911 default:
912 return 0;
Ted Kremenek681bc112011-08-16 01:53:41 +0000913 case Stmt::BinaryOperatorClass:
Ted Kremenek76aadc32012-03-09 01:13:14 +0000914 return VisitTrueTest(Cond, cast<BinaryOperator>(Ex), tookTrue, BRC,
915 R, N);
Ted Kremenek993124e2011-08-06 06:54:45 +0000916 case Stmt::DeclRefExprClass:
Ted Kremenek76aadc32012-03-09 01:13:14 +0000917 return VisitTrueTest(Cond, cast<DeclRefExpr>(Ex), tookTrue, BRC,
918 R, N);
Ted Kremenek993124e2011-08-06 06:54:45 +0000919 case Stmt::UnaryOperatorClass: {
920 const UnaryOperator *UO = cast<UnaryOperator>(Ex);
921 if (UO->getOpcode() == UO_LNot) {
922 tookTrue = !tookTrue;
Ted Kremenekc47dc1b2012-09-07 06:51:37 +0000923 Ex = UO->getSubExpr();
Ted Kremenek993124e2011-08-06 06:54:45 +0000924 continue;
925 }
926 return 0;
927 }
928 }
Ted Kremenek681bc112011-08-16 01:53:41 +0000929 }
930}
931
Anna Zaks50bbc162011-08-19 22:33:38 +0000932bool ConditionBRVisitor::patternMatch(const Expr *Ex, llvm::raw_ostream &Out,
Ted Kremenek76aadc32012-03-09 01:13:14 +0000933 BugReporterContext &BRC,
934 BugReport &report,
935 const ExplodedNode *N,
936 llvm::Optional<bool> &prunable) {
Ted Kremenek681bc112011-08-16 01:53:41 +0000937 const Expr *OriginalExpr = Ex;
938 Ex = Ex->IgnoreParenCasts();
939
940 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Ex)) {
Ted Kremenek3b9e8e42011-08-16 10:57:37 +0000941 const bool quotes = isa<VarDecl>(DR->getDecl());
Ted Kremenek76aadc32012-03-09 01:13:14 +0000942 if (quotes) {
Ted Kremenek3b9e8e42011-08-16 10:57:37 +0000943 Out << '\'';
Ted Kremenek76aadc32012-03-09 01:13:14 +0000944 const LocationContext *LCtx = N->getLocationContext();
945 const ProgramState *state = N->getState().getPtr();
946 if (const MemRegion *R = state->getLValue(cast<VarDecl>(DR->getDecl()),
947 LCtx).getAsRegion()) {
948 if (report.isInteresting(R))
949 prunable = false;
950 else {
951 const ProgramState *state = N->getState().getPtr();
952 SVal V = state->getSVal(R);
953 if (report.isInteresting(V))
954 prunable = false;
955 }
956 }
957 }
Ted Kremenek3b9e8e42011-08-16 10:57:37 +0000958 Out << DR->getDecl()->getDeclName().getAsString();
959 if (quotes)
960 Out << '\'';
961 return quotes;
Ted Kremenek681bc112011-08-16 01:53:41 +0000962 }
963
964 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(Ex)) {
965 QualType OriginalTy = OriginalExpr->getType();
966 if (OriginalTy->isPointerType()) {
967 if (IL->getValue() == 0) {
968 Out << "null";
Ted Kremenek3b9e8e42011-08-16 10:57:37 +0000969 return false;
Ted Kremenek681bc112011-08-16 01:53:41 +0000970 }
971 }
972 else if (OriginalTy->isObjCObjectPointerType()) {
973 if (IL->getValue() == 0) {
974 Out << "nil";
Ted Kremenek3b9e8e42011-08-16 10:57:37 +0000975 return false;
Ted Kremenek681bc112011-08-16 01:53:41 +0000976 }
977 }
978
979 Out << IL->getValue();
Ted Kremenek3b9e8e42011-08-16 10:57:37 +0000980 return false;
Ted Kremenek681bc112011-08-16 01:53:41 +0000981 }
Ted Kremenek3b9e8e42011-08-16 10:57:37 +0000982
983 return false;
Ted Kremenek681bc112011-08-16 01:53:41 +0000984}
985
986PathDiagnosticPiece *
Anna Zaks50bbc162011-08-19 22:33:38 +0000987ConditionBRVisitor::VisitTrueTest(const Expr *Cond,
988 const BinaryOperator *BExpr,
989 const bool tookTrue,
Anna Zaks220ac8c2011-09-15 01:08:34 +0000990 BugReporterContext &BRC,
Ted Kremenek76aadc32012-03-09 01:13:14 +0000991 BugReport &R,
992 const ExplodedNode *N) {
Ted Kremenek681bc112011-08-16 01:53:41 +0000993
Ted Kremenek3b9e8e42011-08-16 10:57:37 +0000994 bool shouldInvert = false;
Ted Kremenek76aadc32012-03-09 01:13:14 +0000995 llvm::Optional<bool> shouldPrune;
Ted Kremenek3b9e8e42011-08-16 10:57:37 +0000996
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000997 SmallString<128> LhsString, RhsString;
Ted Kremenek681bc112011-08-16 01:53:41 +0000998 {
Ted Kremenek76aadc32012-03-09 01:13:14 +0000999 llvm::raw_svector_ostream OutLHS(LhsString), OutRHS(RhsString);
1000 const bool isVarLHS = patternMatch(BExpr->getLHS(), OutLHS, BRC, R, N,
1001 shouldPrune);
1002 const bool isVarRHS = patternMatch(BExpr->getRHS(), OutRHS, BRC, R, N,
1003 shouldPrune);
Ted Kremenek3b9e8e42011-08-16 10:57:37 +00001004
1005 shouldInvert = !isVarLHS && isVarRHS;
Ted Kremenek681bc112011-08-16 01:53:41 +00001006 }
1007
Ted Kremenekd1247c52012-01-04 08:18:09 +00001008 BinaryOperator::Opcode Op = BExpr->getOpcode();
1009
1010 if (BinaryOperator::isAssignmentOp(Op)) {
1011 // For assignment operators, all that we care about is that the LHS
1012 // evaluates to "true" or "false".
1013 return VisitConditionVariable(LhsString, BExpr->getLHS(), tookTrue,
Ted Kremenek76aadc32012-03-09 01:13:14 +00001014 BRC, R, N);
Ted Kremenekd1247c52012-01-04 08:18:09 +00001015 }
1016
1017 // For non-assignment operations, we require that we can understand
1018 // both the LHS and RHS.
Ted Kremenek681bc112011-08-16 01:53:41 +00001019 if (LhsString.empty() || RhsString.empty())
1020 return 0;
Ted Kremenek3b9e8e42011-08-16 10:57:37 +00001021
Ted Kremenekd1247c52012-01-04 08:18:09 +00001022 // Should we invert the strings if the LHS is not a variable name?
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00001023 SmallString<256> buf;
Ted Kremenek681bc112011-08-16 01:53:41 +00001024 llvm::raw_svector_ostream Out(buf);
Ted Kremenek3b9e8e42011-08-16 10:57:37 +00001025 Out << "Assuming " << (shouldInvert ? RhsString : LhsString) << " is ";
Ted Kremenek681bc112011-08-16 01:53:41 +00001026
1027 // Do we need to invert the opcode?
Ted Kremenek3b9e8e42011-08-16 10:57:37 +00001028 if (shouldInvert)
1029 switch (Op) {
1030 default: break;
1031 case BO_LT: Op = BO_GT; break;
1032 case BO_GT: Op = BO_LT; break;
1033 case BO_LE: Op = BO_GE; break;
1034 case BO_GE: Op = BO_LE; break;
1035 }
1036
Ted Kremenek681bc112011-08-16 01:53:41 +00001037 if (!tookTrue)
1038 switch (Op) {
1039 case BO_EQ: Op = BO_NE; break;
1040 case BO_NE: Op = BO_EQ; break;
1041 case BO_LT: Op = BO_GE; break;
1042 case BO_GT: Op = BO_LE; break;
1043 case BO_LE: Op = BO_GT; break;
Ted Kremenek4ee7c9c2011-08-16 03:44:38 +00001044 case BO_GE: Op = BO_LT; break;
Ted Kremenek681bc112011-08-16 01:53:41 +00001045 default:
1046 return 0;
1047 }
1048
Ted Kremenek6ae32572011-12-20 22:00:25 +00001049 switch (Op) {
Ted Kremenek681bc112011-08-16 01:53:41 +00001050 case BO_EQ:
1051 Out << "equal to ";
1052 break;
1053 case BO_NE:
1054 Out << "not equal to ";
1055 break;
1056 default:
1057 Out << BinaryOperator::getOpcodeStr(Op) << ' ';
1058 break;
1059 }
1060
Ted Kremenek3b9e8e42011-08-16 10:57:37 +00001061 Out << (shouldInvert ? LhsString : RhsString);
Ted Kremenek76aadc32012-03-09 01:13:14 +00001062 const LocationContext *LCtx = N->getLocationContext();
1063 PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
1064 PathDiagnosticEventPiece *event =
1065 new PathDiagnosticEventPiece(Loc, Out.str());
1066 if (shouldPrune.hasValue())
1067 event->setPrunable(shouldPrune.getValue());
1068 return event;
Ted Kremenek993124e2011-08-06 06:54:45 +00001069}
Ted Kremenekd1247c52012-01-04 08:18:09 +00001070
1071PathDiagnosticPiece *
1072ConditionBRVisitor::VisitConditionVariable(StringRef LhsString,
1073 const Expr *CondVarExpr,
1074 const bool tookTrue,
1075 BugReporterContext &BRC,
Ted Kremenek76aadc32012-03-09 01:13:14 +00001076 BugReport &report,
1077 const ExplodedNode *N) {
Jordan Roseb0e1bad2012-08-03 23:08:54 +00001078 // FIXME: If there's already a constraint tracker for this variable,
1079 // we shouldn't emit anything here (c.f. the double note in
1080 // test/Analysis/inlining/path-notes.c)
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00001081 SmallString<256> buf;
Ted Kremenekd1247c52012-01-04 08:18:09 +00001082 llvm::raw_svector_ostream Out(buf);
1083 Out << "Assuming " << LhsString << " is ";
1084
1085 QualType Ty = CondVarExpr->getType();
1086
1087 if (Ty->isPointerType())
1088 Out << (tookTrue ? "not null" : "null");
1089 else if (Ty->isObjCObjectPointerType())
1090 Out << (tookTrue ? "not nil" : "nil");
1091 else if (Ty->isBooleanType())
1092 Out << (tookTrue ? "true" : "false");
1093 else if (Ty->isIntegerType())
1094 Out << (tookTrue ? "non-zero" : "zero");
1095 else
1096 return 0;
1097
Ted Kremenek76aadc32012-03-09 01:13:14 +00001098 const LocationContext *LCtx = N->getLocationContext();
1099 PathDiagnosticLocation Loc(CondVarExpr, BRC.getSourceManager(), LCtx);
1100 PathDiagnosticEventPiece *event =
1101 new PathDiagnosticEventPiece(Loc, Out.str());
1102
1103 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(CondVarExpr)) {
1104 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1105 const ProgramState *state = N->getState().getPtr();
1106 if (const MemRegion *R = state->getLValue(VD, LCtx).getAsRegion()) {
1107 if (report.isInteresting(R))
1108 event->setPrunable(false);
1109 }
1110 }
1111 }
1112
1113 return event;
Ted Kremenekd1247c52012-01-04 08:18:09 +00001114}
Ted Kremenek993124e2011-08-06 06:54:45 +00001115
1116PathDiagnosticPiece *
Anna Zaks50bbc162011-08-19 22:33:38 +00001117ConditionBRVisitor::VisitTrueTest(const Expr *Cond,
1118 const DeclRefExpr *DR,
1119 const bool tookTrue,
Anna Zaks220ac8c2011-09-15 01:08:34 +00001120 BugReporterContext &BRC,
Ted Kremenek76aadc32012-03-09 01:13:14 +00001121 BugReport &report,
1122 const ExplodedNode *N) {
Ted Kremenek993124e2011-08-06 06:54:45 +00001123
1124 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
1125 if (!VD)
1126 return 0;
1127
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00001128 SmallString<256> Buf;
Ted Kremenek993124e2011-08-06 06:54:45 +00001129 llvm::raw_svector_ostream Out(Buf);
1130
1131 Out << "Assuming '";
1132 VD->getDeclName().printName(Out);
1133 Out << "' is ";
1134
1135 QualType VDTy = VD->getType();
1136
1137 if (VDTy->isPointerType())
1138 Out << (tookTrue ? "non-null" : "null");
1139 else if (VDTy->isObjCObjectPointerType())
1140 Out << (tookTrue ? "non-nil" : "nil");
1141 else if (VDTy->isScalarType())
1142 Out << (tookTrue ? "not equal to 0" : "0");
1143 else
1144 return 0;
1145
Ted Kremenek76aadc32012-03-09 01:13:14 +00001146 const LocationContext *LCtx = N->getLocationContext();
1147 PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
1148 PathDiagnosticEventPiece *event =
1149 new PathDiagnosticEventPiece(Loc, Out.str());
1150
1151 const ProgramState *state = N->getState().getPtr();
1152 if (const MemRegion *R = state->getLValue(VD, LCtx).getAsRegion()) {
1153 if (report.isInteresting(R))
1154 event->setPrunable(false);
1155 else {
1156 SVal V = state->getSVal(R);
1157 if (report.isInteresting(V))
1158 event->setPrunable(false);
1159 }
1160 }
1161 return event;
Ted Kremenek993124e2011-08-06 06:54:45 +00001162}
Ted Kremenek0cf3d472012-02-07 00:24:33 +00001163
Anna Zaks80de4872012-08-29 21:22:37 +00001164PathDiagnosticPiece *
1165UndefOrNullArgVisitor::VisitNode(const ExplodedNode *N,
1166 const ExplodedNode *PrevN,
1167 BugReporterContext &BRC,
1168 BugReport &BR) {
1169
1170 ProgramStateRef State = N->getState();
1171 ProgramPoint ProgLoc = N->getLocation();
1172
1173 // We are only interested in visiting CallEnter nodes.
1174 CallEnter *CEnter = dyn_cast<CallEnter>(&ProgLoc);
1175 if (!CEnter)
1176 return 0;
1177
1178 // Check if one of the arguments is the region the visitor is tracking.
1179 CallEventManager &CEMgr = BRC.getStateManager().getCallEventManager();
1180 CallEventRef<> Call = CEMgr.getCaller(CEnter->getCalleeContext(), State);
1181 unsigned Idx = 0;
1182 for (CallEvent::param_iterator I = Call->param_begin(),
1183 E = Call->param_end(); I != E; ++I, ++Idx) {
1184 const MemRegion *ArgReg = Call->getArgSVal(Idx).getAsRegion();
1185
Anna Zaks522fc212012-09-12 22:57:30 +00001186 // Are we tracking the argument or its subregion?
1187 if ( !ArgReg || (ArgReg != R && !R->isSubRegionOf(ArgReg->StripCasts())))
Anna Zaks28694c12012-08-29 23:23:39 +00001188 continue;
Anna Zaks80de4872012-08-29 21:22:37 +00001189
1190 // Check the function parameter type.
1191 const ParmVarDecl *ParamDecl = *I;
1192 assert(ParamDecl && "Formal parameter has no decl?");
1193 QualType T = ParamDecl->getType();
1194
1195 if (!(T->isAnyPointerType() || T->isReferenceType())) {
1196 // Function can only change the value passed in by address.
Anna Zaks28694c12012-08-29 23:23:39 +00001197 continue;
Anna Zaks80de4872012-08-29 21:22:37 +00001198 }
1199
1200 // If it is a const pointer value, the function does not intend to
1201 // change the value.
1202 if (T->getPointeeType().isConstQualified())
Anna Zaks28694c12012-08-29 23:23:39 +00001203 continue;
Anna Zaks80de4872012-08-29 21:22:37 +00001204
1205 // Mark the call site (LocationContext) as interesting if the value of the
1206 // argument is undefined or '0'/'NULL'.
Anna Zaks522fc212012-09-12 22:57:30 +00001207 SVal BoundVal = State->getSVal(R);
Anna Zaks80de4872012-08-29 21:22:37 +00001208 if (BoundVal.isUndef() || BoundVal.isZeroConstant()) {
1209 BR.markInteresting(CEnter->getCalleeContext());
1210 return 0;
1211 }
1212 }
1213 return 0;
1214}