blob: 9bb8b8442e1948f9d49999b6efc4d02b68e99dab [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;
138 bool Satisfied;
139public:
140 ReturnVisitor(const StackFrameContext *Frame)
141 : StackFrame(Frame), Satisfied(false) {}
142
143 virtual void Profile(llvm::FoldingSetNodeID &ID) const {
144 static int Tag = 0;
145 ID.AddPointer(&Tag);
146 ID.AddPointer(StackFrame);
147 }
148
149 /// Adds a ReturnVisitor if the given statement represents a call that was
150 /// inlined.
151 ///
152 /// This will search back through the ExplodedGraph, starting from the given
153 /// node, looking for when the given statement was processed. If it turns out
154 /// the statement is a call that was inlined, we add the visitor to the
155 /// bug report, so it can print a note later.
156 static void addVisitorIfNecessary(const ExplodedNode *Node, const Stmt *S,
157 BugReport &BR) {
158 if (!CallEvent::isCallStmt(S))
159 return;
160
161 // First, find when we processed the statement.
162 do {
163 if (const CallExitEnd *CEE = Node->getLocationAs<CallExitEnd>())
164 if (CEE->getCalleeContext()->getCallSite() == S)
165 break;
166 if (const StmtPoint *SP = Node->getLocationAs<StmtPoint>())
167 if (SP->getStmt() == S)
168 break;
169
170 Node = Node->getFirstPred();
171 } while (Node);
172
173 // Next, step over any post-statement checks.
174 while (Node && isa<PostStmt>(Node->getLocation()))
175 Node = Node->getFirstPred();
176
177 // Finally, see if we inlined the call.
178 if (Node)
179 if (const CallExitEnd *CEE = Node->getLocationAs<CallExitEnd>())
180 if (CEE->getCalleeContext()->getCallSite() == S)
181 BR.addVisitor(new ReturnVisitor(CEE->getCalleeContext()));
182
183 }
184
185 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
186 const ExplodedNode *PrevN,
187 BugReporterContext &BRC,
188 BugReport &BR) {
189 if (Satisfied)
190 return 0;
191
192 // Only print a message at the interesting return statement.
193 if (N->getLocationContext() != StackFrame)
194 return 0;
195
196 const StmtPoint *SP = N->getLocationAs<StmtPoint>();
197 if (!SP)
198 return 0;
199
200 const ReturnStmt *Ret = dyn_cast<ReturnStmt>(SP->getStmt());
201 if (!Ret)
202 return 0;
203
204 // Okay, we're at the right return statement, but do we have the return
205 // value available?
206 ProgramStateRef State = N->getState();
207 SVal V = State->getSVal(Ret, StackFrame);
208 if (V.isUnknownOrUndef())
209 return 0;
210
211 // Don't print any more notes after this one.
212 Satisfied = true;
213
214 // Build an appropriate message based on the return value.
215 SmallString<64> Msg;
216 llvm::raw_svector_ostream Out(Msg);
217
218 const Expr *RetE = Ret->getRetValue();
219 assert(RetE && "Tracking a return value for a void function");
220 RetE = RetE->IgnoreParenCasts();
221
222 // See if we know that the return value is 0.
223 ProgramStateRef StNonZero, StZero;
224 llvm::tie(StNonZero, StZero) = State->assume(cast<DefinedSVal>(V));
225 if (StZero && !StNonZero) {
226 // If we're returning 0, we should track where that 0 came from.
Jordan Rosea1f81bb2012-08-28 00:50:51 +0000227 bugreporter::trackNullOrUndefValue(N, RetE, BR);
Jordan Rose7aba1172012-08-28 00:50:42 +0000228
229 if (isa<Loc>(V)) {
230 if (RetE->getType()->isObjCObjectPointerType())
231 Out << "Returning nil";
232 else
233 Out << "Returning null pointer";
234 } else {
235 Out << "Returning zero";
236 }
237 } else {
238 // FIXME: We can probably do better than this.
239 BR.markInteresting(V);
240 Out << "Value returned here";
241 }
242
243 // FIXME: We should have a more generalized location printing mechanism.
244 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(RetE))
245 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(DR->getDecl()))
246 Out << " (loaded from '" << *DD << "')";
247
248 PathDiagnosticLocation L(Ret, BRC.getSourceManager(), StackFrame);
249 return new PathDiagnosticEventPiece(L, Out.str());
250 }
251};
252} // end anonymous namespace
253
254
Anna Zaks50bbc162011-08-19 22:33:38 +0000255void FindLastStoreBRVisitor ::Profile(llvm::FoldingSetNodeID &ID) const {
256 static int tag = 0;
257 ID.AddPointer(&tag);
258 ID.AddPointer(R);
259 ID.Add(V);
260}
Ted Kremenek53500662009-07-22 17:55:28 +0000261
Jordan Rose166b7bd2012-08-28 00:50:45 +0000262PathDiagnosticPiece *FindLastStoreBRVisitor::VisitNode(const ExplodedNode *Succ,
263 const ExplodedNode *Pred,
264 BugReporterContext &BRC,
265 BugReport &BR) {
Mike Stump1eb44332009-09-09 15:08:12 +0000266
Anna Zaks50bbc162011-08-19 22:33:38 +0000267 if (satisfied)
268 return NULL;
269
Jordan Rose166b7bd2012-08-28 00:50:45 +0000270 const ExplodedNode *StoreSite = 0;
271 const Expr *InitE = 0;
Anna Zaks50bbc162011-08-19 22:33:38 +0000272
Jordan Rose166b7bd2012-08-28 00:50:45 +0000273 // First see if we reached the declaration of the region.
274 if (const VarRegion *VR = dyn_cast<VarRegion>(R)) {
275 if (const PostStmt *P = Pred->getLocationAs<PostStmt>()) {
276 if (const DeclStmt *DS = P->getStmtAs<DeclStmt>()) {
277 if (DS->getSingleDecl() == VR->getDecl()) {
278 StoreSite = Pred;
279 InitE = VR->getDecl()->getInit();
Jordan Rose7aba1172012-08-28 00:50:42 +0000280 }
Jordan Rose7aba1172012-08-28 00:50:42 +0000281 }
Jordan Rose7aba1172012-08-28 00:50:42 +0000282 }
Ted Kremenek1b431022010-03-20 18:01:57 +0000283 }
284
Jordan Rose166b7bd2012-08-28 00:50:45 +0000285 // Otherwise, check that Succ has this binding and Pred does not, i.e. this is
286 // where the binding first occurred.
287 if (!StoreSite) {
288 if (Succ->getState()->getSVal(R) != V)
289 return NULL;
290 if (Pred->getState()->getSVal(R) == V)
291 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +0000292
Jordan Rose166b7bd2012-08-28 00:50:45 +0000293 StoreSite = Succ;
294
295 // If this is an assignment expression, we can track the value
296 // being assigned.
297 if (const PostStmt *P = Succ->getLocationAs<PostStmt>())
298 if (const BinaryOperator *BO = P->getStmtAs<BinaryOperator>())
299 if (BO->isAssignmentOp())
300 InitE = BO->getRHS();
Jordan Rose85e99372012-09-22 01:24:46 +0000301
302 // If this is a call entry, the variable should be a parameter.
303 // FIXME: Handle CXXThisRegion as well. (This is not a priority because
304 // 'this' should never be NULL, but this visitor isn't just for NULL and
305 // UndefinedVal.)
306 if (const CallEnter *CE = Succ->getLocationAs<CallEnter>()) {
307 const VarRegion *VR = cast<VarRegion>(R);
308 const ParmVarDecl *Param = cast<ParmVarDecl>(VR->getDecl());
309
310 ProgramStateManager &StateMgr = BRC.getStateManager();
311 CallEventManager &CallMgr = StateMgr.getCallEventManager();
312
313 CallEventRef<> Call = CallMgr.getCaller(CE->getCalleeContext(),
314 Succ->getState());
315 InitE = Call->getArgExpr(Param->getFunctionScopeIndex());
316 }
Jordan Rose166b7bd2012-08-28 00:50:45 +0000317 }
318
319 if (!StoreSite)
320 return NULL;
Anna Zaks50bbc162011-08-19 22:33:38 +0000321 satisfied = true;
Jordan Rose166b7bd2012-08-28 00:50:45 +0000322
323 // If the value that was stored came from an inlined call, make sure we
324 // step into the call.
325 if (InitE) {
326 InitE = InitE->IgnoreParenCasts();
327 ReturnVisitor::addVisitorIfNecessary(StoreSite, InitE, BR);
328 }
329
Jordan Rose85e99372012-09-22 01:24:46 +0000330 if (!R->canPrintPretty())
331 return 0;
332
Jordan Rose166b7bd2012-08-28 00:50:45 +0000333 // Okay, we've found the binding. Emit an appropriate message.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000334 SmallString<256> sbuf;
Anna Zaks50bbc162011-08-19 22:33:38 +0000335 llvm::raw_svector_ostream os(sbuf);
Mike Stump1eb44332009-09-09 15:08:12 +0000336
Jordan Rose166b7bd2012-08-28 00:50:45 +0000337 if (const PostStmt *PS = StoreSite->getLocationAs<PostStmt>()) {
Anna Zaks50bbc162011-08-19 22:33:38 +0000338 if (const DeclStmt *DS = PS->getStmtAs<DeclStmt>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000339
Anna Zaks50bbc162011-08-19 22:33:38 +0000340 if (const VarRegion *VR = dyn_cast<VarRegion>(R)) {
Benjamin Kramerb8989f22011-10-14 18:45:37 +0000341 os << "Variable '" << *VR->getDecl() << "' ";
Ted Kremenek53500662009-07-22 17:55:28 +0000342 }
Anna Zaks50bbc162011-08-19 22:33:38 +0000343 else
Ted Kremenek53500662009-07-22 17:55:28 +0000344 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +0000345
Ted Kremenek53500662009-07-22 17:55:28 +0000346 if (isa<loc::ConcreteInt>(V)) {
347 bool b = false;
Ted Kremenek53500662009-07-22 17:55:28 +0000348 if (R->isBoundable()) {
Ted Kremenek96979342011-08-12 20:02:48 +0000349 if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R)) {
Zhongxing Xu018220c2010-08-11 06:10:55 +0000350 if (TR->getValueType()->isObjCObjectPointerType()) {
Anna Zaks50bbc162011-08-19 22:33:38 +0000351 os << "initialized to nil";
Ted Kremenek53500662009-07-22 17:55:28 +0000352 b = true;
353 }
354 }
355 }
Mike Stump1eb44332009-09-09 15:08:12 +0000356
Ted Kremenek53500662009-07-22 17:55:28 +0000357 if (!b)
Anna Zaks50bbc162011-08-19 22:33:38 +0000358 os << "initialized to a null pointer value";
Ted Kremenek53500662009-07-22 17:55:28 +0000359 }
Ted Kremenek592362b2009-08-18 01:05:30 +0000360 else if (isa<nonloc::ConcreteInt>(V)) {
Anna Zaks50bbc162011-08-19 22:33:38 +0000361 os << "initialized to " << cast<nonloc::ConcreteInt>(V).getValue();
Ted Kremenek592362b2009-08-18 01:05:30 +0000362 }
Anna Zaks50bbc162011-08-19 22:33:38 +0000363 else if (V.isUndef()) {
364 if (isa<VarRegion>(R)) {
365 const VarDecl *VD = cast<VarDecl>(DS->getSingleDecl());
366 if (VD->getInit())
367 os << "initialized to a garbage value";
368 else
369 os << "declared without an initial value";
370 }
Ted Kremenek53500662009-07-22 17:55:28 +0000371 }
Jordan Rose68537992012-08-03 23:09:01 +0000372 else {
373 os << "initialized here";
374 }
Ted Kremenek53500662009-07-22 17:55:28 +0000375 }
Jordan Rose85e99372012-09-22 01:24:46 +0000376 } else if (isa<CallEnter>(StoreSite->getLocation())) {
377 const ParmVarDecl *Param = cast<ParmVarDecl>(cast<VarRegion>(R)->getDecl());
378
379 os << "Passing ";
380
381 if (isa<loc::ConcreteInt>(V)) {
382 if (Param->getType()->isObjCObjectPointerType())
383 os << "nil object reference";
384 else
385 os << "null pointer value";
386 } else if (V.isUndef()) {
387 os << "uninitialized value";
388 } else if (isa<nonloc::ConcreteInt>(V)) {
389 os << "the value " << cast<nonloc::ConcreteInt>(V).getValue();
390 } else {
391 os << "value";
392 }
393
394 // Printed parameter indexes are 1-based, not 0-based.
395 unsigned Idx = Param->getFunctionScopeIndex() + 1;
396 os << " via " << Idx << llvm::getOrdinalSuffix(Idx) << " parameter '";
397
398 R->printPretty(os);
399 os << '\'';
Anna Zaks50bbc162011-08-19 22:33:38 +0000400 }
401
402 if (os.str().empty()) {
403 if (isa<loc::ConcreteInt>(V)) {
404 bool b = false;
405 if (R->isBoundable()) {
406 if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R)) {
407 if (TR->getValueType()->isObjCObjectPointerType()) {
408 os << "nil object reference stored to ";
409 b = true;
410 }
411 }
412 }
413
414 if (!b)
415 os << "Null pointer value stored to ";
416 }
417 else if (V.isUndef()) {
418 os << "Uninitialized value stored to ";
419 }
420 else if (isa<nonloc::ConcreteInt>(V)) {
421 os << "The value " << cast<nonloc::ConcreteInt>(V).getValue()
422 << " is assigned to ";
423 }
424 else
Jordan Rose68537992012-08-03 23:09:01 +0000425 os << "Value assigned to ";
Anna Zaks50bbc162011-08-19 22:33:38 +0000426
Jordan Rose85e99372012-09-22 01:24:46 +0000427 os << '\'';
428 R->printPretty(os);
429 os << '\'';
Anna Zaks50bbc162011-08-19 22:33:38 +0000430 }
431
Anna Zaks50bbc162011-08-19 22:33:38 +0000432 // Construct a new PathDiagnosticPiece.
Jordan Rose166b7bd2012-08-28 00:50:45 +0000433 ProgramPoint P = StoreSite->getLocation();
Jordan Rose85e99372012-09-22 01:24:46 +0000434 PathDiagnosticLocation L;
435 if (isa<CallEnter>(P))
436 L = PathDiagnosticLocation(InitE, BRC.getSourceManager(),
437 P.getLocationContext());
438 else
439 L = PathDiagnosticLocation::create(P, BRC.getSourceManager());
Anna Zaks4fdf97b2011-09-15 18:56:07 +0000440 if (!L.isValid())
441 return NULL;
Anna Zaks50bbc162011-08-19 22:33:38 +0000442 return new PathDiagnosticEventPiece(L, os.str());
443}
444
445void TrackConstraintBRVisitor::Profile(llvm::FoldingSetNodeID &ID) const {
446 static int tag = 0;
447 ID.AddPointer(&tag);
448 ID.AddBoolean(Assumption);
449 ID.Add(Constraint);
450}
451
452PathDiagnosticPiece *
453TrackConstraintBRVisitor::VisitNode(const ExplodedNode *N,
454 const ExplodedNode *PrevN,
455 BugReporterContext &BRC,
456 BugReport &BR) {
457 if (isSatisfied)
458 return NULL;
459
460 // Check if in the previous state it was feasible for this constraint
461 // to *not* be true.
462 if (PrevN->getState()->assume(Constraint, !Assumption)) {
463
464 isSatisfied = true;
465
466 // As a sanity check, make sure that the negation of the constraint
467 // was infeasible in the current state. If it is feasible, we somehow
468 // missed the transition point.
469 if (N->getState()->assume(Constraint, !Assumption))
470 return NULL;
471
472 // We found the transition point for the constraint. We now need to
473 // pretty-print the constraint. (work-in-progress)
474 std::string sbuf;
475 llvm::raw_string_ostream os(sbuf);
476
477 if (isa<Loc>(Constraint)) {
478 os << "Assuming pointer value is ";
479 os << (Assumption ? "non-null" : "null");
480 }
481
482 if (os.str().empty())
483 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +0000484
Ted Kremenek53500662009-07-22 17:55:28 +0000485 // Construct a new PathDiagnosticPiece.
Anna Zaks4fdf97b2011-09-15 18:56:07 +0000486 ProgramPoint P = N->getLocation();
Anna Zaks1531bb02011-09-20 01:38:47 +0000487 PathDiagnosticLocation L =
488 PathDiagnosticLocation::create(P, BRC.getSourceManager());
Anna Zaks4fdf97b2011-09-15 18:56:07 +0000489 if (!L.isValid())
490 return NULL;
Ted Kremenek53500662009-07-22 17:55:28 +0000491 return new PathDiagnosticEventPiece(L, os.str());
492 }
Ted Kremenek53500662009-07-22 17:55:28 +0000493
Anna Zaks50bbc162011-08-19 22:33:38 +0000494 return NULL;
Ted Kremenek53500662009-07-22 17:55:28 +0000495}
496
Jordan Rosea1f81bb2012-08-28 00:50:51 +0000497void bugreporter::trackNullOrUndefValue(const ExplodedNode *N, const Stmt *S,
498 BugReport &report) {
Anna Zaks50bbc162011-08-19 22:33:38 +0000499 if (!S || !N)
Jordan Rose68537992012-08-03 23:09:01 +0000500 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000501
Anna Zaks8e6431a2011-08-18 22:37:56 +0000502 ProgramStateManager &StateMgr = N->getState()->getStateManager();
503
Jordan Rose364b9f92012-08-27 20:18:30 +0000504 // Walk through nodes until we get one that matches the statement exactly.
Ted Kremenek88299892011-07-28 23:07:59 +0000505 while (N) {
506 const ProgramPoint &pp = N->getLocation();
507 if (const PostStmt *ps = dyn_cast<PostStmt>(&pp)) {
508 if (ps->getStmt() == S)
509 break;
Jordan Rose23df2432012-08-24 16:34:31 +0000510 } else if (const CallExitEnd *CEE = dyn_cast<CallExitEnd>(&pp)) {
511 if (CEE->getCalleeContext()->getCallSite() == S)
512 break;
Ted Kremenek88299892011-07-28 23:07:59 +0000513 }
Anna Zaksb459cf32011-10-01 06:35:19 +0000514 N = N->getFirstPred();
Ted Kremenek88299892011-07-28 23:07:59 +0000515 }
516
517 if (!N)
Jordan Rose68537992012-08-03 23:09:01 +0000518 return;
Ted Kremenek88299892011-07-28 23:07:59 +0000519
Ted Kremenek8bef8232012-01-26 21:29:00 +0000520 ProgramStateRef state = N->getState();
Mike Stump1eb44332009-09-09 15:08:12 +0000521
Jordan Rose364b9f92012-08-27 20:18:30 +0000522 // See if the expression we're interested refers to a variable.
523 // If so, we can track both its contents and constraints on its value.
524 if (const Expr *Ex = dyn_cast<Expr>(S)) {
525 // Strip off parens and casts. Note that this will never have issues with
526 // C++ user-defined implicit conversions, because those have a constructor
527 // or function call inside.
Jordan Rosee6cd0542012-08-16 00:03:33 +0000528 Ex = Ex->IgnoreParenCasts();
Ted Kremenek76aadc32012-03-09 01:13:14 +0000529 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Ex)) {
Jordan Rose364b9f92012-08-27 20:18:30 +0000530 // FIXME: Right now we only track VarDecls because it's non-trivial to
531 // get a MemRegion for any other DeclRefExprs. <rdar://problem/12114812>
Ted Kremenek76aadc32012-03-09 01:13:14 +0000532 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
533 const VarRegion *R =
534 StateMgr.getRegionManager().getVarRegion(VD, N->getLocationContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000535
Jordan Rose364b9f92012-08-27 20:18:30 +0000536 // Mark both the variable region and its contents as interesting.
Ted Kremenek11abcec2012-05-02 00:31:29 +0000537 SVal V = state->getRawSVal(loc::MemRegionVal(R));
Jordan Rosea1f81bb2012-08-28 00:50:51 +0000538 report.markInteresting(R);
539 report.markInteresting(V);
Anna Zaks80de4872012-08-29 21:22:37 +0000540 report.addVisitor(new UndefOrNullArgVisitor(R));
Jordan Rose68537992012-08-03 23:09:01 +0000541
Jordan Rose364b9f92012-08-27 20:18:30 +0000542 // If the contents are symbolic, find out when they became null.
Jordan Rose68537992012-08-03 23:09:01 +0000543 if (V.getAsLocSymbol()) {
544 BugReporterVisitor *ConstraintTracker
545 = new TrackConstraintBRVisitor(cast<loc::MemRegionVal>(V), false);
Jordan Rosea1f81bb2012-08-28 00:50:51 +0000546 report.addVisitor(ConstraintTracker);
Jordan Rose68537992012-08-03 23:09:01 +0000547 }
548
Jordan Rosea1f81bb2012-08-28 00:50:51 +0000549 report.addVisitor(new FindLastStoreBRVisitor(V, R));
Jordan Rose68537992012-08-03 23:09:01 +0000550 return;
Ted Kremenek53500662009-07-22 17:55:28 +0000551 }
552 }
553 }
Mike Stump1eb44332009-09-09 15:08:12 +0000554
Jordan Rose364b9f92012-08-27 20:18:30 +0000555 // If the expression does NOT refer to a variable, we can still track
556 // constraints on its contents.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000557 SVal V = state->getSValAsScalarOrLoc(S, N->getLocationContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000558
Ted Kremenek53500662009-07-22 17:55:28 +0000559 // Uncomment this to find cases where we aren't properly getting the
560 // base value that was dereferenced.
561 // assert(!V.isUnknownOrUndef());
Mike Stump1eb44332009-09-09 15:08:12 +0000562
Ted Kremenek53500662009-07-22 17:55:28 +0000563 // Is it a symbolic value?
564 if (loc::MemRegionVal *L = dyn_cast<loc::MemRegionVal>(&V)) {
Anna Zaksd91696e2012-09-05 22:31:55 +0000565 // At this point we are dealing with the region's LValue.
566 // However, if the rvalue is a symbolic region, we should track it as well.
567 SVal RVal = state->getSVal(L->getRegion());
568 const MemRegion *RegionRVal = RVal.getAsRegion();
Anna Zaks522fc212012-09-12 22:57:30 +0000569 report.addVisitor(new UndefOrNullArgVisitor(L->getRegion()));
570
Anna Zaksd91696e2012-09-05 22:31:55 +0000571
572 if (RegionRVal && isa<SymbolicRegion>(RegionRVal)) {
573 report.markInteresting(RegionRVal);
574 report.addVisitor(new TrackConstraintBRVisitor(
575 loc::MemRegionVal(RegionRVal), false));
Ted Kremenek53500662009-07-22 17:55:28 +0000576 }
Jordan Rose7aba1172012-08-28 00:50:42 +0000577 } else {
578 // Otherwise, if the value came from an inlined function call,
579 // we should at least make sure that function isn't pruned in our output.
Jordan Rosea1f81bb2012-08-28 00:50:51 +0000580 ReturnVisitor::addVisitorIfNecessary(N, S, report);
Ted Kremenek53500662009-07-22 17:55:28 +0000581 }
582}
Ted Kremenek94fd0b82010-02-16 08:33:59 +0000583
Anna Zaks50bbc162011-08-19 22:33:38 +0000584BugReporterVisitor *
585FindLastStoreBRVisitor::createVisitorObject(const ExplodedNode *N,
586 const MemRegion *R) {
587 assert(R && "The memory region is null.");
Ted Kremenek94fd0b82010-02-16 08:33:59 +0000588
Ted Kremenek8bef8232012-01-26 21:29:00 +0000589 ProgramStateRef state = N->getState();
Ted Kremenek94fd0b82010-02-16 08:33:59 +0000590 SVal V = state->getSVal(R);
Ted Kremenek94fd0b82010-02-16 08:33:59 +0000591 if (V.isUnknown())
Anna Zaks50bbc162011-08-19 22:33:38 +0000592 return 0;
Ted Kremenek94fd0b82010-02-16 08:33:59 +0000593
Anna Zaks50bbc162011-08-19 22:33:38 +0000594 return new FindLastStoreBRVisitor(V, R);
Ted Kremenek94fd0b82010-02-16 08:33:59 +0000595}
Ted Kremenekff7f7362010-03-20 18:02:01 +0000596
597
Anna Zaks50bbc162011-08-19 22:33:38 +0000598PathDiagnosticPiece *NilReceiverBRVisitor::VisitNode(const ExplodedNode *N,
599 const ExplodedNode *PrevN,
600 BugReporterContext &BRC,
601 BugReport &BR) {
602 const PostStmt *P = N->getLocationAs<PostStmt>();
603 if (!P)
604 return 0;
605 const ObjCMessageExpr *ME = P->getStmtAs<ObjCMessageExpr>();
606 if (!ME)
607 return 0;
608 const Expr *Receiver = ME->getInstanceReceiver();
609 if (!Receiver)
610 return 0;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000611 ProgramStateRef state = N->getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +0000612 const SVal &V = state->getSVal(Receiver, N->getLocationContext());
Anna Zaks50bbc162011-08-19 22:33:38 +0000613 const DefinedOrUnknownSVal *DV = dyn_cast<DefinedOrUnknownSVal>(&V);
614 if (!DV)
615 return 0;
616 state = state->assume(*DV, true);
617 if (state)
618 return 0;
Ted Kremenekff7f7362010-03-20 18:02:01 +0000619
Anna Zaks50bbc162011-08-19 22:33:38 +0000620 // The receiver was nil, and hence the method was skipped.
621 // Register a BugReporterVisitor to issue a message telling us how
622 // the receiver was null.
Jordan Rosea1f81bb2012-08-28 00:50:51 +0000623 bugreporter::trackNullOrUndefValue(N, Receiver, BR);
Anna Zaks50bbc162011-08-19 22:33:38 +0000624 // Issue a message saying that the method was skipped.
Anna Zaks220ac8c2011-09-15 01:08:34 +0000625 PathDiagnosticLocation L(Receiver, BRC.getSourceManager(),
626 N->getLocationContext());
Anna Zaks907344e2012-04-05 02:10:19 +0000627 return new PathDiagnosticEventPiece(L, "No method is called "
Anna Zaks50bbc162011-08-19 22:33:38 +0000628 "because the receiver is nil");
Ted Kremenekff7f7362010-03-20 18:02:01 +0000629}
Tom Care2bbbe502010-09-02 23:30:22 +0000630
Anna Zaks8e6431a2011-08-18 22:37:56 +0000631// Registers every VarDecl inside a Stmt with a last store visitor.
Anna Zaks50bbc162011-08-19 22:33:38 +0000632void FindLastStoreBRVisitor::registerStatementVarDecls(BugReport &BR,
633 const Stmt *S) {
Anna Zaks8e6431a2011-08-18 22:37:56 +0000634 const ExplodedNode *N = BR.getErrorNode();
Tom Care2bbbe502010-09-02 23:30:22 +0000635 std::deque<const Stmt *> WorkList;
Tom Care2bbbe502010-09-02 23:30:22 +0000636 WorkList.push_back(S);
637
638 while (!WorkList.empty()) {
639 const Stmt *Head = WorkList.front();
640 WorkList.pop_front();
641
Ted Kremenek8bef8232012-01-26 21:29:00 +0000642 ProgramStateRef state = N->getState();
Anna Zaks8e6431a2011-08-18 22:37:56 +0000643 ProgramStateManager &StateMgr = state->getStateManager();
Tom Care2bbbe502010-09-02 23:30:22 +0000644
645 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Head)) {
646 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
647 const VarRegion *R =
648 StateMgr.getRegionManager().getVarRegion(VD, N->getLocationContext());
649
650 // What did we load?
Ted Kremenek5eca4822012-01-06 22:09:28 +0000651 SVal V = state->getSVal(S, N->getLocationContext());
Tom Care2bbbe502010-09-02 23:30:22 +0000652
653 if (isa<loc::ConcreteInt>(V) || isa<nonloc::ConcreteInt>(V)) {
Anna Zaks50bbc162011-08-19 22:33:38 +0000654 // Register a new visitor with the BugReport.
655 BR.addVisitor(new FindLastStoreBRVisitor(V, R));
Tom Care2bbbe502010-09-02 23:30:22 +0000656 }
657 }
658 }
659
660 for (Stmt::const_child_iterator I = Head->child_begin();
661 I != Head->child_end(); ++I)
662 WorkList.push_back(*I);
663 }
664}
Ted Kremenek993124e2011-08-06 06:54:45 +0000665
666//===----------------------------------------------------------------------===//
667// Visitor that tries to report interesting diagnostics from conditions.
668//===----------------------------------------------------------------------===//
Anna Zaks50bbc162011-08-19 22:33:38 +0000669PathDiagnosticPiece *ConditionBRVisitor::VisitNode(const ExplodedNode *N,
670 const ExplodedNode *Prev,
671 BugReporterContext &BRC,
672 BugReport &BR) {
Ted Kremenekc89f4b02012-02-28 23:06:21 +0000673 PathDiagnosticPiece *piece = VisitNodeImpl(N, Prev, BRC, BR);
674 if (PathDiagnosticEventPiece *ev =
675 dyn_cast_or_null<PathDiagnosticEventPiece>(piece))
Ted Kremenek76aadc32012-03-09 01:13:14 +0000676 ev->setPrunable(true, /* override */ false);
Ted Kremenekc89f4b02012-02-28 23:06:21 +0000677 return piece;
678}
679
680PathDiagnosticPiece *ConditionBRVisitor::VisitNodeImpl(const ExplodedNode *N,
681 const ExplodedNode *Prev,
682 BugReporterContext &BRC,
683 BugReport &BR) {
Ted Kremenek993124e2011-08-06 06:54:45 +0000684
Ted Kremenek22505ef2012-09-08 07:18:18 +0000685 ProgramPoint progPoint = N->getLocation();
Ted Kremenek8bef8232012-01-26 21:29:00 +0000686 ProgramStateRef CurrentState = N->getState();
687 ProgramStateRef PrevState = Prev->getState();
Ted Kremenek681bc112011-08-16 01:53:41 +0000688
689 // Compare the GDMs of the state, because that is where constraints
690 // are managed. Note that ensure that we only look at nodes that
691 // were generated by the analyzer engine proper, not checkers.
692 if (CurrentState->getGDM().getRoot() ==
693 PrevState->getGDM().getRoot())
694 return 0;
Ted Kremenek993124e2011-08-06 06:54:45 +0000695
696 // If an assumption was made on a branch, it should be caught
697 // here by looking at the state transition.
698 if (const BlockEdge *BE = dyn_cast<BlockEdge>(&progPoint)) {
Ted Kremenek681bc112011-08-16 01:53:41 +0000699 const CFGBlock *srcBlk = BE->getSrc();
700 if (const Stmt *term = srcBlk->getTerminator())
Ted Kremenek76aadc32012-03-09 01:13:14 +0000701 return VisitTerminator(term, N, srcBlk, BE->getDst(), BR, BRC);
Ted Kremenek681bc112011-08-16 01:53:41 +0000702 return 0;
703 }
704
705 if (const PostStmt *PS = dyn_cast<PostStmt>(&progPoint)) {
706 // FIXME: Assuming that BugReporter is a GRBugReporter is a layering
707 // violation.
708 const std::pair<const ProgramPointTag *, const ProgramPointTag *> &tags =
709 cast<GRBugReporter>(BRC.getBugReporter()).
Ted Kremenek0caa2d42012-08-30 19:26:48 +0000710 getEngine().geteagerlyAssumeBinOpBifurcationTags();
Ted Kremenek681bc112011-08-16 01:53:41 +0000711
712 const ProgramPointTag *tag = PS->getTag();
713 if (tag == tags.first)
Anna Zaks220ac8c2011-09-15 01:08:34 +0000714 return VisitTrueTest(cast<Expr>(PS->getStmt()), true,
Ted Kremenek76aadc32012-03-09 01:13:14 +0000715 BRC, BR, N);
Ted Kremenek681bc112011-08-16 01:53:41 +0000716 if (tag == tags.second)
Anna Zaks220ac8c2011-09-15 01:08:34 +0000717 return VisitTrueTest(cast<Expr>(PS->getStmt()), false,
Ted Kremenek76aadc32012-03-09 01:13:14 +0000718 BRC, BR, N);
Ted Kremenek681bc112011-08-16 01:53:41 +0000719
Ted Kremenek993124e2011-08-06 06:54:45 +0000720 return 0;
721 }
722
723 return 0;
724}
725
726PathDiagnosticPiece *
Anna Zaks50bbc162011-08-19 22:33:38 +0000727ConditionBRVisitor::VisitTerminator(const Stmt *Term,
Anna Zaks220ac8c2011-09-15 01:08:34 +0000728 const ExplodedNode *N,
Anna Zaks50bbc162011-08-19 22:33:38 +0000729 const CFGBlock *srcBlk,
730 const CFGBlock *dstBlk,
Ted Kremenek76aadc32012-03-09 01:13:14 +0000731 BugReport &R,
Anna Zaks50bbc162011-08-19 22:33:38 +0000732 BugReporterContext &BRC) {
Ted Kremenek993124e2011-08-06 06:54:45 +0000733 const Expr *Cond = 0;
734
735 switch (Term->getStmtClass()) {
736 default:
737 return 0;
738 case Stmt::IfStmtClass:
739 Cond = cast<IfStmt>(Term)->getCond();
740 break;
741 case Stmt::ConditionalOperatorClass:
742 Cond = cast<ConditionalOperator>(Term)->getCond();
743 break;
744 }
745
746 assert(Cond);
747 assert(srcBlk->succ_size() == 2);
748 const bool tookTrue = *(srcBlk->succ_begin()) == dstBlk;
Ted Kremenekc47dc1b2012-09-07 06:51:37 +0000749 return VisitTrueTest(Cond, tookTrue, BRC, R, N);
Ted Kremenek993124e2011-08-06 06:54:45 +0000750}
751
752PathDiagnosticPiece *
Anna Zaks50bbc162011-08-19 22:33:38 +0000753ConditionBRVisitor::VisitTrueTest(const Expr *Cond,
754 bool tookTrue,
Anna Zaks220ac8c2011-09-15 01:08:34 +0000755 BugReporterContext &BRC,
Ted Kremenek76aadc32012-03-09 01:13:14 +0000756 BugReport &R,
757 const ExplodedNode *N) {
Ted Kremenek993124e2011-08-06 06:54:45 +0000758
759 const Expr *Ex = Cond;
760
Ted Kremenek681bc112011-08-16 01:53:41 +0000761 while (true) {
Ted Kremenekc47dc1b2012-09-07 06:51:37 +0000762 Ex = Ex->IgnoreParenCasts();
Ted Kremenek993124e2011-08-06 06:54:45 +0000763 switch (Ex->getStmtClass()) {
764 default:
765 return 0;
Ted Kremenek681bc112011-08-16 01:53:41 +0000766 case Stmt::BinaryOperatorClass:
Ted Kremenek76aadc32012-03-09 01:13:14 +0000767 return VisitTrueTest(Cond, cast<BinaryOperator>(Ex), tookTrue, BRC,
768 R, N);
Ted Kremenek993124e2011-08-06 06:54:45 +0000769 case Stmt::DeclRefExprClass:
Ted Kremenek76aadc32012-03-09 01:13:14 +0000770 return VisitTrueTest(Cond, cast<DeclRefExpr>(Ex), tookTrue, BRC,
771 R, N);
Ted Kremenek993124e2011-08-06 06:54:45 +0000772 case Stmt::UnaryOperatorClass: {
773 const UnaryOperator *UO = cast<UnaryOperator>(Ex);
774 if (UO->getOpcode() == UO_LNot) {
775 tookTrue = !tookTrue;
Ted Kremenekc47dc1b2012-09-07 06:51:37 +0000776 Ex = UO->getSubExpr();
Ted Kremenek993124e2011-08-06 06:54:45 +0000777 continue;
778 }
779 return 0;
780 }
781 }
Ted Kremenek681bc112011-08-16 01:53:41 +0000782 }
783}
784
Anna Zaks50bbc162011-08-19 22:33:38 +0000785bool ConditionBRVisitor::patternMatch(const Expr *Ex, llvm::raw_ostream &Out,
Ted Kremenek76aadc32012-03-09 01:13:14 +0000786 BugReporterContext &BRC,
787 BugReport &report,
788 const ExplodedNode *N,
789 llvm::Optional<bool> &prunable) {
Ted Kremenek681bc112011-08-16 01:53:41 +0000790 const Expr *OriginalExpr = Ex;
791 Ex = Ex->IgnoreParenCasts();
792
793 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Ex)) {
Ted Kremenek3b9e8e42011-08-16 10:57:37 +0000794 const bool quotes = isa<VarDecl>(DR->getDecl());
Ted Kremenek76aadc32012-03-09 01:13:14 +0000795 if (quotes) {
Ted Kremenek3b9e8e42011-08-16 10:57:37 +0000796 Out << '\'';
Ted Kremenek76aadc32012-03-09 01:13:14 +0000797 const LocationContext *LCtx = N->getLocationContext();
798 const ProgramState *state = N->getState().getPtr();
799 if (const MemRegion *R = state->getLValue(cast<VarDecl>(DR->getDecl()),
800 LCtx).getAsRegion()) {
801 if (report.isInteresting(R))
802 prunable = false;
803 else {
804 const ProgramState *state = N->getState().getPtr();
805 SVal V = state->getSVal(R);
806 if (report.isInteresting(V))
807 prunable = false;
808 }
809 }
810 }
Ted Kremenek3b9e8e42011-08-16 10:57:37 +0000811 Out << DR->getDecl()->getDeclName().getAsString();
812 if (quotes)
813 Out << '\'';
814 return quotes;
Ted Kremenek681bc112011-08-16 01:53:41 +0000815 }
816
817 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(Ex)) {
818 QualType OriginalTy = OriginalExpr->getType();
819 if (OriginalTy->isPointerType()) {
820 if (IL->getValue() == 0) {
821 Out << "null";
Ted Kremenek3b9e8e42011-08-16 10:57:37 +0000822 return false;
Ted Kremenek681bc112011-08-16 01:53:41 +0000823 }
824 }
825 else if (OriginalTy->isObjCObjectPointerType()) {
826 if (IL->getValue() == 0) {
827 Out << "nil";
Ted Kremenek3b9e8e42011-08-16 10:57:37 +0000828 return false;
Ted Kremenek681bc112011-08-16 01:53:41 +0000829 }
830 }
831
832 Out << IL->getValue();
Ted Kremenek3b9e8e42011-08-16 10:57:37 +0000833 return false;
Ted Kremenek681bc112011-08-16 01:53:41 +0000834 }
Ted Kremenek3b9e8e42011-08-16 10:57:37 +0000835
836 return false;
Ted Kremenek681bc112011-08-16 01:53:41 +0000837}
838
839PathDiagnosticPiece *
Anna Zaks50bbc162011-08-19 22:33:38 +0000840ConditionBRVisitor::VisitTrueTest(const Expr *Cond,
841 const BinaryOperator *BExpr,
842 const bool tookTrue,
Anna Zaks220ac8c2011-09-15 01:08:34 +0000843 BugReporterContext &BRC,
Ted Kremenek76aadc32012-03-09 01:13:14 +0000844 BugReport &R,
845 const ExplodedNode *N) {
Ted Kremenek681bc112011-08-16 01:53:41 +0000846
Ted Kremenek3b9e8e42011-08-16 10:57:37 +0000847 bool shouldInvert = false;
Ted Kremenek76aadc32012-03-09 01:13:14 +0000848 llvm::Optional<bool> shouldPrune;
Ted Kremenek3b9e8e42011-08-16 10:57:37 +0000849
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000850 SmallString<128> LhsString, RhsString;
Ted Kremenek681bc112011-08-16 01:53:41 +0000851 {
Ted Kremenek76aadc32012-03-09 01:13:14 +0000852 llvm::raw_svector_ostream OutLHS(LhsString), OutRHS(RhsString);
853 const bool isVarLHS = patternMatch(BExpr->getLHS(), OutLHS, BRC, R, N,
854 shouldPrune);
855 const bool isVarRHS = patternMatch(BExpr->getRHS(), OutRHS, BRC, R, N,
856 shouldPrune);
Ted Kremenek3b9e8e42011-08-16 10:57:37 +0000857
858 shouldInvert = !isVarLHS && isVarRHS;
Ted Kremenek681bc112011-08-16 01:53:41 +0000859 }
860
Ted Kremenekd1247c52012-01-04 08:18:09 +0000861 BinaryOperator::Opcode Op = BExpr->getOpcode();
862
863 if (BinaryOperator::isAssignmentOp(Op)) {
864 // For assignment operators, all that we care about is that the LHS
865 // evaluates to "true" or "false".
866 return VisitConditionVariable(LhsString, BExpr->getLHS(), tookTrue,
Ted Kremenek76aadc32012-03-09 01:13:14 +0000867 BRC, R, N);
Ted Kremenekd1247c52012-01-04 08:18:09 +0000868 }
869
870 // For non-assignment operations, we require that we can understand
871 // both the LHS and RHS.
Ted Kremenek681bc112011-08-16 01:53:41 +0000872 if (LhsString.empty() || RhsString.empty())
873 return 0;
Ted Kremenek3b9e8e42011-08-16 10:57:37 +0000874
Ted Kremenekd1247c52012-01-04 08:18:09 +0000875 // Should we invert the strings if the LHS is not a variable name?
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000876 SmallString<256> buf;
Ted Kremenek681bc112011-08-16 01:53:41 +0000877 llvm::raw_svector_ostream Out(buf);
Ted Kremenek3b9e8e42011-08-16 10:57:37 +0000878 Out << "Assuming " << (shouldInvert ? RhsString : LhsString) << " is ";
Ted Kremenek681bc112011-08-16 01:53:41 +0000879
880 // Do we need to invert the opcode?
Ted Kremenek3b9e8e42011-08-16 10:57:37 +0000881 if (shouldInvert)
882 switch (Op) {
883 default: break;
884 case BO_LT: Op = BO_GT; break;
885 case BO_GT: Op = BO_LT; break;
886 case BO_LE: Op = BO_GE; break;
887 case BO_GE: Op = BO_LE; break;
888 }
889
Ted Kremenek681bc112011-08-16 01:53:41 +0000890 if (!tookTrue)
891 switch (Op) {
892 case BO_EQ: Op = BO_NE; break;
893 case BO_NE: Op = BO_EQ; break;
894 case BO_LT: Op = BO_GE; break;
895 case BO_GT: Op = BO_LE; break;
896 case BO_LE: Op = BO_GT; break;
Ted Kremenek4ee7c9c2011-08-16 03:44:38 +0000897 case BO_GE: Op = BO_LT; break;
Ted Kremenek681bc112011-08-16 01:53:41 +0000898 default:
899 return 0;
900 }
901
Ted Kremenek6ae32572011-12-20 22:00:25 +0000902 switch (Op) {
Ted Kremenek681bc112011-08-16 01:53:41 +0000903 case BO_EQ:
904 Out << "equal to ";
905 break;
906 case BO_NE:
907 Out << "not equal to ";
908 break;
909 default:
910 Out << BinaryOperator::getOpcodeStr(Op) << ' ';
911 break;
912 }
913
Ted Kremenek3b9e8e42011-08-16 10:57:37 +0000914 Out << (shouldInvert ? LhsString : RhsString);
Ted Kremenek76aadc32012-03-09 01:13:14 +0000915 const LocationContext *LCtx = N->getLocationContext();
916 PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
917 PathDiagnosticEventPiece *event =
918 new PathDiagnosticEventPiece(Loc, Out.str());
919 if (shouldPrune.hasValue())
920 event->setPrunable(shouldPrune.getValue());
921 return event;
Ted Kremenek993124e2011-08-06 06:54:45 +0000922}
Ted Kremenekd1247c52012-01-04 08:18:09 +0000923
924PathDiagnosticPiece *
925ConditionBRVisitor::VisitConditionVariable(StringRef LhsString,
926 const Expr *CondVarExpr,
927 const bool tookTrue,
928 BugReporterContext &BRC,
Ted Kremenek76aadc32012-03-09 01:13:14 +0000929 BugReport &report,
930 const ExplodedNode *N) {
Jordan Roseb0e1bad2012-08-03 23:08:54 +0000931 // FIXME: If there's already a constraint tracker for this variable,
932 // we shouldn't emit anything here (c.f. the double note in
933 // test/Analysis/inlining/path-notes.c)
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000934 SmallString<256> buf;
Ted Kremenekd1247c52012-01-04 08:18:09 +0000935 llvm::raw_svector_ostream Out(buf);
936 Out << "Assuming " << LhsString << " is ";
937
938 QualType Ty = CondVarExpr->getType();
939
940 if (Ty->isPointerType())
941 Out << (tookTrue ? "not null" : "null");
942 else if (Ty->isObjCObjectPointerType())
943 Out << (tookTrue ? "not nil" : "nil");
944 else if (Ty->isBooleanType())
945 Out << (tookTrue ? "true" : "false");
946 else if (Ty->isIntegerType())
947 Out << (tookTrue ? "non-zero" : "zero");
948 else
949 return 0;
950
Ted Kremenek76aadc32012-03-09 01:13:14 +0000951 const LocationContext *LCtx = N->getLocationContext();
952 PathDiagnosticLocation Loc(CondVarExpr, BRC.getSourceManager(), LCtx);
953 PathDiagnosticEventPiece *event =
954 new PathDiagnosticEventPiece(Loc, Out.str());
955
956 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(CondVarExpr)) {
957 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
958 const ProgramState *state = N->getState().getPtr();
959 if (const MemRegion *R = state->getLValue(VD, LCtx).getAsRegion()) {
960 if (report.isInteresting(R))
961 event->setPrunable(false);
962 }
963 }
964 }
965
966 return event;
Ted Kremenekd1247c52012-01-04 08:18:09 +0000967}
Ted Kremenek993124e2011-08-06 06:54:45 +0000968
969PathDiagnosticPiece *
Anna Zaks50bbc162011-08-19 22:33:38 +0000970ConditionBRVisitor::VisitTrueTest(const Expr *Cond,
971 const DeclRefExpr *DR,
972 const bool tookTrue,
Anna Zaks220ac8c2011-09-15 01:08:34 +0000973 BugReporterContext &BRC,
Ted Kremenek76aadc32012-03-09 01:13:14 +0000974 BugReport &report,
975 const ExplodedNode *N) {
Ted Kremenek993124e2011-08-06 06:54:45 +0000976
977 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
978 if (!VD)
979 return 0;
980
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000981 SmallString<256> Buf;
Ted Kremenek993124e2011-08-06 06:54:45 +0000982 llvm::raw_svector_ostream Out(Buf);
983
984 Out << "Assuming '";
985 VD->getDeclName().printName(Out);
986 Out << "' is ";
987
988 QualType VDTy = VD->getType();
989
990 if (VDTy->isPointerType())
991 Out << (tookTrue ? "non-null" : "null");
992 else if (VDTy->isObjCObjectPointerType())
993 Out << (tookTrue ? "non-nil" : "nil");
994 else if (VDTy->isScalarType())
995 Out << (tookTrue ? "not equal to 0" : "0");
996 else
997 return 0;
998
Ted Kremenek76aadc32012-03-09 01:13:14 +0000999 const LocationContext *LCtx = N->getLocationContext();
1000 PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
1001 PathDiagnosticEventPiece *event =
1002 new PathDiagnosticEventPiece(Loc, Out.str());
1003
1004 const ProgramState *state = N->getState().getPtr();
1005 if (const MemRegion *R = state->getLValue(VD, LCtx).getAsRegion()) {
1006 if (report.isInteresting(R))
1007 event->setPrunable(false);
1008 else {
1009 SVal V = state->getSVal(R);
1010 if (report.isInteresting(V))
1011 event->setPrunable(false);
1012 }
1013 }
1014 return event;
Ted Kremenek993124e2011-08-06 06:54:45 +00001015}
Ted Kremenek0cf3d472012-02-07 00:24:33 +00001016
Anna Zaks80de4872012-08-29 21:22:37 +00001017PathDiagnosticPiece *
1018UndefOrNullArgVisitor::VisitNode(const ExplodedNode *N,
1019 const ExplodedNode *PrevN,
1020 BugReporterContext &BRC,
1021 BugReport &BR) {
1022
1023 ProgramStateRef State = N->getState();
1024 ProgramPoint ProgLoc = N->getLocation();
1025
1026 // We are only interested in visiting CallEnter nodes.
1027 CallEnter *CEnter = dyn_cast<CallEnter>(&ProgLoc);
1028 if (!CEnter)
1029 return 0;
1030
1031 // Check if one of the arguments is the region the visitor is tracking.
1032 CallEventManager &CEMgr = BRC.getStateManager().getCallEventManager();
1033 CallEventRef<> Call = CEMgr.getCaller(CEnter->getCalleeContext(), State);
1034 unsigned Idx = 0;
1035 for (CallEvent::param_iterator I = Call->param_begin(),
1036 E = Call->param_end(); I != E; ++I, ++Idx) {
1037 const MemRegion *ArgReg = Call->getArgSVal(Idx).getAsRegion();
1038
Anna Zaks522fc212012-09-12 22:57:30 +00001039 // Are we tracking the argument or its subregion?
1040 if ( !ArgReg || (ArgReg != R && !R->isSubRegionOf(ArgReg->StripCasts())))
Anna Zaks28694c12012-08-29 23:23:39 +00001041 continue;
Anna Zaks80de4872012-08-29 21:22:37 +00001042
1043 // Check the function parameter type.
1044 const ParmVarDecl *ParamDecl = *I;
1045 assert(ParamDecl && "Formal parameter has no decl?");
1046 QualType T = ParamDecl->getType();
1047
1048 if (!(T->isAnyPointerType() || T->isReferenceType())) {
1049 // Function can only change the value passed in by address.
Anna Zaks28694c12012-08-29 23:23:39 +00001050 continue;
Anna Zaks80de4872012-08-29 21:22:37 +00001051 }
1052
1053 // If it is a const pointer value, the function does not intend to
1054 // change the value.
1055 if (T->getPointeeType().isConstQualified())
Anna Zaks28694c12012-08-29 23:23:39 +00001056 continue;
Anna Zaks80de4872012-08-29 21:22:37 +00001057
1058 // Mark the call site (LocationContext) as interesting if the value of the
1059 // argument is undefined or '0'/'NULL'.
Anna Zaks522fc212012-09-12 22:57:30 +00001060 SVal BoundVal = State->getSVal(R);
Anna Zaks80de4872012-08-29 21:22:37 +00001061 if (BoundVal.isUndef() || BoundVal.isZeroConstant()) {
1062 BR.markInteresting(CEnter->getCalleeContext());
1063 return 0;
1064 }
1065 }
1066 return 0;
1067}