blob: e1a93673f65952bb30a1e0b0117571b146742c64 [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
Jordan Rose6686b662012-09-22 01:24:49 +0000502 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(S))
503 S = OVE->getSourceExpr();
504
Anna Zaks8e6431a2011-08-18 22:37:56 +0000505 ProgramStateManager &StateMgr = N->getState()->getStateManager();
506
Jordan Rose364b9f92012-08-27 20:18:30 +0000507 // Walk through nodes until we get one that matches the statement exactly.
Ted Kremenek88299892011-07-28 23:07:59 +0000508 while (N) {
509 const ProgramPoint &pp = N->getLocation();
510 if (const PostStmt *ps = dyn_cast<PostStmt>(&pp)) {
511 if (ps->getStmt() == S)
512 break;
Jordan Rose23df2432012-08-24 16:34:31 +0000513 } else if (const CallExitEnd *CEE = dyn_cast<CallExitEnd>(&pp)) {
514 if (CEE->getCalleeContext()->getCallSite() == S)
515 break;
Ted Kremenek88299892011-07-28 23:07:59 +0000516 }
Anna Zaksb459cf32011-10-01 06:35:19 +0000517 N = N->getFirstPred();
Ted Kremenek88299892011-07-28 23:07:59 +0000518 }
519
520 if (!N)
Jordan Rose68537992012-08-03 23:09:01 +0000521 return;
Ted Kremenek88299892011-07-28 23:07:59 +0000522
Ted Kremenek8bef8232012-01-26 21:29:00 +0000523 ProgramStateRef state = N->getState();
Mike Stump1eb44332009-09-09 15:08:12 +0000524
Jordan Rose364b9f92012-08-27 20:18:30 +0000525 // See if the expression we're interested refers to a variable.
526 // If so, we can track both its contents and constraints on its value.
527 if (const Expr *Ex = dyn_cast<Expr>(S)) {
528 // Strip off parens and casts. Note that this will never have issues with
529 // C++ user-defined implicit conversions, because those have a constructor
530 // or function call inside.
Jordan Rosee6cd0542012-08-16 00:03:33 +0000531 Ex = Ex->IgnoreParenCasts();
Ted Kremenek76aadc32012-03-09 01:13:14 +0000532 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Ex)) {
Jordan Rose364b9f92012-08-27 20:18:30 +0000533 // FIXME: Right now we only track VarDecls because it's non-trivial to
534 // get a MemRegion for any other DeclRefExprs. <rdar://problem/12114812>
Ted Kremenek76aadc32012-03-09 01:13:14 +0000535 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
536 const VarRegion *R =
537 StateMgr.getRegionManager().getVarRegion(VD, N->getLocationContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000538
Jordan Rose364b9f92012-08-27 20:18:30 +0000539 // Mark both the variable region and its contents as interesting.
Ted Kremenek11abcec2012-05-02 00:31:29 +0000540 SVal V = state->getRawSVal(loc::MemRegionVal(R));
Jordan Rosea1f81bb2012-08-28 00:50:51 +0000541 report.markInteresting(R);
542 report.markInteresting(V);
Anna Zaks80de4872012-08-29 21:22:37 +0000543 report.addVisitor(new UndefOrNullArgVisitor(R));
Jordan Rose68537992012-08-03 23:09:01 +0000544
Jordan Rose364b9f92012-08-27 20:18:30 +0000545 // If the contents are symbolic, find out when they became null.
Jordan Rose68537992012-08-03 23:09:01 +0000546 if (V.getAsLocSymbol()) {
547 BugReporterVisitor *ConstraintTracker
548 = new TrackConstraintBRVisitor(cast<loc::MemRegionVal>(V), false);
Jordan Rosea1f81bb2012-08-28 00:50:51 +0000549 report.addVisitor(ConstraintTracker);
Jordan Rose68537992012-08-03 23:09:01 +0000550 }
551
Jordan Rosea1f81bb2012-08-28 00:50:51 +0000552 report.addVisitor(new FindLastStoreBRVisitor(V, R));
Jordan Rose68537992012-08-03 23:09:01 +0000553 return;
Ted Kremenek53500662009-07-22 17:55:28 +0000554 }
555 }
556 }
Mike Stump1eb44332009-09-09 15:08:12 +0000557
Jordan Rose364b9f92012-08-27 20:18:30 +0000558 // If the expression does NOT refer to a variable, we can still track
559 // constraints on its contents.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000560 SVal V = state->getSValAsScalarOrLoc(S, N->getLocationContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000561
Ted Kremenek53500662009-07-22 17:55:28 +0000562 // Uncomment this to find cases where we aren't properly getting the
563 // base value that was dereferenced.
564 // assert(!V.isUnknownOrUndef());
Mike Stump1eb44332009-09-09 15:08:12 +0000565
Ted Kremenek53500662009-07-22 17:55:28 +0000566 // Is it a symbolic value?
567 if (loc::MemRegionVal *L = dyn_cast<loc::MemRegionVal>(&V)) {
Anna Zaksd91696e2012-09-05 22:31:55 +0000568 // At this point we are dealing with the region's LValue.
569 // However, if the rvalue is a symbolic region, we should track it as well.
570 SVal RVal = state->getSVal(L->getRegion());
571 const MemRegion *RegionRVal = RVal.getAsRegion();
Anna Zaks522fc212012-09-12 22:57:30 +0000572 report.addVisitor(new UndefOrNullArgVisitor(L->getRegion()));
573
Anna Zaksd91696e2012-09-05 22:31:55 +0000574
575 if (RegionRVal && isa<SymbolicRegion>(RegionRVal)) {
576 report.markInteresting(RegionRVal);
577 report.addVisitor(new TrackConstraintBRVisitor(
578 loc::MemRegionVal(RegionRVal), false));
Ted Kremenek53500662009-07-22 17:55:28 +0000579 }
Jordan Rose7aba1172012-08-28 00:50:42 +0000580 } else {
581 // Otherwise, if the value came from an inlined function call,
582 // we should at least make sure that function isn't pruned in our output.
Jordan Rosea1f81bb2012-08-28 00:50:51 +0000583 ReturnVisitor::addVisitorIfNecessary(N, S, report);
Ted Kremenek53500662009-07-22 17:55:28 +0000584 }
585}
Ted Kremenek94fd0b82010-02-16 08:33:59 +0000586
Anna Zaks50bbc162011-08-19 22:33:38 +0000587BugReporterVisitor *
588FindLastStoreBRVisitor::createVisitorObject(const ExplodedNode *N,
589 const MemRegion *R) {
590 assert(R && "The memory region is null.");
Ted Kremenek94fd0b82010-02-16 08:33:59 +0000591
Ted Kremenek8bef8232012-01-26 21:29:00 +0000592 ProgramStateRef state = N->getState();
Ted Kremenek94fd0b82010-02-16 08:33:59 +0000593 SVal V = state->getSVal(R);
Ted Kremenek94fd0b82010-02-16 08:33:59 +0000594 if (V.isUnknown())
Anna Zaks50bbc162011-08-19 22:33:38 +0000595 return 0;
Ted Kremenek94fd0b82010-02-16 08:33:59 +0000596
Anna Zaks50bbc162011-08-19 22:33:38 +0000597 return new FindLastStoreBRVisitor(V, R);
Ted Kremenek94fd0b82010-02-16 08:33:59 +0000598}
Ted Kremenekff7f7362010-03-20 18:02:01 +0000599
600
Anna Zaks50bbc162011-08-19 22:33:38 +0000601PathDiagnosticPiece *NilReceiverBRVisitor::VisitNode(const ExplodedNode *N,
602 const ExplodedNode *PrevN,
603 BugReporterContext &BRC,
604 BugReport &BR) {
605 const PostStmt *P = N->getLocationAs<PostStmt>();
606 if (!P)
607 return 0;
608 const ObjCMessageExpr *ME = P->getStmtAs<ObjCMessageExpr>();
609 if (!ME)
610 return 0;
611 const Expr *Receiver = ME->getInstanceReceiver();
612 if (!Receiver)
613 return 0;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000614 ProgramStateRef state = N->getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +0000615 const SVal &V = state->getSVal(Receiver, N->getLocationContext());
Anna Zaks50bbc162011-08-19 22:33:38 +0000616 const DefinedOrUnknownSVal *DV = dyn_cast<DefinedOrUnknownSVal>(&V);
617 if (!DV)
618 return 0;
619 state = state->assume(*DV, true);
620 if (state)
621 return 0;
Ted Kremenekff7f7362010-03-20 18:02:01 +0000622
Anna Zaks50bbc162011-08-19 22:33:38 +0000623 // The receiver was nil, and hence the method was skipped.
624 // Register a BugReporterVisitor to issue a message telling us how
625 // the receiver was null.
Jordan Rosea1f81bb2012-08-28 00:50:51 +0000626 bugreporter::trackNullOrUndefValue(N, Receiver, BR);
Anna Zaks50bbc162011-08-19 22:33:38 +0000627 // Issue a message saying that the method was skipped.
Anna Zaks220ac8c2011-09-15 01:08:34 +0000628 PathDiagnosticLocation L(Receiver, BRC.getSourceManager(),
629 N->getLocationContext());
Anna Zaks907344e2012-04-05 02:10:19 +0000630 return new PathDiagnosticEventPiece(L, "No method is called "
Anna Zaks50bbc162011-08-19 22:33:38 +0000631 "because the receiver is nil");
Ted Kremenekff7f7362010-03-20 18:02:01 +0000632}
Tom Care2bbbe502010-09-02 23:30:22 +0000633
Anna Zaks8e6431a2011-08-18 22:37:56 +0000634// Registers every VarDecl inside a Stmt with a last store visitor.
Anna Zaks50bbc162011-08-19 22:33:38 +0000635void FindLastStoreBRVisitor::registerStatementVarDecls(BugReport &BR,
636 const Stmt *S) {
Anna Zaks8e6431a2011-08-18 22:37:56 +0000637 const ExplodedNode *N = BR.getErrorNode();
Tom Care2bbbe502010-09-02 23:30:22 +0000638 std::deque<const Stmt *> WorkList;
Tom Care2bbbe502010-09-02 23:30:22 +0000639 WorkList.push_back(S);
640
641 while (!WorkList.empty()) {
642 const Stmt *Head = WorkList.front();
643 WorkList.pop_front();
644
Ted Kremenek8bef8232012-01-26 21:29:00 +0000645 ProgramStateRef state = N->getState();
Anna Zaks8e6431a2011-08-18 22:37:56 +0000646 ProgramStateManager &StateMgr = state->getStateManager();
Tom Care2bbbe502010-09-02 23:30:22 +0000647
648 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Head)) {
649 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
650 const VarRegion *R =
651 StateMgr.getRegionManager().getVarRegion(VD, N->getLocationContext());
652
653 // What did we load?
Ted Kremenek5eca4822012-01-06 22:09:28 +0000654 SVal V = state->getSVal(S, N->getLocationContext());
Tom Care2bbbe502010-09-02 23:30:22 +0000655
656 if (isa<loc::ConcreteInt>(V) || isa<nonloc::ConcreteInt>(V)) {
Anna Zaks50bbc162011-08-19 22:33:38 +0000657 // Register a new visitor with the BugReport.
658 BR.addVisitor(new FindLastStoreBRVisitor(V, R));
Tom Care2bbbe502010-09-02 23:30:22 +0000659 }
660 }
661 }
662
663 for (Stmt::const_child_iterator I = Head->child_begin();
664 I != Head->child_end(); ++I)
665 WorkList.push_back(*I);
666 }
667}
Ted Kremenek993124e2011-08-06 06:54:45 +0000668
669//===----------------------------------------------------------------------===//
670// Visitor that tries to report interesting diagnostics from conditions.
671//===----------------------------------------------------------------------===//
Anna Zaks50bbc162011-08-19 22:33:38 +0000672PathDiagnosticPiece *ConditionBRVisitor::VisitNode(const ExplodedNode *N,
673 const ExplodedNode *Prev,
674 BugReporterContext &BRC,
675 BugReport &BR) {
Ted Kremenekc89f4b02012-02-28 23:06:21 +0000676 PathDiagnosticPiece *piece = VisitNodeImpl(N, Prev, BRC, BR);
677 if (PathDiagnosticEventPiece *ev =
678 dyn_cast_or_null<PathDiagnosticEventPiece>(piece))
Ted Kremenek76aadc32012-03-09 01:13:14 +0000679 ev->setPrunable(true, /* override */ false);
Ted Kremenekc89f4b02012-02-28 23:06:21 +0000680 return piece;
681}
682
683PathDiagnosticPiece *ConditionBRVisitor::VisitNodeImpl(const ExplodedNode *N,
684 const ExplodedNode *Prev,
685 BugReporterContext &BRC,
686 BugReport &BR) {
Ted Kremenek993124e2011-08-06 06:54:45 +0000687
Ted Kremenek22505ef2012-09-08 07:18:18 +0000688 ProgramPoint progPoint = N->getLocation();
Ted Kremenek8bef8232012-01-26 21:29:00 +0000689 ProgramStateRef CurrentState = N->getState();
690 ProgramStateRef PrevState = Prev->getState();
Ted Kremenek681bc112011-08-16 01:53:41 +0000691
692 // Compare the GDMs of the state, because that is where constraints
693 // are managed. Note that ensure that we only look at nodes that
694 // were generated by the analyzer engine proper, not checkers.
695 if (CurrentState->getGDM().getRoot() ==
696 PrevState->getGDM().getRoot())
697 return 0;
Ted Kremenek993124e2011-08-06 06:54:45 +0000698
699 // If an assumption was made on a branch, it should be caught
700 // here by looking at the state transition.
701 if (const BlockEdge *BE = dyn_cast<BlockEdge>(&progPoint)) {
Ted Kremenek681bc112011-08-16 01:53:41 +0000702 const CFGBlock *srcBlk = BE->getSrc();
703 if (const Stmt *term = srcBlk->getTerminator())
Ted Kremenek76aadc32012-03-09 01:13:14 +0000704 return VisitTerminator(term, N, srcBlk, BE->getDst(), BR, BRC);
Ted Kremenek681bc112011-08-16 01:53:41 +0000705 return 0;
706 }
707
708 if (const PostStmt *PS = dyn_cast<PostStmt>(&progPoint)) {
709 // FIXME: Assuming that BugReporter is a GRBugReporter is a layering
710 // violation.
711 const std::pair<const ProgramPointTag *, const ProgramPointTag *> &tags =
712 cast<GRBugReporter>(BRC.getBugReporter()).
Ted Kremenek0caa2d42012-08-30 19:26:48 +0000713 getEngine().geteagerlyAssumeBinOpBifurcationTags();
Ted Kremenek681bc112011-08-16 01:53:41 +0000714
715 const ProgramPointTag *tag = PS->getTag();
716 if (tag == tags.first)
Anna Zaks220ac8c2011-09-15 01:08:34 +0000717 return VisitTrueTest(cast<Expr>(PS->getStmt()), true,
Ted Kremenek76aadc32012-03-09 01:13:14 +0000718 BRC, BR, N);
Ted Kremenek681bc112011-08-16 01:53:41 +0000719 if (tag == tags.second)
Anna Zaks220ac8c2011-09-15 01:08:34 +0000720 return VisitTrueTest(cast<Expr>(PS->getStmt()), false,
Ted Kremenek76aadc32012-03-09 01:13:14 +0000721 BRC, BR, N);
Ted Kremenek681bc112011-08-16 01:53:41 +0000722
Ted Kremenek993124e2011-08-06 06:54:45 +0000723 return 0;
724 }
725
726 return 0;
727}
728
729PathDiagnosticPiece *
Anna Zaks50bbc162011-08-19 22:33:38 +0000730ConditionBRVisitor::VisitTerminator(const Stmt *Term,
Anna Zaks220ac8c2011-09-15 01:08:34 +0000731 const ExplodedNode *N,
Anna Zaks50bbc162011-08-19 22:33:38 +0000732 const CFGBlock *srcBlk,
733 const CFGBlock *dstBlk,
Ted Kremenek76aadc32012-03-09 01:13:14 +0000734 BugReport &R,
Anna Zaks50bbc162011-08-19 22:33:38 +0000735 BugReporterContext &BRC) {
Ted Kremenek993124e2011-08-06 06:54:45 +0000736 const Expr *Cond = 0;
737
738 switch (Term->getStmtClass()) {
739 default:
740 return 0;
741 case Stmt::IfStmtClass:
742 Cond = cast<IfStmt>(Term)->getCond();
743 break;
744 case Stmt::ConditionalOperatorClass:
745 Cond = cast<ConditionalOperator>(Term)->getCond();
746 break;
747 }
748
749 assert(Cond);
750 assert(srcBlk->succ_size() == 2);
751 const bool tookTrue = *(srcBlk->succ_begin()) == dstBlk;
Ted Kremenekc47dc1b2012-09-07 06:51:37 +0000752 return VisitTrueTest(Cond, tookTrue, BRC, R, N);
Ted Kremenek993124e2011-08-06 06:54:45 +0000753}
754
755PathDiagnosticPiece *
Anna Zaks50bbc162011-08-19 22:33:38 +0000756ConditionBRVisitor::VisitTrueTest(const Expr *Cond,
757 bool tookTrue,
Anna Zaks220ac8c2011-09-15 01:08:34 +0000758 BugReporterContext &BRC,
Ted Kremenek76aadc32012-03-09 01:13:14 +0000759 BugReport &R,
760 const ExplodedNode *N) {
Ted Kremenek993124e2011-08-06 06:54:45 +0000761
762 const Expr *Ex = Cond;
763
Ted Kremenek681bc112011-08-16 01:53:41 +0000764 while (true) {
Ted Kremenekc47dc1b2012-09-07 06:51:37 +0000765 Ex = Ex->IgnoreParenCasts();
Ted Kremenek993124e2011-08-06 06:54:45 +0000766 switch (Ex->getStmtClass()) {
767 default:
768 return 0;
Ted Kremenek681bc112011-08-16 01:53:41 +0000769 case Stmt::BinaryOperatorClass:
Ted Kremenek76aadc32012-03-09 01:13:14 +0000770 return VisitTrueTest(Cond, cast<BinaryOperator>(Ex), tookTrue, BRC,
771 R, N);
Ted Kremenek993124e2011-08-06 06:54:45 +0000772 case Stmt::DeclRefExprClass:
Ted Kremenek76aadc32012-03-09 01:13:14 +0000773 return VisitTrueTest(Cond, cast<DeclRefExpr>(Ex), tookTrue, BRC,
774 R, N);
Ted Kremenek993124e2011-08-06 06:54:45 +0000775 case Stmt::UnaryOperatorClass: {
776 const UnaryOperator *UO = cast<UnaryOperator>(Ex);
777 if (UO->getOpcode() == UO_LNot) {
778 tookTrue = !tookTrue;
Ted Kremenekc47dc1b2012-09-07 06:51:37 +0000779 Ex = UO->getSubExpr();
Ted Kremenek993124e2011-08-06 06:54:45 +0000780 continue;
781 }
782 return 0;
783 }
784 }
Ted Kremenek681bc112011-08-16 01:53:41 +0000785 }
786}
787
Anna Zaks50bbc162011-08-19 22:33:38 +0000788bool ConditionBRVisitor::patternMatch(const Expr *Ex, llvm::raw_ostream &Out,
Ted Kremenek76aadc32012-03-09 01:13:14 +0000789 BugReporterContext &BRC,
790 BugReport &report,
791 const ExplodedNode *N,
792 llvm::Optional<bool> &prunable) {
Ted Kremenek681bc112011-08-16 01:53:41 +0000793 const Expr *OriginalExpr = Ex;
794 Ex = Ex->IgnoreParenCasts();
795
796 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Ex)) {
Ted Kremenek3b9e8e42011-08-16 10:57:37 +0000797 const bool quotes = isa<VarDecl>(DR->getDecl());
Ted Kremenek76aadc32012-03-09 01:13:14 +0000798 if (quotes) {
Ted Kremenek3b9e8e42011-08-16 10:57:37 +0000799 Out << '\'';
Ted Kremenek76aadc32012-03-09 01:13:14 +0000800 const LocationContext *LCtx = N->getLocationContext();
801 const ProgramState *state = N->getState().getPtr();
802 if (const MemRegion *R = state->getLValue(cast<VarDecl>(DR->getDecl()),
803 LCtx).getAsRegion()) {
804 if (report.isInteresting(R))
805 prunable = false;
806 else {
807 const ProgramState *state = N->getState().getPtr();
808 SVal V = state->getSVal(R);
809 if (report.isInteresting(V))
810 prunable = false;
811 }
812 }
813 }
Ted Kremenek3b9e8e42011-08-16 10:57:37 +0000814 Out << DR->getDecl()->getDeclName().getAsString();
815 if (quotes)
816 Out << '\'';
817 return quotes;
Ted Kremenek681bc112011-08-16 01:53:41 +0000818 }
819
820 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(Ex)) {
821 QualType OriginalTy = OriginalExpr->getType();
822 if (OriginalTy->isPointerType()) {
823 if (IL->getValue() == 0) {
824 Out << "null";
Ted Kremenek3b9e8e42011-08-16 10:57:37 +0000825 return false;
Ted Kremenek681bc112011-08-16 01:53:41 +0000826 }
827 }
828 else if (OriginalTy->isObjCObjectPointerType()) {
829 if (IL->getValue() == 0) {
830 Out << "nil";
Ted Kremenek3b9e8e42011-08-16 10:57:37 +0000831 return false;
Ted Kremenek681bc112011-08-16 01:53:41 +0000832 }
833 }
834
835 Out << IL->getValue();
Ted Kremenek3b9e8e42011-08-16 10:57:37 +0000836 return false;
Ted Kremenek681bc112011-08-16 01:53:41 +0000837 }
Ted Kremenek3b9e8e42011-08-16 10:57:37 +0000838
839 return false;
Ted Kremenek681bc112011-08-16 01:53:41 +0000840}
841
842PathDiagnosticPiece *
Anna Zaks50bbc162011-08-19 22:33:38 +0000843ConditionBRVisitor::VisitTrueTest(const Expr *Cond,
844 const BinaryOperator *BExpr,
845 const bool tookTrue,
Anna Zaks220ac8c2011-09-15 01:08:34 +0000846 BugReporterContext &BRC,
Ted Kremenek76aadc32012-03-09 01:13:14 +0000847 BugReport &R,
848 const ExplodedNode *N) {
Ted Kremenek681bc112011-08-16 01:53:41 +0000849
Ted Kremenek3b9e8e42011-08-16 10:57:37 +0000850 bool shouldInvert = false;
Ted Kremenek76aadc32012-03-09 01:13:14 +0000851 llvm::Optional<bool> shouldPrune;
Ted Kremenek3b9e8e42011-08-16 10:57:37 +0000852
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000853 SmallString<128> LhsString, RhsString;
Ted Kremenek681bc112011-08-16 01:53:41 +0000854 {
Ted Kremenek76aadc32012-03-09 01:13:14 +0000855 llvm::raw_svector_ostream OutLHS(LhsString), OutRHS(RhsString);
856 const bool isVarLHS = patternMatch(BExpr->getLHS(), OutLHS, BRC, R, N,
857 shouldPrune);
858 const bool isVarRHS = patternMatch(BExpr->getRHS(), OutRHS, BRC, R, N,
859 shouldPrune);
Ted Kremenek3b9e8e42011-08-16 10:57:37 +0000860
861 shouldInvert = !isVarLHS && isVarRHS;
Ted Kremenek681bc112011-08-16 01:53:41 +0000862 }
863
Ted Kremenekd1247c52012-01-04 08:18:09 +0000864 BinaryOperator::Opcode Op = BExpr->getOpcode();
865
866 if (BinaryOperator::isAssignmentOp(Op)) {
867 // For assignment operators, all that we care about is that the LHS
868 // evaluates to "true" or "false".
869 return VisitConditionVariable(LhsString, BExpr->getLHS(), tookTrue,
Ted Kremenek76aadc32012-03-09 01:13:14 +0000870 BRC, R, N);
Ted Kremenekd1247c52012-01-04 08:18:09 +0000871 }
872
873 // For non-assignment operations, we require that we can understand
874 // both the LHS and RHS.
Ted Kremenek681bc112011-08-16 01:53:41 +0000875 if (LhsString.empty() || RhsString.empty())
876 return 0;
Ted Kremenek3b9e8e42011-08-16 10:57:37 +0000877
Ted Kremenekd1247c52012-01-04 08:18:09 +0000878 // Should we invert the strings if the LHS is not a variable name?
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000879 SmallString<256> buf;
Ted Kremenek681bc112011-08-16 01:53:41 +0000880 llvm::raw_svector_ostream Out(buf);
Ted Kremenek3b9e8e42011-08-16 10:57:37 +0000881 Out << "Assuming " << (shouldInvert ? RhsString : LhsString) << " is ";
Ted Kremenek681bc112011-08-16 01:53:41 +0000882
883 // Do we need to invert the opcode?
Ted Kremenek3b9e8e42011-08-16 10:57:37 +0000884 if (shouldInvert)
885 switch (Op) {
886 default: break;
887 case BO_LT: Op = BO_GT; break;
888 case BO_GT: Op = BO_LT; break;
889 case BO_LE: Op = BO_GE; break;
890 case BO_GE: Op = BO_LE; break;
891 }
892
Ted Kremenek681bc112011-08-16 01:53:41 +0000893 if (!tookTrue)
894 switch (Op) {
895 case BO_EQ: Op = BO_NE; break;
896 case BO_NE: Op = BO_EQ; break;
897 case BO_LT: Op = BO_GE; break;
898 case BO_GT: Op = BO_LE; break;
899 case BO_LE: Op = BO_GT; break;
Ted Kremenek4ee7c9c2011-08-16 03:44:38 +0000900 case BO_GE: Op = BO_LT; break;
Ted Kremenek681bc112011-08-16 01:53:41 +0000901 default:
902 return 0;
903 }
904
Ted Kremenek6ae32572011-12-20 22:00:25 +0000905 switch (Op) {
Ted Kremenek681bc112011-08-16 01:53:41 +0000906 case BO_EQ:
907 Out << "equal to ";
908 break;
909 case BO_NE:
910 Out << "not equal to ";
911 break;
912 default:
913 Out << BinaryOperator::getOpcodeStr(Op) << ' ';
914 break;
915 }
916
Ted Kremenek3b9e8e42011-08-16 10:57:37 +0000917 Out << (shouldInvert ? LhsString : RhsString);
Ted Kremenek76aadc32012-03-09 01:13:14 +0000918 const LocationContext *LCtx = N->getLocationContext();
919 PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
920 PathDiagnosticEventPiece *event =
921 new PathDiagnosticEventPiece(Loc, Out.str());
922 if (shouldPrune.hasValue())
923 event->setPrunable(shouldPrune.getValue());
924 return event;
Ted Kremenek993124e2011-08-06 06:54:45 +0000925}
Ted Kremenekd1247c52012-01-04 08:18:09 +0000926
927PathDiagnosticPiece *
928ConditionBRVisitor::VisitConditionVariable(StringRef LhsString,
929 const Expr *CondVarExpr,
930 const bool tookTrue,
931 BugReporterContext &BRC,
Ted Kremenek76aadc32012-03-09 01:13:14 +0000932 BugReport &report,
933 const ExplodedNode *N) {
Jordan Roseb0e1bad2012-08-03 23:08:54 +0000934 // FIXME: If there's already a constraint tracker for this variable,
935 // we shouldn't emit anything here (c.f. the double note in
936 // test/Analysis/inlining/path-notes.c)
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000937 SmallString<256> buf;
Ted Kremenekd1247c52012-01-04 08:18:09 +0000938 llvm::raw_svector_ostream Out(buf);
939 Out << "Assuming " << LhsString << " is ";
940
941 QualType Ty = CondVarExpr->getType();
942
943 if (Ty->isPointerType())
944 Out << (tookTrue ? "not null" : "null");
945 else if (Ty->isObjCObjectPointerType())
946 Out << (tookTrue ? "not nil" : "nil");
947 else if (Ty->isBooleanType())
948 Out << (tookTrue ? "true" : "false");
949 else if (Ty->isIntegerType())
950 Out << (tookTrue ? "non-zero" : "zero");
951 else
952 return 0;
953
Ted Kremenek76aadc32012-03-09 01:13:14 +0000954 const LocationContext *LCtx = N->getLocationContext();
955 PathDiagnosticLocation Loc(CondVarExpr, BRC.getSourceManager(), LCtx);
956 PathDiagnosticEventPiece *event =
957 new PathDiagnosticEventPiece(Loc, Out.str());
958
959 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(CondVarExpr)) {
960 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
961 const ProgramState *state = N->getState().getPtr();
962 if (const MemRegion *R = state->getLValue(VD, LCtx).getAsRegion()) {
963 if (report.isInteresting(R))
964 event->setPrunable(false);
965 }
966 }
967 }
968
969 return event;
Ted Kremenekd1247c52012-01-04 08:18:09 +0000970}
Ted Kremenek993124e2011-08-06 06:54:45 +0000971
972PathDiagnosticPiece *
Anna Zaks50bbc162011-08-19 22:33:38 +0000973ConditionBRVisitor::VisitTrueTest(const Expr *Cond,
974 const DeclRefExpr *DR,
975 const bool tookTrue,
Anna Zaks220ac8c2011-09-15 01:08:34 +0000976 BugReporterContext &BRC,
Ted Kremenek76aadc32012-03-09 01:13:14 +0000977 BugReport &report,
978 const ExplodedNode *N) {
Ted Kremenek993124e2011-08-06 06:54:45 +0000979
980 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
981 if (!VD)
982 return 0;
983
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000984 SmallString<256> Buf;
Ted Kremenek993124e2011-08-06 06:54:45 +0000985 llvm::raw_svector_ostream Out(Buf);
986
987 Out << "Assuming '";
988 VD->getDeclName().printName(Out);
989 Out << "' is ";
990
991 QualType VDTy = VD->getType();
992
993 if (VDTy->isPointerType())
994 Out << (tookTrue ? "non-null" : "null");
995 else if (VDTy->isObjCObjectPointerType())
996 Out << (tookTrue ? "non-nil" : "nil");
997 else if (VDTy->isScalarType())
998 Out << (tookTrue ? "not equal to 0" : "0");
999 else
1000 return 0;
1001
Ted Kremenek76aadc32012-03-09 01:13:14 +00001002 const LocationContext *LCtx = N->getLocationContext();
1003 PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
1004 PathDiagnosticEventPiece *event =
1005 new PathDiagnosticEventPiece(Loc, Out.str());
1006
1007 const ProgramState *state = N->getState().getPtr();
1008 if (const MemRegion *R = state->getLValue(VD, LCtx).getAsRegion()) {
1009 if (report.isInteresting(R))
1010 event->setPrunable(false);
1011 else {
1012 SVal V = state->getSVal(R);
1013 if (report.isInteresting(V))
1014 event->setPrunable(false);
1015 }
1016 }
1017 return event;
Ted Kremenek993124e2011-08-06 06:54:45 +00001018}
Ted Kremenek0cf3d472012-02-07 00:24:33 +00001019
Anna Zaks80de4872012-08-29 21:22:37 +00001020PathDiagnosticPiece *
1021UndefOrNullArgVisitor::VisitNode(const ExplodedNode *N,
1022 const ExplodedNode *PrevN,
1023 BugReporterContext &BRC,
1024 BugReport &BR) {
1025
1026 ProgramStateRef State = N->getState();
1027 ProgramPoint ProgLoc = N->getLocation();
1028
1029 // We are only interested in visiting CallEnter nodes.
1030 CallEnter *CEnter = dyn_cast<CallEnter>(&ProgLoc);
1031 if (!CEnter)
1032 return 0;
1033
1034 // Check if one of the arguments is the region the visitor is tracking.
1035 CallEventManager &CEMgr = BRC.getStateManager().getCallEventManager();
1036 CallEventRef<> Call = CEMgr.getCaller(CEnter->getCalleeContext(), State);
1037 unsigned Idx = 0;
1038 for (CallEvent::param_iterator I = Call->param_begin(),
1039 E = Call->param_end(); I != E; ++I, ++Idx) {
1040 const MemRegion *ArgReg = Call->getArgSVal(Idx).getAsRegion();
1041
Anna Zaks522fc212012-09-12 22:57:30 +00001042 // Are we tracking the argument or its subregion?
1043 if ( !ArgReg || (ArgReg != R && !R->isSubRegionOf(ArgReg->StripCasts())))
Anna Zaks28694c12012-08-29 23:23:39 +00001044 continue;
Anna Zaks80de4872012-08-29 21:22:37 +00001045
1046 // Check the function parameter type.
1047 const ParmVarDecl *ParamDecl = *I;
1048 assert(ParamDecl && "Formal parameter has no decl?");
1049 QualType T = ParamDecl->getType();
1050
1051 if (!(T->isAnyPointerType() || T->isReferenceType())) {
1052 // Function can only change the value passed in by address.
Anna Zaks28694c12012-08-29 23:23:39 +00001053 continue;
Anna Zaks80de4872012-08-29 21:22:37 +00001054 }
1055
1056 // If it is a const pointer value, the function does not intend to
1057 // change the value.
1058 if (T->getPointeeType().isConstQualified())
Anna Zaks28694c12012-08-29 23:23:39 +00001059 continue;
Anna Zaks80de4872012-08-29 21:22:37 +00001060
1061 // Mark the call site (LocationContext) as interesting if the value of the
1062 // argument is undefined or '0'/'NULL'.
Anna Zaks522fc212012-09-12 22:57:30 +00001063 SVal BoundVal = State->getSVal(R);
Anna Zaks80de4872012-08-29 21:22:37 +00001064 if (BoundVal.isUndef() || BoundVal.isZeroConstant()) {
1065 BR.markInteresting(CEnter->getCalleeContext());
1066 return 0;
1067 }
1068 }
1069 return 0;
1070}