blob: e26e2069c7bf64977d9c274f9b2c93023ba85a66 [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#include "clang/AST/Expr.h"
16#include "clang/AST/ExprObjC.h"
Ted Kremenek9b663712011-02-10 01:03:03 +000017#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
18#include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
Anna Zaks80de4872012-08-29 21:22:37 +000019#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000020#include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
21#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
22#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
Benjamin Kramer8fe83e12012-02-04 13:45:25 +000023#include "llvm/ADT/SmallString.h"
Jordan Rose85e99372012-09-22 01:24:46 +000024#include "llvm/ADT/StringExtras.h"
Benjamin Kramera93d0f22012-12-01 17:12:56 +000025#include "llvm/Support/raw_ostream.h"
Ted Kremenek53500662009-07-22 17:55:28 +000026
27using namespace clang;
Ted Kremenek9ef65372010-12-23 07:20:52 +000028using namespace ento;
Ted Kremenek53500662009-07-22 17:55:28 +000029
30//===----------------------------------------------------------------------===//
31// Utility functions.
32//===----------------------------------------------------------------------===//
33
Anna Zaks9b925ac2012-09-05 23:41:54 +000034bool bugreporter::isDeclRefExprToReference(const Expr *E) {
35 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
36 return DRE->getDecl()->getType()->isReferenceType();
37 }
38 return false;
39}
40
Argyrios Kyrtzidis5a4f98f2010-12-22 18:53:20 +000041const Stmt *bugreporter::GetDerefExpr(const ExplodedNode *N) {
Ted Kremenek53500662009-07-22 17:55:28 +000042 // Pattern match for a few useful cases (do something smarter later):
43 // a[0], p->f, *p
Jordan Rose3682f1e2012-08-25 01:06:23 +000044 const PostStmt *Loc = N->getLocationAs<PostStmt>();
45 if (!Loc)
46 return 0;
47
Jordan Rose364b9f92012-08-27 20:18:30 +000048 const Expr *S = dyn_cast<Expr>(Loc->getStmt());
49 if (!S)
50 return 0;
51 S = S->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +000052
Ted Kremenek11abcec2012-05-02 00:31:29 +000053 while (true) {
54 if (const BinaryOperator *B = dyn_cast<BinaryOperator>(S)) {
55 assert(B->isAssignmentOp());
56 S = B->getLHS()->IgnoreParenCasts();
57 continue;
58 }
59 else if (const UnaryOperator *U = dyn_cast<UnaryOperator>(S)) {
60 if (U->getOpcode() == UO_Deref)
61 return U->getSubExpr()->IgnoreParenCasts();
62 }
63 else if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
Anna Zaks9b925ac2012-09-05 23:41:54 +000064 if (ME->isArrow() || isDeclRefExprToReference(ME->getBase())) {
Anna Zaksd91696e2012-09-05 22:31:55 +000065 return ME->getBase()->IgnoreParenCasts();
66 }
Ted Kremenek11abcec2012-05-02 00:31:29 +000067 }
Jordan Rose991bcb42012-09-22 01:24:38 +000068 else if (const ObjCIvarRefExpr *IvarRef = dyn_cast<ObjCIvarRefExpr>(S)) {
69 return IvarRef->getBase()->IgnoreParenCasts();
70 }
Ted Kremenek11abcec2012-05-02 00:31:29 +000071 else if (const ArraySubscriptExpr *AE = dyn_cast<ArraySubscriptExpr>(S)) {
72 return AE->getBase();
73 }
74 break;
Ted Kremenek53500662009-07-22 17:55:28 +000075 }
Mike Stump1eb44332009-09-09 15:08:12 +000076
77 return NULL;
Ted Kremenek53500662009-07-22 17:55:28 +000078}
79
Argyrios Kyrtzidis5a4f98f2010-12-22 18:53:20 +000080const Stmt *bugreporter::GetDenomExpr(const ExplodedNode *N) {
Zhongxing Xu6403b572009-09-02 13:26:26 +000081 const Stmt *S = N->getLocationAs<PreStmt>()->getStmt();
Ted Kremenek53500662009-07-22 17:55:28 +000082 if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(S))
83 return BE->getRHS();
84 return NULL;
85}
86
Argyrios Kyrtzidis5a4f98f2010-12-22 18:53:20 +000087const Stmt *bugreporter::GetRetValExpr(const ExplodedNode *N) {
Ted Kremenek53500662009-07-22 17:55:28 +000088 const Stmt *S = N->getLocationAs<PostStmt>()->getStmt();
89 if (const ReturnStmt *RS = dyn_cast<ReturnStmt>(S))
90 return RS->getRetValue();
91 return NULL;
92}
93
94//===----------------------------------------------------------------------===//
95// Definitions for bug reporter visitors.
96//===----------------------------------------------------------------------===//
Anna Zaks23f395e2011-08-20 01:27:22 +000097
98PathDiagnosticPiece*
99BugReporterVisitor::getEndPath(BugReporterContext &BRC,
100 const ExplodedNode *EndPathNode,
101 BugReport &BR) {
102 return 0;
103}
104
105PathDiagnosticPiece*
106BugReporterVisitor::getDefaultEndPath(BugReporterContext &BRC,
107 const ExplodedNode *EndPathNode,
108 BugReport &BR) {
Anna Zaks5a0917d2012-02-16 03:41:01 +0000109 PathDiagnosticLocation L =
110 PathDiagnosticLocation::createEndOfPath(EndPathNode,BRC.getSourceManager());
Anna Zaks23f395e2011-08-20 01:27:22 +0000111
112 BugReport::ranges_iterator Beg, End;
113 llvm::tie(Beg, End) = BR.getRanges();
114
115 // Only add the statement itself as a range if we didn't specify any
116 // special ranges for this report.
117 PathDiagnosticPiece *P = new PathDiagnosticEventPiece(L,
118 BR.getDescription(),
119 Beg == End);
120 for (; Beg != End; ++Beg)
121 P->addRange(*Beg);
122
123 return P;
124}
125
126
Jordan Rose7aba1172012-08-28 00:50:42 +0000127namespace {
128/// Emits an extra note at the return statement of an interesting stack frame.
129///
130/// The returned value is marked as an interesting value, and if it's null,
131/// adds a visitor to track where it became null.
132///
133/// This visitor is intended to be used when another visitor discovers that an
134/// interesting value comes from an inlined function call.
135class ReturnVisitor : public BugReporterVisitorImpl<ReturnVisitor> {
136 const StackFrameContext *StackFrame;
Jordan Rose6a329ee2012-10-29 17:31:59 +0000137 enum {
138 Initial,
139 MaybeSuppress,
140 Satisfied
141 } Mode;
142
Jordan Rose7aba1172012-08-28 00:50:42 +0000143public:
144 ReturnVisitor(const StackFrameContext *Frame)
Jordan Rose6a329ee2012-10-29 17:31:59 +0000145 : StackFrame(Frame), Mode(Initial) {}
Jordan Rose7aba1172012-08-28 00:50:42 +0000146
Jordan Roseb9d4e5e2012-09-22 01:25:06 +0000147 static void *getTag() {
Jordan Rose7aba1172012-08-28 00:50:42 +0000148 static int Tag = 0;
Jordan Roseb9d4e5e2012-09-22 01:25:06 +0000149 return static_cast<void *>(&Tag);
150 }
151
152 virtual void Profile(llvm::FoldingSetNodeID &ID) const {
153 ID.AddPointer(ReturnVisitor::getTag());
Jordan Rose7aba1172012-08-28 00:50:42 +0000154 ID.AddPointer(StackFrame);
155 }
156
157 /// Adds a ReturnVisitor if the given statement represents a call that was
158 /// inlined.
159 ///
160 /// This will search back through the ExplodedGraph, starting from the given
161 /// node, looking for when the given statement was processed. If it turns out
162 /// the statement is a call that was inlined, we add the visitor to the
163 /// bug report, so it can print a note later.
164 static void addVisitorIfNecessary(const ExplodedNode *Node, const Stmt *S,
165 BugReport &BR) {
166 if (!CallEvent::isCallStmt(S))
167 return;
168
169 // First, find when we processed the statement.
170 do {
171 if (const CallExitEnd *CEE = Node->getLocationAs<CallExitEnd>())
172 if (CEE->getCalleeContext()->getCallSite() == S)
173 break;
174 if (const StmtPoint *SP = Node->getLocationAs<StmtPoint>())
175 if (SP->getStmt() == S)
176 break;
177
178 Node = Node->getFirstPred();
179 } while (Node);
180
181 // Next, step over any post-statement checks.
182 while (Node && isa<PostStmt>(Node->getLocation()))
183 Node = Node->getFirstPred();
184
185 // Finally, see if we inlined the call.
Jordan Rose53221da2012-09-22 01:25:00 +0000186 if (Node) {
187 if (const CallExitEnd *CEE = Node->getLocationAs<CallExitEnd>()) {
188 const StackFrameContext *CalleeContext = CEE->getCalleeContext();
189 if (CalleeContext->getCallSite() == S) {
190 BR.markInteresting(CalleeContext);
191 BR.addVisitor(new ReturnVisitor(CalleeContext));
192 }
193 }
194 }
Jordan Rose7aba1172012-08-28 00:50:42 +0000195 }
196
Jordan Rose6a329ee2012-10-29 17:31:59 +0000197 /// Returns true if any counter-suppression heuristics are enabled for
198 /// ReturnVisitor.
199 static bool hasCounterSuppression(AnalyzerOptions &Options) {
200 return Options.shouldAvoidSuppressingNullArgumentPaths();
201 }
Jordan Rose7aba1172012-08-28 00:50:42 +0000202
Jordan Rose6a329ee2012-10-29 17:31:59 +0000203 PathDiagnosticPiece *visitNodeInitial(const ExplodedNode *N,
204 const ExplodedNode *PrevN,
205 BugReporterContext &BRC,
206 BugReport &BR) {
Jordan Rose7aba1172012-08-28 00:50:42 +0000207 // Only print a message at the interesting return statement.
208 if (N->getLocationContext() != StackFrame)
209 return 0;
210
211 const StmtPoint *SP = N->getLocationAs<StmtPoint>();
212 if (!SP)
213 return 0;
214
215 const ReturnStmt *Ret = dyn_cast<ReturnStmt>(SP->getStmt());
216 if (!Ret)
217 return 0;
218
219 // Okay, we're at the right return statement, but do we have the return
220 // value available?
221 ProgramStateRef State = N->getState();
222 SVal V = State->getSVal(Ret, StackFrame);
223 if (V.isUnknownOrUndef())
224 return 0;
225
226 // Don't print any more notes after this one.
Jordan Rose6a329ee2012-10-29 17:31:59 +0000227 Mode = Satisfied;
Jordan Rose7aba1172012-08-28 00:50:42 +0000228
Jordan Rose7aba1172012-08-28 00:50:42 +0000229 const Expr *RetE = Ret->getRetValue();
230 assert(RetE && "Tracking a return value for a void function");
231 RetE = RetE->IgnoreParenCasts();
232
Jordan Rose53221da2012-09-22 01:25:00 +0000233 // If we can't prove the return value is 0, just mark it interesting, and
234 // make sure to track it into any further inner functions.
235 if (State->assume(cast<DefinedSVal>(V), true)) {
Jordan Rose7aba1172012-08-28 00:50:42 +0000236 BR.markInteresting(V);
Jordan Rose53221da2012-09-22 01:25:00 +0000237 ReturnVisitor::addVisitorIfNecessary(N, RetE, BR);
238 return 0;
239 }
240
241 // If we're returning 0, we should track where that 0 came from.
242 bugreporter::trackNullOrUndefValue(N, RetE, BR);
243
Jordan Roseb9d4e5e2012-09-22 01:25:06 +0000244 // Build an appropriate message based on the return value.
245 SmallString<64> Msg;
246 llvm::raw_svector_ostream Out(Msg);
247
Jordan Rose53221da2012-09-22 01:25:00 +0000248 if (isa<Loc>(V)) {
Jordan Roseb9d4e5e2012-09-22 01:25:06 +0000249 // If we are pruning null-return paths as unlikely error paths, mark the
250 // report invalid. We still want to emit a path note, however, in case
251 // the report is resurrected as valid later on.
252 ExprEngine &Eng = BRC.getBugReporter().getEngine();
Jordan Rose6a329ee2012-10-29 17:31:59 +0000253 AnalyzerOptions &Options = Eng.getAnalysisManager().options;
254 if (Options.shouldPruneNullReturnPaths()) {
255 if (hasCounterSuppression(Options))
256 Mode = MaybeSuppress;
257 else
258 BR.markInvalid(ReturnVisitor::getTag(), StackFrame);
259 }
Jordan Roseb9d4e5e2012-09-22 01:25:06 +0000260
Jordan Rose53221da2012-09-22 01:25:00 +0000261 if (RetE->getType()->isObjCObjectPointerType())
262 Out << "Returning nil";
263 else
264 Out << "Returning null pointer";
265 } else {
266 Out << "Returning zero";
Jordan Rose7aba1172012-08-28 00:50:42 +0000267 }
268
269 // FIXME: We should have a more generalized location printing mechanism.
270 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(RetE))
271 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(DR->getDecl()))
272 Out << " (loaded from '" << *DD << "')";
273
274 PathDiagnosticLocation L(Ret, BRC.getSourceManager(), StackFrame);
275 return new PathDiagnosticEventPiece(L, Out.str());
276 }
Jordan Rose6a329ee2012-10-29 17:31:59 +0000277
278 PathDiagnosticPiece *visitNodeMaybeSuppress(const ExplodedNode *N,
279 const ExplodedNode *PrevN,
280 BugReporterContext &BRC,
281 BugReport &BR) {
282 // Are we at the entry node for this call?
283 const CallEnter *CE = N->getLocationAs<CallEnter>();
284 if (!CE)
285 return 0;
286
287 if (CE->getCalleeContext() != StackFrame)
288 return 0;
289
290 Mode = Satisfied;
291
292 ExprEngine &Eng = BRC.getBugReporter().getEngine();
293 AnalyzerOptions &Options = Eng.getAnalysisManager().options;
294 if (Options.shouldAvoidSuppressingNullArgumentPaths()) {
295 // Don't automatically suppress a report if one of the arguments is
296 // known to be a null pointer. Instead, start tracking /that/ null
297 // value back to its origin.
298 ProgramStateManager &StateMgr = BRC.getStateManager();
299 CallEventManager &CallMgr = StateMgr.getCallEventManager();
300
301 ProgramStateRef State = N->getState();
302 CallEventRef<> Call = CallMgr.getCaller(StackFrame, State);
303 for (unsigned I = 0, E = Call->getNumArgs(); I != E; ++I) {
304 SVal ArgV = Call->getArgSVal(I);
305 if (!isa<Loc>(ArgV))
306 continue;
307
308 const Expr *ArgE = Call->getArgExpr(I);
309 if (!ArgE)
310 continue;
311
312 // Is it possible for this argument to be non-null?
313 if (State->assume(cast<Loc>(ArgV), true))
314 continue;
315
316 if (bugreporter::trackNullOrUndefValue(N, ArgE, BR, /*IsArg=*/true))
317 return 0;
318
319 // If we /can't/ track the null pointer, we should err on the side of
320 // false negatives, and continue towards marking this report invalid.
321 // (We will still look at the other arguments, though.)
322 }
323 }
324
325 // There is no reason not to suppress this report; go ahead and do it.
326 BR.markInvalid(ReturnVisitor::getTag(), StackFrame);
327 return 0;
328 }
329
330 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
331 const ExplodedNode *PrevN,
332 BugReporterContext &BRC,
333 BugReport &BR) {
334 switch (Mode) {
335 case Initial:
336 return visitNodeInitial(N, PrevN, BRC, BR);
337 case MaybeSuppress:
338 return visitNodeMaybeSuppress(N, PrevN, BRC, BR);
339 case Satisfied:
340 return 0;
341 }
342
343 llvm_unreachable("Invalid visit mode!");
344 }
Jordan Rose7aba1172012-08-28 00:50:42 +0000345};
346} // end anonymous namespace
347
348
Anna Zaks50bbc162011-08-19 22:33:38 +0000349void FindLastStoreBRVisitor ::Profile(llvm::FoldingSetNodeID &ID) const {
350 static int tag = 0;
351 ID.AddPointer(&tag);
352 ID.AddPointer(R);
353 ID.Add(V);
354}
Ted Kremenek53500662009-07-22 17:55:28 +0000355
Jordan Rose166b7bd2012-08-28 00:50:45 +0000356PathDiagnosticPiece *FindLastStoreBRVisitor::VisitNode(const ExplodedNode *Succ,
357 const ExplodedNode *Pred,
358 BugReporterContext &BRC,
359 BugReport &BR) {
Mike Stump1eb44332009-09-09 15:08:12 +0000360
Anna Zaks50bbc162011-08-19 22:33:38 +0000361 if (satisfied)
362 return NULL;
363
Jordan Rose166b7bd2012-08-28 00:50:45 +0000364 const ExplodedNode *StoreSite = 0;
365 const Expr *InitE = 0;
Jordan Rose09f7bf12012-10-29 17:31:53 +0000366 bool IsParam = false;
Anna Zaks50bbc162011-08-19 22:33:38 +0000367
Jordan Rose166b7bd2012-08-28 00:50:45 +0000368 // First see if we reached the declaration of the region.
369 if (const VarRegion *VR = dyn_cast<VarRegion>(R)) {
370 if (const PostStmt *P = Pred->getLocationAs<PostStmt>()) {
371 if (const DeclStmt *DS = P->getStmtAs<DeclStmt>()) {
372 if (DS->getSingleDecl() == VR->getDecl()) {
373 StoreSite = Pred;
374 InitE = VR->getDecl()->getInit();
Jordan Rose7aba1172012-08-28 00:50:42 +0000375 }
Jordan Rose7aba1172012-08-28 00:50:42 +0000376 }
Jordan Rose7aba1172012-08-28 00:50:42 +0000377 }
Ted Kremenek1b431022010-03-20 18:01:57 +0000378 }
379
Jordan Rose166b7bd2012-08-28 00:50:45 +0000380 // Otherwise, check that Succ has this binding and Pred does not, i.e. this is
381 // where the binding first occurred.
382 if (!StoreSite) {
383 if (Succ->getState()->getSVal(R) != V)
384 return NULL;
385 if (Pred->getState()->getSVal(R) == V)
386 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +0000387
Jordan Rose166b7bd2012-08-28 00:50:45 +0000388 StoreSite = Succ;
389
390 // If this is an assignment expression, we can track the value
391 // being assigned.
392 if (const PostStmt *P = Succ->getLocationAs<PostStmt>())
393 if (const BinaryOperator *BO = P->getStmtAs<BinaryOperator>())
394 if (BO->isAssignmentOp())
395 InitE = BO->getRHS();
Jordan Rose85e99372012-09-22 01:24:46 +0000396
397 // If this is a call entry, the variable should be a parameter.
398 // FIXME: Handle CXXThisRegion as well. (This is not a priority because
399 // 'this' should never be NULL, but this visitor isn't just for NULL and
400 // UndefinedVal.)
401 if (const CallEnter *CE = Succ->getLocationAs<CallEnter>()) {
402 const VarRegion *VR = cast<VarRegion>(R);
403 const ParmVarDecl *Param = cast<ParmVarDecl>(VR->getDecl());
404
405 ProgramStateManager &StateMgr = BRC.getStateManager();
406 CallEventManager &CallMgr = StateMgr.getCallEventManager();
407
408 CallEventRef<> Call = CallMgr.getCaller(CE->getCalleeContext(),
409 Succ->getState());
410 InitE = Call->getArgExpr(Param->getFunctionScopeIndex());
Jordan Rose09f7bf12012-10-29 17:31:53 +0000411 IsParam = true;
Jordan Rose85e99372012-09-22 01:24:46 +0000412 }
Jordan Rose166b7bd2012-08-28 00:50:45 +0000413 }
414
415 if (!StoreSite)
416 return NULL;
Anna Zaks50bbc162011-08-19 22:33:38 +0000417 satisfied = true;
Jordan Rose166b7bd2012-08-28 00:50:45 +0000418
Jordan Rose53221da2012-09-22 01:25:00 +0000419 // If we have an expression that provided the value, try to track where it
420 // came from.
Jordan Rose166b7bd2012-08-28 00:50:45 +0000421 if (InitE) {
Jordan Rose09f7bf12012-10-29 17:31:53 +0000422 if (V.isUndef() || isa<loc::ConcreteInt>(V)) {
423 if (!IsParam)
424 InitE = InitE->IgnoreParenCasts();
425 bugreporter::trackNullOrUndefValue(StoreSite, InitE, BR, IsParam);
426 } else {
427 ReturnVisitor::addVisitorIfNecessary(StoreSite, InitE->IgnoreParenCasts(),
428 BR);
429 }
Jordan Rose166b7bd2012-08-28 00:50:45 +0000430 }
431
Jordan Rose85e99372012-09-22 01:24:46 +0000432 if (!R->canPrintPretty())
433 return 0;
434
Jordan Rose166b7bd2012-08-28 00:50:45 +0000435 // Okay, we've found the binding. Emit an appropriate message.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000436 SmallString<256> sbuf;
Anna Zaks50bbc162011-08-19 22:33:38 +0000437 llvm::raw_svector_ostream os(sbuf);
Mike Stump1eb44332009-09-09 15:08:12 +0000438
Jordan Rose166b7bd2012-08-28 00:50:45 +0000439 if (const PostStmt *PS = StoreSite->getLocationAs<PostStmt>()) {
Anna Zaks50bbc162011-08-19 22:33:38 +0000440 if (const DeclStmt *DS = PS->getStmtAs<DeclStmt>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000441
Anna Zaks50bbc162011-08-19 22:33:38 +0000442 if (const VarRegion *VR = dyn_cast<VarRegion>(R)) {
Benjamin Kramerb8989f22011-10-14 18:45:37 +0000443 os << "Variable '" << *VR->getDecl() << "' ";
Ted Kremenek53500662009-07-22 17:55:28 +0000444 }
Anna Zaks50bbc162011-08-19 22:33:38 +0000445 else
Ted Kremenek53500662009-07-22 17:55:28 +0000446 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +0000447
Ted Kremenek53500662009-07-22 17:55:28 +0000448 if (isa<loc::ConcreteInt>(V)) {
449 bool b = false;
Ted Kremenek53500662009-07-22 17:55:28 +0000450 if (R->isBoundable()) {
Ted Kremenek96979342011-08-12 20:02:48 +0000451 if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R)) {
Zhongxing Xu018220c2010-08-11 06:10:55 +0000452 if (TR->getValueType()->isObjCObjectPointerType()) {
Anna Zaks50bbc162011-08-19 22:33:38 +0000453 os << "initialized to nil";
Ted Kremenek53500662009-07-22 17:55:28 +0000454 b = true;
455 }
456 }
457 }
Mike Stump1eb44332009-09-09 15:08:12 +0000458
Ted Kremenek53500662009-07-22 17:55:28 +0000459 if (!b)
Anna Zaks50bbc162011-08-19 22:33:38 +0000460 os << "initialized to a null pointer value";
Ted Kremenek53500662009-07-22 17:55:28 +0000461 }
Ted Kremenek592362b2009-08-18 01:05:30 +0000462 else if (isa<nonloc::ConcreteInt>(V)) {
Anna Zaks50bbc162011-08-19 22:33:38 +0000463 os << "initialized to " << cast<nonloc::ConcreteInt>(V).getValue();
Ted Kremenek592362b2009-08-18 01:05:30 +0000464 }
Anna Zaks50bbc162011-08-19 22:33:38 +0000465 else if (V.isUndef()) {
466 if (isa<VarRegion>(R)) {
467 const VarDecl *VD = cast<VarDecl>(DS->getSingleDecl());
468 if (VD->getInit())
469 os << "initialized to a garbage value";
470 else
471 os << "declared without an initial value";
472 }
Ted Kremenek53500662009-07-22 17:55:28 +0000473 }
Jordan Rose68537992012-08-03 23:09:01 +0000474 else {
475 os << "initialized here";
476 }
Ted Kremenek53500662009-07-22 17:55:28 +0000477 }
Jordan Rose85e99372012-09-22 01:24:46 +0000478 } else if (isa<CallEnter>(StoreSite->getLocation())) {
479 const ParmVarDecl *Param = cast<ParmVarDecl>(cast<VarRegion>(R)->getDecl());
480
481 os << "Passing ";
482
483 if (isa<loc::ConcreteInt>(V)) {
484 if (Param->getType()->isObjCObjectPointerType())
485 os << "nil object reference";
486 else
487 os << "null pointer value";
488 } else if (V.isUndef()) {
489 os << "uninitialized value";
490 } else if (isa<nonloc::ConcreteInt>(V)) {
491 os << "the value " << cast<nonloc::ConcreteInt>(V).getValue();
492 } else {
493 os << "value";
494 }
495
496 // Printed parameter indexes are 1-based, not 0-based.
497 unsigned Idx = Param->getFunctionScopeIndex() + 1;
498 os << " via " << Idx << llvm::getOrdinalSuffix(Idx) << " parameter '";
499
500 R->printPretty(os);
501 os << '\'';
Anna Zaks50bbc162011-08-19 22:33:38 +0000502 }
503
504 if (os.str().empty()) {
505 if (isa<loc::ConcreteInt>(V)) {
506 bool b = false;
507 if (R->isBoundable()) {
508 if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R)) {
509 if (TR->getValueType()->isObjCObjectPointerType()) {
510 os << "nil object reference stored to ";
511 b = true;
512 }
513 }
514 }
515
516 if (!b)
517 os << "Null pointer value stored to ";
518 }
519 else if (V.isUndef()) {
520 os << "Uninitialized value stored to ";
521 }
522 else if (isa<nonloc::ConcreteInt>(V)) {
523 os << "The value " << cast<nonloc::ConcreteInt>(V).getValue()
524 << " is assigned to ";
525 }
526 else
Jordan Rose68537992012-08-03 23:09:01 +0000527 os << "Value assigned to ";
Anna Zaks50bbc162011-08-19 22:33:38 +0000528
Jordan Rose85e99372012-09-22 01:24:46 +0000529 os << '\'';
530 R->printPretty(os);
531 os << '\'';
Anna Zaks50bbc162011-08-19 22:33:38 +0000532 }
533
Anna Zaks50bbc162011-08-19 22:33:38 +0000534 // Construct a new PathDiagnosticPiece.
Jordan Rose166b7bd2012-08-28 00:50:45 +0000535 ProgramPoint P = StoreSite->getLocation();
Jordan Rose85e99372012-09-22 01:24:46 +0000536 PathDiagnosticLocation L;
537 if (isa<CallEnter>(P))
538 L = PathDiagnosticLocation(InitE, BRC.getSourceManager(),
539 P.getLocationContext());
540 else
541 L = PathDiagnosticLocation::create(P, BRC.getSourceManager());
Anna Zaks4fdf97b2011-09-15 18:56:07 +0000542 if (!L.isValid())
543 return NULL;
Anna Zaks50bbc162011-08-19 22:33:38 +0000544 return new PathDiagnosticEventPiece(L, os.str());
545}
546
547void TrackConstraintBRVisitor::Profile(llvm::FoldingSetNodeID &ID) const {
548 static int tag = 0;
549 ID.AddPointer(&tag);
550 ID.AddBoolean(Assumption);
551 ID.Add(Constraint);
552}
553
Ted Kremenekb85cce02012-10-25 22:07:10 +0000554/// Return the tag associated with this visitor. This tag will be used
555/// to make all PathDiagnosticPieces created by this visitor.
556const char *TrackConstraintBRVisitor::getTag() {
557 return "TrackConstraintBRVisitor";
558}
559
Anna Zaks50bbc162011-08-19 22:33:38 +0000560PathDiagnosticPiece *
561TrackConstraintBRVisitor::VisitNode(const ExplodedNode *N,
562 const ExplodedNode *PrevN,
563 BugReporterContext &BRC,
564 BugReport &BR) {
565 if (isSatisfied)
566 return NULL;
567
568 // Check if in the previous state it was feasible for this constraint
569 // to *not* be true.
570 if (PrevN->getState()->assume(Constraint, !Assumption)) {
571
572 isSatisfied = true;
573
574 // As a sanity check, make sure that the negation of the constraint
575 // was infeasible in the current state. If it is feasible, we somehow
576 // missed the transition point.
577 if (N->getState()->assume(Constraint, !Assumption))
578 return NULL;
579
580 // We found the transition point for the constraint. We now need to
581 // pretty-print the constraint. (work-in-progress)
582 std::string sbuf;
583 llvm::raw_string_ostream os(sbuf);
584
585 if (isa<Loc>(Constraint)) {
586 os << "Assuming pointer value is ";
587 os << (Assumption ? "non-null" : "null");
588 }
589
590 if (os.str().empty())
591 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +0000592
Ted Kremenek53500662009-07-22 17:55:28 +0000593 // Construct a new PathDiagnosticPiece.
Anna Zaks4fdf97b2011-09-15 18:56:07 +0000594 ProgramPoint P = N->getLocation();
Anna Zaks1531bb02011-09-20 01:38:47 +0000595 PathDiagnosticLocation L =
596 PathDiagnosticLocation::create(P, BRC.getSourceManager());
Anna Zaks4fdf97b2011-09-15 18:56:07 +0000597 if (!L.isValid())
598 return NULL;
Ted Kremenekb85cce02012-10-25 22:07:10 +0000599
600 PathDiagnosticEventPiece *X = new PathDiagnosticEventPiece(L, os.str());
601 X->setTag(getTag());
602 return X;
Ted Kremenek53500662009-07-22 17:55:28 +0000603 }
Ted Kremenek53500662009-07-22 17:55:28 +0000604
Anna Zaks50bbc162011-08-19 22:33:38 +0000605 return NULL;
Ted Kremenek53500662009-07-22 17:55:28 +0000606}
607
Jordan Rose6a329ee2012-10-29 17:31:59 +0000608bool bugreporter::trackNullOrUndefValue(const ExplodedNode *N, const Stmt *S,
Jordan Rose09f7bf12012-10-29 17:31:53 +0000609 BugReport &report, bool IsArg) {
Anna Zaks50bbc162011-08-19 22:33:38 +0000610 if (!S || !N)
Jordan Rose6a329ee2012-10-29 17:31:59 +0000611 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000612
Jordan Rose6686b662012-09-22 01:24:49 +0000613 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(S))
614 S = OVE->getSourceExpr();
615
Jordan Rose09f7bf12012-10-29 17:31:53 +0000616 if (IsArg) {
617 assert(isa<CallEnter>(N->getLocation()) && "Tracking arg but not at call");
618 } else {
619 // Walk through nodes until we get one that matches the statement exactly.
620 do {
621 const ProgramPoint &pp = N->getLocation();
622 if (const PostStmt *ps = dyn_cast<PostStmt>(&pp)) {
623 if (ps->getStmt() == S)
624 break;
625 } else if (const CallExitEnd *CEE = dyn_cast<CallExitEnd>(&pp)) {
626 if (CEE->getCalleeContext()->getCallSite() == S)
627 break;
628 }
629 N = N->getFirstPred();
630 } while (N);
Anna Zaks8e6431a2011-08-18 22:37:56 +0000631
Jordan Rose09f7bf12012-10-29 17:31:53 +0000632 if (!N)
Jordan Rose6a329ee2012-10-29 17:31:59 +0000633 return false;
Ted Kremenek88299892011-07-28 23:07:59 +0000634 }
Ted Kremenek88299892011-07-28 23:07:59 +0000635
Ted Kremenek8bef8232012-01-26 21:29:00 +0000636 ProgramStateRef state = N->getState();
Mike Stump1eb44332009-09-09 15:08:12 +0000637
Jordan Rose364b9f92012-08-27 20:18:30 +0000638 // See if the expression we're interested refers to a variable.
639 // If so, we can track both its contents and constraints on its value.
640 if (const Expr *Ex = dyn_cast<Expr>(S)) {
641 // Strip off parens and casts. Note that this will never have issues with
642 // C++ user-defined implicit conversions, because those have a constructor
643 // or function call inside.
Jordan Rosee6cd0542012-08-16 00:03:33 +0000644 Ex = Ex->IgnoreParenCasts();
Ted Kremenek76aadc32012-03-09 01:13:14 +0000645 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Ex)) {
Jordan Rose364b9f92012-08-27 20:18:30 +0000646 // FIXME: Right now we only track VarDecls because it's non-trivial to
647 // get a MemRegion for any other DeclRefExprs. <rdar://problem/12114812>
Ted Kremenek76aadc32012-03-09 01:13:14 +0000648 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
Jordan Rose09f7bf12012-10-29 17:31:53 +0000649 ProgramStateManager &StateMgr = state->getStateManager();
650 MemRegionManager &MRMgr = StateMgr.getRegionManager();
651 const VarRegion *R = MRMgr.getVarRegion(VD, N->getLocationContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000652
Jordan Rose364b9f92012-08-27 20:18:30 +0000653 // Mark both the variable region and its contents as interesting.
Ted Kremenek11abcec2012-05-02 00:31:29 +0000654 SVal V = state->getRawSVal(loc::MemRegionVal(R));
Jordan Rose09f7bf12012-10-29 17:31:53 +0000655
656 // If the value matches the default for the variable region, that
657 // might mean that it's been cleared out of the state. Fall back to
658 // the full argument expression (with casts and such intact).
659 if (IsArg) {
660 bool UseArgValue = V.isUnknownOrUndef() || V.isZeroConstant();
661 if (!UseArgValue) {
662 const SymbolRegionValue *SRV =
663 dyn_cast_or_null<SymbolRegionValue>(V.getAsLocSymbol());
664 if (SRV)
665 UseArgValue = (SRV->getRegion() == R);
666 }
667 if (UseArgValue)
668 V = state->getSValAsScalarOrLoc(S, N->getLocationContext());
669 }
670
Jordan Rosea1f81bb2012-08-28 00:50:51 +0000671 report.markInteresting(R);
672 report.markInteresting(V);
Anna Zaks80de4872012-08-29 21:22:37 +0000673 report.addVisitor(new UndefOrNullArgVisitor(R));
Jordan Rose68537992012-08-03 23:09:01 +0000674
Jordan Rose364b9f92012-08-27 20:18:30 +0000675 // If the contents are symbolic, find out when they became null.
Jordan Rose68537992012-08-03 23:09:01 +0000676 if (V.getAsLocSymbol()) {
677 BugReporterVisitor *ConstraintTracker
Jordan Rose53221da2012-09-22 01:25:00 +0000678 = new TrackConstraintBRVisitor(cast<DefinedSVal>(V), false);
Jordan Rosea1f81bb2012-08-28 00:50:51 +0000679 report.addVisitor(ConstraintTracker);
Jordan Rose68537992012-08-03 23:09:01 +0000680 }
681
Jordan Rosea1f81bb2012-08-28 00:50:51 +0000682 report.addVisitor(new FindLastStoreBRVisitor(V, R));
Jordan Rose6a329ee2012-10-29 17:31:59 +0000683 return true;
Ted Kremenek53500662009-07-22 17:55:28 +0000684 }
685 }
686 }
Mike Stump1eb44332009-09-09 15:08:12 +0000687
Jordan Rose364b9f92012-08-27 20:18:30 +0000688 // If the expression does NOT refer to a variable, we can still track
689 // constraints on its contents.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000690 SVal V = state->getSValAsScalarOrLoc(S, N->getLocationContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000691
Ted Kremenek53500662009-07-22 17:55:28 +0000692 // Uncomment this to find cases where we aren't properly getting the
693 // base value that was dereferenced.
694 // assert(!V.isUnknownOrUndef());
Mike Stump1eb44332009-09-09 15:08:12 +0000695
Ted Kremenek53500662009-07-22 17:55:28 +0000696 // Is it a symbolic value?
697 if (loc::MemRegionVal *L = dyn_cast<loc::MemRegionVal>(&V)) {
Anna Zaksd91696e2012-09-05 22:31:55 +0000698 // At this point we are dealing with the region's LValue.
699 // However, if the rvalue is a symbolic region, we should track it as well.
700 SVal RVal = state->getSVal(L->getRegion());
701 const MemRegion *RegionRVal = RVal.getAsRegion();
Anna Zaks522fc212012-09-12 22:57:30 +0000702 report.addVisitor(new UndefOrNullArgVisitor(L->getRegion()));
703
Anna Zaksd91696e2012-09-05 22:31:55 +0000704
705 if (RegionRVal && isa<SymbolicRegion>(RegionRVal)) {
706 report.markInteresting(RegionRVal);
707 report.addVisitor(new TrackConstraintBRVisitor(
708 loc::MemRegionVal(RegionRVal), false));
Ted Kremenek53500662009-07-22 17:55:28 +0000709 }
Jordan Rose7aba1172012-08-28 00:50:42 +0000710 } else {
711 // Otherwise, if the value came from an inlined function call,
712 // we should at least make sure that function isn't pruned in our output.
Jordan Rose53221da2012-09-22 01:25:00 +0000713 if (const Expr *E = dyn_cast<Expr>(S))
714 S = E->IgnoreParenCasts();
Jordan Rosea1f81bb2012-08-28 00:50:51 +0000715 ReturnVisitor::addVisitorIfNecessary(N, S, report);
Ted Kremenek53500662009-07-22 17:55:28 +0000716 }
Jordan Rose6a329ee2012-10-29 17:31:59 +0000717
718 return true;
Ted Kremenek53500662009-07-22 17:55:28 +0000719}
Ted Kremenek94fd0b82010-02-16 08:33:59 +0000720
Anna Zaks50bbc162011-08-19 22:33:38 +0000721BugReporterVisitor *
722FindLastStoreBRVisitor::createVisitorObject(const ExplodedNode *N,
723 const MemRegion *R) {
724 assert(R && "The memory region is null.");
Ted Kremenek94fd0b82010-02-16 08:33:59 +0000725
Ted Kremenek8bef8232012-01-26 21:29:00 +0000726 ProgramStateRef state = N->getState();
Ted Kremenek94fd0b82010-02-16 08:33:59 +0000727 SVal V = state->getSVal(R);
Ted Kremenek94fd0b82010-02-16 08:33:59 +0000728 if (V.isUnknown())
Anna Zaks50bbc162011-08-19 22:33:38 +0000729 return 0;
Ted Kremenek94fd0b82010-02-16 08:33:59 +0000730
Anna Zaks50bbc162011-08-19 22:33:38 +0000731 return new FindLastStoreBRVisitor(V, R);
Ted Kremenek94fd0b82010-02-16 08:33:59 +0000732}
Ted Kremenekff7f7362010-03-20 18:02:01 +0000733
734
Anna Zaks50bbc162011-08-19 22:33:38 +0000735PathDiagnosticPiece *NilReceiverBRVisitor::VisitNode(const ExplodedNode *N,
736 const ExplodedNode *PrevN,
737 BugReporterContext &BRC,
738 BugReport &BR) {
739 const PostStmt *P = N->getLocationAs<PostStmt>();
740 if (!P)
741 return 0;
742 const ObjCMessageExpr *ME = P->getStmtAs<ObjCMessageExpr>();
743 if (!ME)
744 return 0;
745 const Expr *Receiver = ME->getInstanceReceiver();
746 if (!Receiver)
747 return 0;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000748 ProgramStateRef state = N->getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +0000749 const SVal &V = state->getSVal(Receiver, N->getLocationContext());
Anna Zaks50bbc162011-08-19 22:33:38 +0000750 const DefinedOrUnknownSVal *DV = dyn_cast<DefinedOrUnknownSVal>(&V);
751 if (!DV)
752 return 0;
753 state = state->assume(*DV, true);
754 if (state)
755 return 0;
Ted Kremenekff7f7362010-03-20 18:02:01 +0000756
Anna Zaks50bbc162011-08-19 22:33:38 +0000757 // The receiver was nil, and hence the method was skipped.
758 // Register a BugReporterVisitor to issue a message telling us how
759 // the receiver was null.
Jordan Rosea1f81bb2012-08-28 00:50:51 +0000760 bugreporter::trackNullOrUndefValue(N, Receiver, BR);
Anna Zaks50bbc162011-08-19 22:33:38 +0000761 // Issue a message saying that the method was skipped.
Anna Zaks220ac8c2011-09-15 01:08:34 +0000762 PathDiagnosticLocation L(Receiver, BRC.getSourceManager(),
763 N->getLocationContext());
Anna Zaks907344e2012-04-05 02:10:19 +0000764 return new PathDiagnosticEventPiece(L, "No method is called "
Anna Zaks50bbc162011-08-19 22:33:38 +0000765 "because the receiver is nil");
Ted Kremenekff7f7362010-03-20 18:02:01 +0000766}
Tom Care2bbbe502010-09-02 23:30:22 +0000767
Anna Zaks8e6431a2011-08-18 22:37:56 +0000768// Registers every VarDecl inside a Stmt with a last store visitor.
Anna Zaks50bbc162011-08-19 22:33:38 +0000769void FindLastStoreBRVisitor::registerStatementVarDecls(BugReport &BR,
770 const Stmt *S) {
Anna Zaks8e6431a2011-08-18 22:37:56 +0000771 const ExplodedNode *N = BR.getErrorNode();
Tom Care2bbbe502010-09-02 23:30:22 +0000772 std::deque<const Stmt *> WorkList;
Tom Care2bbbe502010-09-02 23:30:22 +0000773 WorkList.push_back(S);
774
775 while (!WorkList.empty()) {
776 const Stmt *Head = WorkList.front();
777 WorkList.pop_front();
778
Ted Kremenek8bef8232012-01-26 21:29:00 +0000779 ProgramStateRef state = N->getState();
Anna Zaks8e6431a2011-08-18 22:37:56 +0000780 ProgramStateManager &StateMgr = state->getStateManager();
Tom Care2bbbe502010-09-02 23:30:22 +0000781
782 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Head)) {
783 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
784 const VarRegion *R =
785 StateMgr.getRegionManager().getVarRegion(VD, N->getLocationContext());
786
787 // What did we load?
Ted Kremenek5eca4822012-01-06 22:09:28 +0000788 SVal V = state->getSVal(S, N->getLocationContext());
Tom Care2bbbe502010-09-02 23:30:22 +0000789
790 if (isa<loc::ConcreteInt>(V) || isa<nonloc::ConcreteInt>(V)) {
Anna Zaks50bbc162011-08-19 22:33:38 +0000791 // Register a new visitor with the BugReport.
792 BR.addVisitor(new FindLastStoreBRVisitor(V, R));
Tom Care2bbbe502010-09-02 23:30:22 +0000793 }
794 }
795 }
796
797 for (Stmt::const_child_iterator I = Head->child_begin();
798 I != Head->child_end(); ++I)
799 WorkList.push_back(*I);
800 }
801}
Ted Kremenek993124e2011-08-06 06:54:45 +0000802
803//===----------------------------------------------------------------------===//
804// Visitor that tries to report interesting diagnostics from conditions.
805//===----------------------------------------------------------------------===//
Ted Kremenekb85cce02012-10-25 22:07:10 +0000806
807/// Return the tag associated with this visitor. This tag will be used
808/// to make all PathDiagnosticPieces created by this visitor.
809const char *ConditionBRVisitor::getTag() {
810 return "ConditionBRVisitor";
811}
812
Anna Zaks50bbc162011-08-19 22:33:38 +0000813PathDiagnosticPiece *ConditionBRVisitor::VisitNode(const ExplodedNode *N,
814 const ExplodedNode *Prev,
815 BugReporterContext &BRC,
816 BugReport &BR) {
Ted Kremenekc89f4b02012-02-28 23:06:21 +0000817 PathDiagnosticPiece *piece = VisitNodeImpl(N, Prev, BRC, BR);
Ted Kremenekb85cce02012-10-25 22:07:10 +0000818 if (piece) {
819 piece->setTag(getTag());
820 if (PathDiagnosticEventPiece *ev=dyn_cast<PathDiagnosticEventPiece>(piece))
821 ev->setPrunable(true, /* override */ false);
822 }
Ted Kremenekc89f4b02012-02-28 23:06:21 +0000823 return piece;
824}
825
826PathDiagnosticPiece *ConditionBRVisitor::VisitNodeImpl(const ExplodedNode *N,
827 const ExplodedNode *Prev,
828 BugReporterContext &BRC,
829 BugReport &BR) {
Ted Kremenek993124e2011-08-06 06:54:45 +0000830
Ted Kremenek22505ef2012-09-08 07:18:18 +0000831 ProgramPoint progPoint = N->getLocation();
Ted Kremenek8bef8232012-01-26 21:29:00 +0000832 ProgramStateRef CurrentState = N->getState();
833 ProgramStateRef PrevState = Prev->getState();
Ted Kremenek681bc112011-08-16 01:53:41 +0000834
835 // Compare the GDMs of the state, because that is where constraints
836 // are managed. Note that ensure that we only look at nodes that
837 // were generated by the analyzer engine proper, not checkers.
838 if (CurrentState->getGDM().getRoot() ==
839 PrevState->getGDM().getRoot())
840 return 0;
Ted Kremenek993124e2011-08-06 06:54:45 +0000841
842 // If an assumption was made on a branch, it should be caught
843 // here by looking at the state transition.
844 if (const BlockEdge *BE = dyn_cast<BlockEdge>(&progPoint)) {
Ted Kremenek681bc112011-08-16 01:53:41 +0000845 const CFGBlock *srcBlk = BE->getSrc();
846 if (const Stmt *term = srcBlk->getTerminator())
Ted Kremenek76aadc32012-03-09 01:13:14 +0000847 return VisitTerminator(term, N, srcBlk, BE->getDst(), BR, BRC);
Ted Kremenek681bc112011-08-16 01:53:41 +0000848 return 0;
849 }
850
851 if (const PostStmt *PS = dyn_cast<PostStmt>(&progPoint)) {
852 // FIXME: Assuming that BugReporter is a GRBugReporter is a layering
853 // violation.
854 const std::pair<const ProgramPointTag *, const ProgramPointTag *> &tags =
855 cast<GRBugReporter>(BRC.getBugReporter()).
Ted Kremenek0caa2d42012-08-30 19:26:48 +0000856 getEngine().geteagerlyAssumeBinOpBifurcationTags();
Ted Kremenek681bc112011-08-16 01:53:41 +0000857
858 const ProgramPointTag *tag = PS->getTag();
859 if (tag == tags.first)
Anna Zaks220ac8c2011-09-15 01:08:34 +0000860 return VisitTrueTest(cast<Expr>(PS->getStmt()), true,
Ted Kremenek76aadc32012-03-09 01:13:14 +0000861 BRC, BR, N);
Ted Kremenek681bc112011-08-16 01:53:41 +0000862 if (tag == tags.second)
Anna Zaks220ac8c2011-09-15 01:08:34 +0000863 return VisitTrueTest(cast<Expr>(PS->getStmt()), false,
Ted Kremenek76aadc32012-03-09 01:13:14 +0000864 BRC, BR, N);
Ted Kremenek681bc112011-08-16 01:53:41 +0000865
Ted Kremenek993124e2011-08-06 06:54:45 +0000866 return 0;
867 }
868
869 return 0;
870}
871
872PathDiagnosticPiece *
Anna Zaks50bbc162011-08-19 22:33:38 +0000873ConditionBRVisitor::VisitTerminator(const Stmt *Term,
Anna Zaks220ac8c2011-09-15 01:08:34 +0000874 const ExplodedNode *N,
Anna Zaks50bbc162011-08-19 22:33:38 +0000875 const CFGBlock *srcBlk,
876 const CFGBlock *dstBlk,
Ted Kremenek76aadc32012-03-09 01:13:14 +0000877 BugReport &R,
Anna Zaks50bbc162011-08-19 22:33:38 +0000878 BugReporterContext &BRC) {
Ted Kremenek993124e2011-08-06 06:54:45 +0000879 const Expr *Cond = 0;
880
881 switch (Term->getStmtClass()) {
882 default:
883 return 0;
884 case Stmt::IfStmtClass:
885 Cond = cast<IfStmt>(Term)->getCond();
886 break;
887 case Stmt::ConditionalOperatorClass:
888 Cond = cast<ConditionalOperator>(Term)->getCond();
889 break;
890 }
891
892 assert(Cond);
893 assert(srcBlk->succ_size() == 2);
894 const bool tookTrue = *(srcBlk->succ_begin()) == dstBlk;
Ted Kremenekc47dc1b2012-09-07 06:51:37 +0000895 return VisitTrueTest(Cond, tookTrue, BRC, R, N);
Ted Kremenek993124e2011-08-06 06:54:45 +0000896}
897
898PathDiagnosticPiece *
Anna Zaks50bbc162011-08-19 22:33:38 +0000899ConditionBRVisitor::VisitTrueTest(const Expr *Cond,
900 bool tookTrue,
Anna Zaks220ac8c2011-09-15 01:08:34 +0000901 BugReporterContext &BRC,
Ted Kremenek76aadc32012-03-09 01:13:14 +0000902 BugReport &R,
903 const ExplodedNode *N) {
Ted Kremenek993124e2011-08-06 06:54:45 +0000904
905 const Expr *Ex = Cond;
906
Ted Kremenek681bc112011-08-16 01:53:41 +0000907 while (true) {
Ted Kremenekc47dc1b2012-09-07 06:51:37 +0000908 Ex = Ex->IgnoreParenCasts();
Ted Kremenek993124e2011-08-06 06:54:45 +0000909 switch (Ex->getStmtClass()) {
910 default:
911 return 0;
Ted Kremenek681bc112011-08-16 01:53:41 +0000912 case Stmt::BinaryOperatorClass:
Ted Kremenek76aadc32012-03-09 01:13:14 +0000913 return VisitTrueTest(Cond, cast<BinaryOperator>(Ex), tookTrue, BRC,
914 R, N);
Ted Kremenek993124e2011-08-06 06:54:45 +0000915 case Stmt::DeclRefExprClass:
Ted Kremenek76aadc32012-03-09 01:13:14 +0000916 return VisitTrueTest(Cond, cast<DeclRefExpr>(Ex), tookTrue, BRC,
917 R, N);
Ted Kremenek993124e2011-08-06 06:54:45 +0000918 case Stmt::UnaryOperatorClass: {
919 const UnaryOperator *UO = cast<UnaryOperator>(Ex);
920 if (UO->getOpcode() == UO_LNot) {
921 tookTrue = !tookTrue;
Ted Kremenekc47dc1b2012-09-07 06:51:37 +0000922 Ex = UO->getSubExpr();
Ted Kremenek993124e2011-08-06 06:54:45 +0000923 continue;
924 }
925 return 0;
926 }
927 }
Ted Kremenek681bc112011-08-16 01:53:41 +0000928 }
929}
930
Anna Zaks50bbc162011-08-19 22:33:38 +0000931bool ConditionBRVisitor::patternMatch(const Expr *Ex, llvm::raw_ostream &Out,
Ted Kremenek76aadc32012-03-09 01:13:14 +0000932 BugReporterContext &BRC,
933 BugReport &report,
934 const ExplodedNode *N,
935 llvm::Optional<bool> &prunable) {
Ted Kremenek681bc112011-08-16 01:53:41 +0000936 const Expr *OriginalExpr = Ex;
937 Ex = Ex->IgnoreParenCasts();
938
939 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Ex)) {
Ted Kremenek3b9e8e42011-08-16 10:57:37 +0000940 const bool quotes = isa<VarDecl>(DR->getDecl());
Ted Kremenek76aadc32012-03-09 01:13:14 +0000941 if (quotes) {
Ted Kremenek3b9e8e42011-08-16 10:57:37 +0000942 Out << '\'';
Ted Kremenek76aadc32012-03-09 01:13:14 +0000943 const LocationContext *LCtx = N->getLocationContext();
944 const ProgramState *state = N->getState().getPtr();
945 if (const MemRegion *R = state->getLValue(cast<VarDecl>(DR->getDecl()),
946 LCtx).getAsRegion()) {
947 if (report.isInteresting(R))
948 prunable = false;
949 else {
950 const ProgramState *state = N->getState().getPtr();
951 SVal V = state->getSVal(R);
952 if (report.isInteresting(V))
953 prunable = false;
954 }
955 }
956 }
Ted Kremenek3b9e8e42011-08-16 10:57:37 +0000957 Out << DR->getDecl()->getDeclName().getAsString();
958 if (quotes)
959 Out << '\'';
960 return quotes;
Ted Kremenek681bc112011-08-16 01:53:41 +0000961 }
962
963 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(Ex)) {
964 QualType OriginalTy = OriginalExpr->getType();
965 if (OriginalTy->isPointerType()) {
966 if (IL->getValue() == 0) {
967 Out << "null";
Ted Kremenek3b9e8e42011-08-16 10:57:37 +0000968 return false;
Ted Kremenek681bc112011-08-16 01:53:41 +0000969 }
970 }
971 else if (OriginalTy->isObjCObjectPointerType()) {
972 if (IL->getValue() == 0) {
973 Out << "nil";
Ted Kremenek3b9e8e42011-08-16 10:57:37 +0000974 return false;
Ted Kremenek681bc112011-08-16 01:53:41 +0000975 }
976 }
977
978 Out << IL->getValue();
Ted Kremenek3b9e8e42011-08-16 10:57:37 +0000979 return false;
Ted Kremenek681bc112011-08-16 01:53:41 +0000980 }
Ted Kremenek3b9e8e42011-08-16 10:57:37 +0000981
982 return false;
Ted Kremenek681bc112011-08-16 01:53:41 +0000983}
984
985PathDiagnosticPiece *
Anna Zaks50bbc162011-08-19 22:33:38 +0000986ConditionBRVisitor::VisitTrueTest(const Expr *Cond,
987 const BinaryOperator *BExpr,
988 const bool tookTrue,
Anna Zaks220ac8c2011-09-15 01:08:34 +0000989 BugReporterContext &BRC,
Ted Kremenek76aadc32012-03-09 01:13:14 +0000990 BugReport &R,
991 const ExplodedNode *N) {
Ted Kremenek681bc112011-08-16 01:53:41 +0000992
Ted Kremenek3b9e8e42011-08-16 10:57:37 +0000993 bool shouldInvert = false;
Ted Kremenek76aadc32012-03-09 01:13:14 +0000994 llvm::Optional<bool> shouldPrune;
Ted Kremenek3b9e8e42011-08-16 10:57:37 +0000995
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000996 SmallString<128> LhsString, RhsString;
Ted Kremenek681bc112011-08-16 01:53:41 +0000997 {
Ted Kremenek76aadc32012-03-09 01:13:14 +0000998 llvm::raw_svector_ostream OutLHS(LhsString), OutRHS(RhsString);
999 const bool isVarLHS = patternMatch(BExpr->getLHS(), OutLHS, BRC, R, N,
1000 shouldPrune);
1001 const bool isVarRHS = patternMatch(BExpr->getRHS(), OutRHS, BRC, R, N,
1002 shouldPrune);
Ted Kremenek3b9e8e42011-08-16 10:57:37 +00001003
1004 shouldInvert = !isVarLHS && isVarRHS;
Ted Kremenek681bc112011-08-16 01:53:41 +00001005 }
1006
Ted Kremenekd1247c52012-01-04 08:18:09 +00001007 BinaryOperator::Opcode Op = BExpr->getOpcode();
1008
1009 if (BinaryOperator::isAssignmentOp(Op)) {
1010 // For assignment operators, all that we care about is that the LHS
1011 // evaluates to "true" or "false".
1012 return VisitConditionVariable(LhsString, BExpr->getLHS(), tookTrue,
Ted Kremenek76aadc32012-03-09 01:13:14 +00001013 BRC, R, N);
Ted Kremenekd1247c52012-01-04 08:18:09 +00001014 }
1015
1016 // For non-assignment operations, we require that we can understand
1017 // both the LHS and RHS.
Ted Kremenek681bc112011-08-16 01:53:41 +00001018 if (LhsString.empty() || RhsString.empty())
1019 return 0;
Ted Kremenek3b9e8e42011-08-16 10:57:37 +00001020
Ted Kremenekd1247c52012-01-04 08:18:09 +00001021 // Should we invert the strings if the LHS is not a variable name?
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00001022 SmallString<256> buf;
Ted Kremenek681bc112011-08-16 01:53:41 +00001023 llvm::raw_svector_ostream Out(buf);
Ted Kremenek3b9e8e42011-08-16 10:57:37 +00001024 Out << "Assuming " << (shouldInvert ? RhsString : LhsString) << " is ";
Ted Kremenek681bc112011-08-16 01:53:41 +00001025
1026 // Do we need to invert the opcode?
Ted Kremenek3b9e8e42011-08-16 10:57:37 +00001027 if (shouldInvert)
1028 switch (Op) {
1029 default: break;
1030 case BO_LT: Op = BO_GT; break;
1031 case BO_GT: Op = BO_LT; break;
1032 case BO_LE: Op = BO_GE; break;
1033 case BO_GE: Op = BO_LE; break;
1034 }
1035
Ted Kremenek681bc112011-08-16 01:53:41 +00001036 if (!tookTrue)
1037 switch (Op) {
1038 case BO_EQ: Op = BO_NE; break;
1039 case BO_NE: Op = BO_EQ; break;
1040 case BO_LT: Op = BO_GE; break;
1041 case BO_GT: Op = BO_LE; break;
1042 case BO_LE: Op = BO_GT; break;
Ted Kremenek4ee7c9c2011-08-16 03:44:38 +00001043 case BO_GE: Op = BO_LT; break;
Ted Kremenek681bc112011-08-16 01:53:41 +00001044 default:
1045 return 0;
1046 }
1047
Ted Kremenek6ae32572011-12-20 22:00:25 +00001048 switch (Op) {
Ted Kremenek681bc112011-08-16 01:53:41 +00001049 case BO_EQ:
1050 Out << "equal to ";
1051 break;
1052 case BO_NE:
1053 Out << "not equal to ";
1054 break;
1055 default:
1056 Out << BinaryOperator::getOpcodeStr(Op) << ' ';
1057 break;
1058 }
1059
Ted Kremenek3b9e8e42011-08-16 10:57:37 +00001060 Out << (shouldInvert ? LhsString : RhsString);
Ted Kremenek76aadc32012-03-09 01:13:14 +00001061 const LocationContext *LCtx = N->getLocationContext();
1062 PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
1063 PathDiagnosticEventPiece *event =
1064 new PathDiagnosticEventPiece(Loc, Out.str());
1065 if (shouldPrune.hasValue())
1066 event->setPrunable(shouldPrune.getValue());
1067 return event;
Ted Kremenek993124e2011-08-06 06:54:45 +00001068}
Ted Kremenekd1247c52012-01-04 08:18:09 +00001069
1070PathDiagnosticPiece *
1071ConditionBRVisitor::VisitConditionVariable(StringRef LhsString,
1072 const Expr *CondVarExpr,
1073 const bool tookTrue,
1074 BugReporterContext &BRC,
Ted Kremenek76aadc32012-03-09 01:13:14 +00001075 BugReport &report,
1076 const ExplodedNode *N) {
Jordan Roseb0e1bad2012-08-03 23:08:54 +00001077 // FIXME: If there's already a constraint tracker for this variable,
1078 // we shouldn't emit anything here (c.f. the double note in
1079 // test/Analysis/inlining/path-notes.c)
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00001080 SmallString<256> buf;
Ted Kremenekd1247c52012-01-04 08:18:09 +00001081 llvm::raw_svector_ostream Out(buf);
1082 Out << "Assuming " << LhsString << " is ";
1083
1084 QualType Ty = CondVarExpr->getType();
1085
1086 if (Ty->isPointerType())
1087 Out << (tookTrue ? "not null" : "null");
1088 else if (Ty->isObjCObjectPointerType())
1089 Out << (tookTrue ? "not nil" : "nil");
1090 else if (Ty->isBooleanType())
1091 Out << (tookTrue ? "true" : "false");
1092 else if (Ty->isIntegerType())
1093 Out << (tookTrue ? "non-zero" : "zero");
1094 else
1095 return 0;
1096
Ted Kremenek76aadc32012-03-09 01:13:14 +00001097 const LocationContext *LCtx = N->getLocationContext();
1098 PathDiagnosticLocation Loc(CondVarExpr, BRC.getSourceManager(), LCtx);
1099 PathDiagnosticEventPiece *event =
1100 new PathDiagnosticEventPiece(Loc, Out.str());
1101
1102 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(CondVarExpr)) {
1103 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1104 const ProgramState *state = N->getState().getPtr();
1105 if (const MemRegion *R = state->getLValue(VD, LCtx).getAsRegion()) {
1106 if (report.isInteresting(R))
1107 event->setPrunable(false);
1108 }
1109 }
1110 }
1111
1112 return event;
Ted Kremenekd1247c52012-01-04 08:18:09 +00001113}
Ted Kremenek993124e2011-08-06 06:54:45 +00001114
1115PathDiagnosticPiece *
Anna Zaks50bbc162011-08-19 22:33:38 +00001116ConditionBRVisitor::VisitTrueTest(const Expr *Cond,
1117 const DeclRefExpr *DR,
1118 const bool tookTrue,
Anna Zaks220ac8c2011-09-15 01:08:34 +00001119 BugReporterContext &BRC,
Ted Kremenek76aadc32012-03-09 01:13:14 +00001120 BugReport &report,
1121 const ExplodedNode *N) {
Ted Kremenek993124e2011-08-06 06:54:45 +00001122
1123 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
1124 if (!VD)
1125 return 0;
1126
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00001127 SmallString<256> Buf;
Ted Kremenek993124e2011-08-06 06:54:45 +00001128 llvm::raw_svector_ostream Out(Buf);
1129
1130 Out << "Assuming '";
1131 VD->getDeclName().printName(Out);
1132 Out << "' is ";
1133
1134 QualType VDTy = VD->getType();
1135
1136 if (VDTy->isPointerType())
1137 Out << (tookTrue ? "non-null" : "null");
1138 else if (VDTy->isObjCObjectPointerType())
1139 Out << (tookTrue ? "non-nil" : "nil");
1140 else if (VDTy->isScalarType())
1141 Out << (tookTrue ? "not equal to 0" : "0");
1142 else
1143 return 0;
1144
Ted Kremenek76aadc32012-03-09 01:13:14 +00001145 const LocationContext *LCtx = N->getLocationContext();
1146 PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
1147 PathDiagnosticEventPiece *event =
1148 new PathDiagnosticEventPiece(Loc, Out.str());
1149
1150 const ProgramState *state = N->getState().getPtr();
1151 if (const MemRegion *R = state->getLValue(VD, LCtx).getAsRegion()) {
1152 if (report.isInteresting(R))
1153 event->setPrunable(false);
1154 else {
1155 SVal V = state->getSVal(R);
1156 if (report.isInteresting(V))
1157 event->setPrunable(false);
1158 }
1159 }
1160 return event;
Ted Kremenek993124e2011-08-06 06:54:45 +00001161}
Ted Kremenek0cf3d472012-02-07 00:24:33 +00001162
Anna Zaks80de4872012-08-29 21:22:37 +00001163PathDiagnosticPiece *
1164UndefOrNullArgVisitor::VisitNode(const ExplodedNode *N,
1165 const ExplodedNode *PrevN,
1166 BugReporterContext &BRC,
1167 BugReport &BR) {
1168
1169 ProgramStateRef State = N->getState();
1170 ProgramPoint ProgLoc = N->getLocation();
1171
1172 // We are only interested in visiting CallEnter nodes.
1173 CallEnter *CEnter = dyn_cast<CallEnter>(&ProgLoc);
1174 if (!CEnter)
1175 return 0;
1176
1177 // Check if one of the arguments is the region the visitor is tracking.
1178 CallEventManager &CEMgr = BRC.getStateManager().getCallEventManager();
1179 CallEventRef<> Call = CEMgr.getCaller(CEnter->getCalleeContext(), State);
1180 unsigned Idx = 0;
1181 for (CallEvent::param_iterator I = Call->param_begin(),
1182 E = Call->param_end(); I != E; ++I, ++Idx) {
1183 const MemRegion *ArgReg = Call->getArgSVal(Idx).getAsRegion();
1184
Anna Zaks522fc212012-09-12 22:57:30 +00001185 // Are we tracking the argument or its subregion?
1186 if ( !ArgReg || (ArgReg != R && !R->isSubRegionOf(ArgReg->StripCasts())))
Anna Zaks28694c12012-08-29 23:23:39 +00001187 continue;
Anna Zaks80de4872012-08-29 21:22:37 +00001188
1189 // Check the function parameter type.
1190 const ParmVarDecl *ParamDecl = *I;
1191 assert(ParamDecl && "Formal parameter has no decl?");
1192 QualType T = ParamDecl->getType();
1193
1194 if (!(T->isAnyPointerType() || T->isReferenceType())) {
1195 // Function can only change the value passed in by address.
Anna Zaks28694c12012-08-29 23:23:39 +00001196 continue;
Anna Zaks80de4872012-08-29 21:22:37 +00001197 }
1198
1199 // If it is a const pointer value, the function does not intend to
1200 // change the value.
1201 if (T->getPointeeType().isConstQualified())
Anna Zaks28694c12012-08-29 23:23:39 +00001202 continue;
Anna Zaks80de4872012-08-29 21:22:37 +00001203
1204 // Mark the call site (LocationContext) as interesting if the value of the
1205 // argument is undefined or '0'/'NULL'.
Anna Zaks522fc212012-09-12 22:57:30 +00001206 SVal BoundVal = State->getSVal(R);
Anna Zaks80de4872012-08-29 21:22:37 +00001207 if (BoundVal.isUndef() || BoundVal.isZeroConstant()) {
1208 BR.markInteresting(CEnter->getCalleeContext());
1209 return 0;
1210 }
1211 }
1212 return 0;
1213}