BugReporterVisitors.cpp 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259
  1. // 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. //===----------------------------------------------------------------------===//
  14. #include "clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitor.h"
  15. #include "clang/AST/Expr.h"
  16. #include "clang/AST/ExprObjC.h"
  17. #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
  18. #include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
  19. #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
  20. #include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
  21. #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
  22. #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
  23. #include "llvm/ADT/SmallString.h"
  24. #include "llvm/ADT/StringExtras.h"
  25. #include "llvm/Support/raw_ostream.h"
  26. using namespace clang;
  27. using namespace ento;
  28. //===----------------------------------------------------------------------===//
  29. // Utility functions.
  30. //===----------------------------------------------------------------------===//
  31. bool bugreporter::isDeclRefExprToReference(const Expr *E) {
  32. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  33. return DRE->getDecl()->getType()->isReferenceType();
  34. }
  35. return false;
  36. }
  37. const Expr *bugreporter::getDerefExpr(const Stmt *S) {
  38. // Pattern match for a few useful cases (do something smarter later):
  39. // a[0], p->f, *p
  40. const Expr *E = dyn_cast<Expr>(S);
  41. if (!E)
  42. return 0;
  43. E = E->IgnoreParenCasts();
  44. while (true) {
  45. if (const BinaryOperator *B = dyn_cast<BinaryOperator>(E)) {
  46. assert(B->isAssignmentOp());
  47. E = B->getLHS()->IgnoreParenCasts();
  48. continue;
  49. }
  50. else if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
  51. if (U->getOpcode() == UO_Deref)
  52. return U->getSubExpr()->IgnoreParenCasts();
  53. }
  54. else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  55. if (ME->isArrow() || isDeclRefExprToReference(ME->getBase())) {
  56. return ME->getBase()->IgnoreParenCasts();
  57. }
  58. }
  59. else if (const ObjCIvarRefExpr *IvarRef = dyn_cast<ObjCIvarRefExpr>(E)) {
  60. return IvarRef->getBase()->IgnoreParenCasts();
  61. }
  62. else if (const ArraySubscriptExpr *AE = dyn_cast<ArraySubscriptExpr>(E)) {
  63. return AE->getBase();
  64. }
  65. break;
  66. }
  67. return NULL;
  68. }
  69. const Stmt *bugreporter::GetDenomExpr(const ExplodedNode *N) {
  70. const Stmt *S = N->getLocationAs<PreStmt>()->getStmt();
  71. if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(S))
  72. return BE->getRHS();
  73. return NULL;
  74. }
  75. const Stmt *bugreporter::GetRetValExpr(const ExplodedNode *N) {
  76. const Stmt *S = N->getLocationAs<PostStmt>()->getStmt();
  77. if (const ReturnStmt *RS = dyn_cast<ReturnStmt>(S))
  78. return RS->getRetValue();
  79. return NULL;
  80. }
  81. //===----------------------------------------------------------------------===//
  82. // Definitions for bug reporter visitors.
  83. //===----------------------------------------------------------------------===//
  84. PathDiagnosticPiece*
  85. BugReporterVisitor::getEndPath(BugReporterContext &BRC,
  86. const ExplodedNode *EndPathNode,
  87. BugReport &BR) {
  88. return 0;
  89. }
  90. PathDiagnosticPiece*
  91. BugReporterVisitor::getDefaultEndPath(BugReporterContext &BRC,
  92. const ExplodedNode *EndPathNode,
  93. BugReport &BR) {
  94. PathDiagnosticLocation L =
  95. PathDiagnosticLocation::createEndOfPath(EndPathNode,BRC.getSourceManager());
  96. BugReport::ranges_iterator Beg, End;
  97. llvm::tie(Beg, End) = BR.getRanges();
  98. // Only add the statement itself as a range if we didn't specify any
  99. // special ranges for this report.
  100. PathDiagnosticPiece *P = new PathDiagnosticEventPiece(L,
  101. BR.getDescription(),
  102. Beg == End);
  103. for (; Beg != End; ++Beg)
  104. P->addRange(*Beg);
  105. return P;
  106. }
  107. namespace {
  108. /// Emits an extra note at the return statement of an interesting stack frame.
  109. ///
  110. /// The returned value is marked as an interesting value, and if it's null,
  111. /// adds a visitor to track where it became null.
  112. ///
  113. /// This visitor is intended to be used when another visitor discovers that an
  114. /// interesting value comes from an inlined function call.
  115. class ReturnVisitor : public BugReporterVisitorImpl<ReturnVisitor> {
  116. const StackFrameContext *StackFrame;
  117. enum {
  118. Initial,
  119. MaybeSuppress,
  120. Satisfied
  121. } Mode;
  122. public:
  123. ReturnVisitor(const StackFrameContext *Frame)
  124. : StackFrame(Frame), Mode(Initial) {}
  125. static void *getTag() {
  126. static int Tag = 0;
  127. return static_cast<void *>(&Tag);
  128. }
  129. virtual void Profile(llvm::FoldingSetNodeID &ID) const {
  130. ID.AddPointer(ReturnVisitor::getTag());
  131. ID.AddPointer(StackFrame);
  132. }
  133. /// Adds a ReturnVisitor if the given statement represents a call that was
  134. /// inlined.
  135. ///
  136. /// This will search back through the ExplodedGraph, starting from the given
  137. /// node, looking for when the given statement was processed. If it turns out
  138. /// the statement is a call that was inlined, we add the visitor to the
  139. /// bug report, so it can print a note later.
  140. static void addVisitorIfNecessary(const ExplodedNode *Node, const Stmt *S,
  141. BugReport &BR) {
  142. if (!CallEvent::isCallStmt(S))
  143. return;
  144. // First, find when we processed the statement.
  145. do {
  146. if (const CallExitEnd *CEE = Node->getLocationAs<CallExitEnd>())
  147. if (CEE->getCalleeContext()->getCallSite() == S)
  148. break;
  149. if (const StmtPoint *SP = Node->getLocationAs<StmtPoint>())
  150. if (SP->getStmt() == S)
  151. break;
  152. Node = Node->getFirstPred();
  153. } while (Node);
  154. // Next, step over any post-statement checks.
  155. while (Node && isa<PostStmt>(Node->getLocation()))
  156. Node = Node->getFirstPred();
  157. // Finally, see if we inlined the call.
  158. if (Node) {
  159. if (const CallExitEnd *CEE = Node->getLocationAs<CallExitEnd>()) {
  160. const StackFrameContext *CalleeContext = CEE->getCalleeContext();
  161. if (CalleeContext->getCallSite() == S) {
  162. BR.markInteresting(CalleeContext);
  163. BR.addVisitor(new ReturnVisitor(CalleeContext));
  164. }
  165. }
  166. }
  167. }
  168. /// Returns true if any counter-suppression heuristics are enabled for
  169. /// ReturnVisitor.
  170. static bool hasCounterSuppression(AnalyzerOptions &Options) {
  171. return Options.shouldAvoidSuppressingNullArgumentPaths();
  172. }
  173. PathDiagnosticPiece *visitNodeInitial(const ExplodedNode *N,
  174. const ExplodedNode *PrevN,
  175. BugReporterContext &BRC,
  176. BugReport &BR) {
  177. // Only print a message at the interesting return statement.
  178. if (N->getLocationContext() != StackFrame)
  179. return 0;
  180. const StmtPoint *SP = N->getLocationAs<StmtPoint>();
  181. if (!SP)
  182. return 0;
  183. const ReturnStmt *Ret = dyn_cast<ReturnStmt>(SP->getStmt());
  184. if (!Ret)
  185. return 0;
  186. // Okay, we're at the right return statement, but do we have the return
  187. // value available?
  188. ProgramStateRef State = N->getState();
  189. SVal V = State->getSVal(Ret, StackFrame);
  190. if (V.isUnknownOrUndef())
  191. return 0;
  192. // Don't print any more notes after this one.
  193. Mode = Satisfied;
  194. const Expr *RetE = Ret->getRetValue();
  195. assert(RetE && "Tracking a return value for a void function");
  196. RetE = RetE->IgnoreParenCasts();
  197. // If we can't prove the return value is 0, just mark it interesting, and
  198. // make sure to track it into any further inner functions.
  199. if (State->assume(V.castAs<DefinedSVal>(), true)) {
  200. BR.markInteresting(V);
  201. ReturnVisitor::addVisitorIfNecessary(N, RetE, BR);
  202. return 0;
  203. }
  204. // If we're returning 0, we should track where that 0 came from.
  205. bugreporter::trackNullOrUndefValue(N, RetE, BR);
  206. // Build an appropriate message based on the return value.
  207. SmallString<64> Msg;
  208. llvm::raw_svector_ostream Out(Msg);
  209. if (V.getAs<Loc>()) {
  210. // If we are pruning null-return paths as unlikely error paths, mark the
  211. // report invalid. We still want to emit a path note, however, in case
  212. // the report is resurrected as valid later on.
  213. ExprEngine &Eng = BRC.getBugReporter().getEngine();
  214. AnalyzerOptions &Options = Eng.getAnalysisManager().options;
  215. if (Options.shouldSuppressNullReturnPaths()) {
  216. if (hasCounterSuppression(Options))
  217. Mode = MaybeSuppress;
  218. else
  219. BR.markInvalid(ReturnVisitor::getTag(), StackFrame);
  220. }
  221. if (RetE->getType()->isObjCObjectPointerType())
  222. Out << "Returning nil";
  223. else
  224. Out << "Returning null pointer";
  225. } else {
  226. Out << "Returning zero";
  227. }
  228. // FIXME: We should have a more generalized location printing mechanism.
  229. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(RetE))
  230. if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(DR->getDecl()))
  231. Out << " (loaded from '" << *DD << "')";
  232. PathDiagnosticLocation L(Ret, BRC.getSourceManager(), StackFrame);
  233. return new PathDiagnosticEventPiece(L, Out.str());
  234. }
  235. PathDiagnosticPiece *visitNodeMaybeSuppress(const ExplodedNode *N,
  236. const ExplodedNode *PrevN,
  237. BugReporterContext &BRC,
  238. BugReport &BR) {
  239. // Are we at the entry node for this call?
  240. const CallEnter *CE = N->getLocationAs<CallEnter>();
  241. if (!CE)
  242. return 0;
  243. if (CE->getCalleeContext() != StackFrame)
  244. return 0;
  245. Mode = Satisfied;
  246. ExprEngine &Eng = BRC.getBugReporter().getEngine();
  247. AnalyzerOptions &Options = Eng.getAnalysisManager().options;
  248. if (Options.shouldAvoidSuppressingNullArgumentPaths()) {
  249. // Don't automatically suppress a report if one of the arguments is
  250. // known to be a null pointer. Instead, start tracking /that/ null
  251. // value back to its origin.
  252. ProgramStateManager &StateMgr = BRC.getStateManager();
  253. CallEventManager &CallMgr = StateMgr.getCallEventManager();
  254. ProgramStateRef State = N->getState();
  255. CallEventRef<> Call = CallMgr.getCaller(StackFrame, State);
  256. for (unsigned I = 0, E = Call->getNumArgs(); I != E; ++I) {
  257. SVal ArgV = Call->getArgSVal(I);
  258. if (!ArgV.getAs<Loc>())
  259. continue;
  260. const Expr *ArgE = Call->getArgExpr(I);
  261. if (!ArgE)
  262. continue;
  263. // Is it possible for this argument to be non-null?
  264. if (State->assume(ArgV.castAs<Loc>(), true))
  265. continue;
  266. if (bugreporter::trackNullOrUndefValue(N, ArgE, BR, /*IsArg=*/true))
  267. return 0;
  268. // If we /can't/ track the null pointer, we should err on the side of
  269. // false negatives, and continue towards marking this report invalid.
  270. // (We will still look at the other arguments, though.)
  271. }
  272. }
  273. // There is no reason not to suppress this report; go ahead and do it.
  274. BR.markInvalid(ReturnVisitor::getTag(), StackFrame);
  275. return 0;
  276. }
  277. PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
  278. const ExplodedNode *PrevN,
  279. BugReporterContext &BRC,
  280. BugReport &BR) {
  281. switch (Mode) {
  282. case Initial:
  283. return visitNodeInitial(N, PrevN, BRC, BR);
  284. case MaybeSuppress:
  285. return visitNodeMaybeSuppress(N, PrevN, BRC, BR);
  286. case Satisfied:
  287. return 0;
  288. }
  289. llvm_unreachable("Invalid visit mode!");
  290. }
  291. };
  292. } // end anonymous namespace
  293. void FindLastStoreBRVisitor ::Profile(llvm::FoldingSetNodeID &ID) const {
  294. static int tag = 0;
  295. ID.AddPointer(&tag);
  296. ID.AddPointer(R);
  297. ID.Add(V);
  298. }
  299. PathDiagnosticPiece *FindLastStoreBRVisitor::VisitNode(const ExplodedNode *Succ,
  300. const ExplodedNode *Pred,
  301. BugReporterContext &BRC,
  302. BugReport &BR) {
  303. if (satisfied)
  304. return NULL;
  305. const ExplodedNode *StoreSite = 0;
  306. const Expr *InitE = 0;
  307. bool IsParam = false;
  308. // First see if we reached the declaration of the region.
  309. if (const VarRegion *VR = dyn_cast<VarRegion>(R)) {
  310. if (const PostStmt *P = Pred->getLocationAs<PostStmt>()) {
  311. if (const DeclStmt *DS = P->getStmtAs<DeclStmt>()) {
  312. if (DS->getSingleDecl() == VR->getDecl()) {
  313. StoreSite = Pred;
  314. InitE = VR->getDecl()->getInit();
  315. }
  316. }
  317. }
  318. }
  319. // Otherwise, check that Succ has this binding and Pred does not, i.e. this is
  320. // where the binding first occurred.
  321. if (!StoreSite) {
  322. if (Succ->getState()->getSVal(R) != V)
  323. return NULL;
  324. if (Pred->getState()->getSVal(R) == V)
  325. return NULL;
  326. StoreSite = Succ;
  327. // If this is an assignment expression, we can track the value
  328. // being assigned.
  329. if (const PostStmt *P = Succ->getLocationAs<PostStmt>())
  330. if (const BinaryOperator *BO = P->getStmtAs<BinaryOperator>())
  331. if (BO->isAssignmentOp())
  332. InitE = BO->getRHS();
  333. // If this is a call entry, the variable should be a parameter.
  334. // FIXME: Handle CXXThisRegion as well. (This is not a priority because
  335. // 'this' should never be NULL, but this visitor isn't just for NULL and
  336. // UndefinedVal.)
  337. if (const CallEnter *CE = Succ->getLocationAs<CallEnter>()) {
  338. const VarRegion *VR = cast<VarRegion>(R);
  339. const ParmVarDecl *Param = cast<ParmVarDecl>(VR->getDecl());
  340. ProgramStateManager &StateMgr = BRC.getStateManager();
  341. CallEventManager &CallMgr = StateMgr.getCallEventManager();
  342. CallEventRef<> Call = CallMgr.getCaller(CE->getCalleeContext(),
  343. Succ->getState());
  344. InitE = Call->getArgExpr(Param->getFunctionScopeIndex());
  345. IsParam = true;
  346. }
  347. }
  348. if (!StoreSite)
  349. return NULL;
  350. satisfied = true;
  351. // If we have an expression that provided the value, try to track where it
  352. // came from.
  353. if (InitE) {
  354. if (V.isUndef() || V.getAs<loc::ConcreteInt>()) {
  355. if (!IsParam)
  356. InitE = InitE->IgnoreParenCasts();
  357. bugreporter::trackNullOrUndefValue(StoreSite, InitE, BR, IsParam);
  358. } else {
  359. ReturnVisitor::addVisitorIfNecessary(StoreSite, InitE->IgnoreParenCasts(),
  360. BR);
  361. }
  362. }
  363. if (!R->canPrintPretty())
  364. return 0;
  365. // Okay, we've found the binding. Emit an appropriate message.
  366. SmallString<256> sbuf;
  367. llvm::raw_svector_ostream os(sbuf);
  368. if (const PostStmt *PS = StoreSite->getLocationAs<PostStmt>()) {
  369. const Stmt *S = PS->getStmt();
  370. const char *action = 0;
  371. const DeclStmt *DS = dyn_cast<DeclStmt>(S);
  372. const VarRegion *VR = dyn_cast<VarRegion>(R);
  373. if (DS) {
  374. action = "initialized to ";
  375. } else if (isa<BlockExpr>(S)) {
  376. action = "captured by block as ";
  377. if (VR) {
  378. // See if we can get the BlockVarRegion.
  379. ProgramStateRef State = StoreSite->getState();
  380. SVal V = State->getSVal(S, PS->getLocationContext());
  381. if (const BlockDataRegion *BDR =
  382. dyn_cast_or_null<BlockDataRegion>(V.getAsRegion())) {
  383. if (const VarRegion *OriginalR = BDR->getOriginalRegion(VR)) {
  384. V = State->getSVal(OriginalR);
  385. BR.addVisitor(new FindLastStoreBRVisitor(V, OriginalR));
  386. }
  387. }
  388. }
  389. }
  390. if (action) {
  391. if (!R)
  392. return 0;
  393. os << "Variable '" << *VR->getDecl() << "' ";
  394. if (V.getAs<loc::ConcreteInt>()) {
  395. bool b = false;
  396. if (R->isBoundable()) {
  397. if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R)) {
  398. if (TR->getValueType()->isObjCObjectPointerType()) {
  399. os << action << "nil";
  400. b = true;
  401. }
  402. }
  403. }
  404. if (!b)
  405. os << action << "a null pointer value";
  406. } else if (Optional<nonloc::ConcreteInt> CVal =
  407. V.getAs<nonloc::ConcreteInt>()) {
  408. os << action << CVal->getValue();
  409. }
  410. else if (DS) {
  411. if (V.isUndef()) {
  412. if (isa<VarRegion>(R)) {
  413. const VarDecl *VD = cast<VarDecl>(DS->getSingleDecl());
  414. if (VD->getInit())
  415. os << "initialized to a garbage value";
  416. else
  417. os << "declared without an initial value";
  418. }
  419. }
  420. else {
  421. os << "initialized here";
  422. }
  423. }
  424. }
  425. } else if (isa<CallEnter>(StoreSite->getLocation())) {
  426. const ParmVarDecl *Param = cast<ParmVarDecl>(cast<VarRegion>(R)->getDecl());
  427. os << "Passing ";
  428. if (V.getAs<loc::ConcreteInt>()) {
  429. if (Param->getType()->isObjCObjectPointerType())
  430. os << "nil object reference";
  431. else
  432. os << "null pointer value";
  433. } else if (V.isUndef()) {
  434. os << "uninitialized value";
  435. } else if (Optional<nonloc::ConcreteInt> CI =
  436. V.getAs<nonloc::ConcreteInt>()) {
  437. os << "the value " << CI->getValue();
  438. } else {
  439. os << "value";
  440. }
  441. // Printed parameter indexes are 1-based, not 0-based.
  442. unsigned Idx = Param->getFunctionScopeIndex() + 1;
  443. os << " via " << Idx << llvm::getOrdinalSuffix(Idx) << " parameter '";
  444. R->printPretty(os);
  445. os << '\'';
  446. }
  447. if (os.str().empty()) {
  448. if (V.getAs<loc::ConcreteInt>()) {
  449. bool b = false;
  450. if (R->isBoundable()) {
  451. if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R)) {
  452. if (TR->getValueType()->isObjCObjectPointerType()) {
  453. os << "nil object reference stored to ";
  454. b = true;
  455. }
  456. }
  457. }
  458. if (!b)
  459. os << "Null pointer value stored to ";
  460. }
  461. else if (V.isUndef()) {
  462. os << "Uninitialized value stored to ";
  463. } else if (Optional<nonloc::ConcreteInt> CV =
  464. V.getAs<nonloc::ConcreteInt>()) {
  465. os << "The value " << CV->getValue() << " is assigned to ";
  466. }
  467. else
  468. os << "Value assigned to ";
  469. os << '\'';
  470. R->printPretty(os);
  471. os << '\'';
  472. }
  473. // Construct a new PathDiagnosticPiece.
  474. ProgramPoint P = StoreSite->getLocation();
  475. PathDiagnosticLocation L;
  476. if (isa<CallEnter>(P))
  477. L = PathDiagnosticLocation(InitE, BRC.getSourceManager(),
  478. P.getLocationContext());
  479. else
  480. L = PathDiagnosticLocation::create(P, BRC.getSourceManager());
  481. if (!L.isValid())
  482. return NULL;
  483. return new PathDiagnosticEventPiece(L, os.str());
  484. }
  485. void TrackConstraintBRVisitor::Profile(llvm::FoldingSetNodeID &ID) const {
  486. static int tag = 0;
  487. ID.AddPointer(&tag);
  488. ID.AddBoolean(Assumption);
  489. ID.Add(Constraint);
  490. }
  491. /// Return the tag associated with this visitor. This tag will be used
  492. /// to make all PathDiagnosticPieces created by this visitor.
  493. const char *TrackConstraintBRVisitor::getTag() {
  494. return "TrackConstraintBRVisitor";
  495. }
  496. PathDiagnosticPiece *
  497. TrackConstraintBRVisitor::VisitNode(const ExplodedNode *N,
  498. const ExplodedNode *PrevN,
  499. BugReporterContext &BRC,
  500. BugReport &BR) {
  501. if (isSatisfied)
  502. return NULL;
  503. // Check if in the previous state it was feasible for this constraint
  504. // to *not* be true.
  505. if (PrevN->getState()->assume(Constraint, !Assumption)) {
  506. isSatisfied = true;
  507. // As a sanity check, make sure that the negation of the constraint
  508. // was infeasible in the current state. If it is feasible, we somehow
  509. // missed the transition point.
  510. if (N->getState()->assume(Constraint, !Assumption))
  511. return NULL;
  512. // We found the transition point for the constraint. We now need to
  513. // pretty-print the constraint. (work-in-progress)
  514. std::string sbuf;
  515. llvm::raw_string_ostream os(sbuf);
  516. if (Constraint.getAs<Loc>()) {
  517. os << "Assuming pointer value is ";
  518. os << (Assumption ? "non-null" : "null");
  519. }
  520. if (os.str().empty())
  521. return NULL;
  522. // Construct a new PathDiagnosticPiece.
  523. ProgramPoint P = N->getLocation();
  524. PathDiagnosticLocation L =
  525. PathDiagnosticLocation::create(P, BRC.getSourceManager());
  526. if (!L.isValid())
  527. return NULL;
  528. PathDiagnosticEventPiece *X = new PathDiagnosticEventPiece(L, os.str());
  529. X->setTag(getTag());
  530. return X;
  531. }
  532. return NULL;
  533. }
  534. bool bugreporter::trackNullOrUndefValue(const ExplodedNode *N, const Stmt *S,
  535. BugReport &report, bool IsArg) {
  536. if (!S || !N)
  537. return false;
  538. if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(S))
  539. S = OVE->getSourceExpr();
  540. if (IsArg) {
  541. assert(isa<CallEnter>(N->getLocation()) && "Tracking arg but not at call");
  542. } else {
  543. // Walk through nodes until we get one that matches the statement exactly.
  544. do {
  545. const ProgramPoint &pp = N->getLocation();
  546. if (const PostStmt *ps = dyn_cast<PostStmt>(&pp)) {
  547. if (ps->getStmt() == S)
  548. break;
  549. } else if (const CallExitEnd *CEE = dyn_cast<CallExitEnd>(&pp)) {
  550. if (CEE->getCalleeContext()->getCallSite() == S)
  551. break;
  552. }
  553. N = N->getFirstPred();
  554. } while (N);
  555. if (!N)
  556. return false;
  557. }
  558. ProgramStateRef state = N->getState();
  559. // See if the expression we're interested refers to a variable.
  560. // If so, we can track both its contents and constraints on its value.
  561. if (const Expr *Ex = dyn_cast<Expr>(S)) {
  562. // Strip off parens and casts. Note that this will never have issues with
  563. // C++ user-defined implicit conversions, because those have a constructor
  564. // or function call inside.
  565. Ex = Ex->IgnoreParenCasts();
  566. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Ex)) {
  567. // FIXME: Right now we only track VarDecls because it's non-trivial to
  568. // get a MemRegion for any other DeclRefExprs. <rdar://problem/12114812>
  569. if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
  570. ProgramStateManager &StateMgr = state->getStateManager();
  571. MemRegionManager &MRMgr = StateMgr.getRegionManager();
  572. const VarRegion *R = MRMgr.getVarRegion(VD, N->getLocationContext());
  573. // Mark both the variable region and its contents as interesting.
  574. SVal V = state->getRawSVal(loc::MemRegionVal(R));
  575. // If the value matches the default for the variable region, that
  576. // might mean that it's been cleared out of the state. Fall back to
  577. // the full argument expression (with casts and such intact).
  578. if (IsArg) {
  579. bool UseArgValue = V.isUnknownOrUndef() || V.isZeroConstant();
  580. if (!UseArgValue) {
  581. const SymbolRegionValue *SRV =
  582. dyn_cast_or_null<SymbolRegionValue>(V.getAsLocSymbol());
  583. if (SRV)
  584. UseArgValue = (SRV->getRegion() == R);
  585. }
  586. if (UseArgValue)
  587. V = state->getSValAsScalarOrLoc(S, N->getLocationContext());
  588. }
  589. report.markInteresting(R);
  590. report.markInteresting(V);
  591. report.addVisitor(new UndefOrNullArgVisitor(R));
  592. // If the contents are symbolic, find out when they became null.
  593. if (V.getAsLocSymbol()) {
  594. BugReporterVisitor *ConstraintTracker =
  595. new TrackConstraintBRVisitor(V.castAs<DefinedSVal>(), false);
  596. report.addVisitor(ConstraintTracker);
  597. }
  598. report.addVisitor(new FindLastStoreBRVisitor(V, R));
  599. return true;
  600. }
  601. }
  602. }
  603. // If the expression does NOT refer to a variable, we can still track
  604. // constraints on its contents.
  605. SVal V = state->getSValAsScalarOrLoc(S, N->getLocationContext());
  606. // Uncomment this to find cases where we aren't properly getting the
  607. // base value that was dereferenced.
  608. // assert(!V.isUnknownOrUndef());
  609. // Is it a symbolic value?
  610. if (Optional<loc::MemRegionVal> L = V.getAs<loc::MemRegionVal>()) {
  611. // At this point we are dealing with the region's LValue.
  612. // However, if the rvalue is a symbolic region, we should track it as well.
  613. SVal RVal = state->getSVal(L->getRegion());
  614. const MemRegion *RegionRVal = RVal.getAsRegion();
  615. report.addVisitor(new UndefOrNullArgVisitor(L->getRegion()));
  616. if (RegionRVal && isa<SymbolicRegion>(RegionRVal)) {
  617. report.markInteresting(RegionRVal);
  618. report.addVisitor(new TrackConstraintBRVisitor(
  619. loc::MemRegionVal(RegionRVal), false));
  620. }
  621. } else {
  622. // Otherwise, if the value came from an inlined function call,
  623. // we should at least make sure that function isn't pruned in our output.
  624. if (const Expr *E = dyn_cast<Expr>(S))
  625. S = E->IgnoreParenCasts();
  626. ReturnVisitor::addVisitorIfNecessary(N, S, report);
  627. }
  628. return true;
  629. }
  630. BugReporterVisitor *
  631. FindLastStoreBRVisitor::createVisitorObject(const ExplodedNode *N,
  632. const MemRegion *R) {
  633. assert(R && "The memory region is null.");
  634. ProgramStateRef state = N->getState();
  635. SVal V = state->getSVal(R);
  636. if (V.isUnknown())
  637. return 0;
  638. return new FindLastStoreBRVisitor(V, R);
  639. }
  640. PathDiagnosticPiece *NilReceiverBRVisitor::VisitNode(const ExplodedNode *N,
  641. const ExplodedNode *PrevN,
  642. BugReporterContext &BRC,
  643. BugReport &BR) {
  644. const PostStmt *P = N->getLocationAs<PostStmt>();
  645. if (!P)
  646. return 0;
  647. const ObjCMessageExpr *ME = P->getStmtAs<ObjCMessageExpr>();
  648. if (!ME)
  649. return 0;
  650. const Expr *Receiver = ME->getInstanceReceiver();
  651. if (!Receiver)
  652. return 0;
  653. ProgramStateRef state = N->getState();
  654. const SVal &V = state->getSVal(Receiver, N->getLocationContext());
  655. Optional<DefinedOrUnknownSVal> DV = V.getAs<DefinedOrUnknownSVal>();
  656. if (!DV)
  657. return 0;
  658. state = state->assume(*DV, true);
  659. if (state)
  660. return 0;
  661. // The receiver was nil, and hence the method was skipped.
  662. // Register a BugReporterVisitor to issue a message telling us how
  663. // the receiver was null.
  664. bugreporter::trackNullOrUndefValue(N, Receiver, BR);
  665. // Issue a message saying that the method was skipped.
  666. PathDiagnosticLocation L(Receiver, BRC.getSourceManager(),
  667. N->getLocationContext());
  668. return new PathDiagnosticEventPiece(L, "No method is called "
  669. "because the receiver is nil");
  670. }
  671. // Registers every VarDecl inside a Stmt with a last store visitor.
  672. void FindLastStoreBRVisitor::registerStatementVarDecls(BugReport &BR,
  673. const Stmt *S) {
  674. const ExplodedNode *N = BR.getErrorNode();
  675. std::deque<const Stmt *> WorkList;
  676. WorkList.push_back(S);
  677. while (!WorkList.empty()) {
  678. const Stmt *Head = WorkList.front();
  679. WorkList.pop_front();
  680. ProgramStateRef state = N->getState();
  681. ProgramStateManager &StateMgr = state->getStateManager();
  682. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Head)) {
  683. if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
  684. const VarRegion *R =
  685. StateMgr.getRegionManager().getVarRegion(VD, N->getLocationContext());
  686. // What did we load?
  687. SVal V = state->getSVal(S, N->getLocationContext());
  688. if (V.getAs<loc::ConcreteInt>() || V.getAs<nonloc::ConcreteInt>()) {
  689. // Register a new visitor with the BugReport.
  690. BR.addVisitor(new FindLastStoreBRVisitor(V, R));
  691. }
  692. }
  693. }
  694. for (Stmt::const_child_iterator I = Head->child_begin();
  695. I != Head->child_end(); ++I)
  696. WorkList.push_back(*I);
  697. }
  698. }
  699. //===----------------------------------------------------------------------===//
  700. // Visitor that tries to report interesting diagnostics from conditions.
  701. //===----------------------------------------------------------------------===//
  702. /// Return the tag associated with this visitor. This tag will be used
  703. /// to make all PathDiagnosticPieces created by this visitor.
  704. const char *ConditionBRVisitor::getTag() {
  705. return "ConditionBRVisitor";
  706. }
  707. PathDiagnosticPiece *ConditionBRVisitor::VisitNode(const ExplodedNode *N,
  708. const ExplodedNode *Prev,
  709. BugReporterContext &BRC,
  710. BugReport &BR) {
  711. PathDiagnosticPiece *piece = VisitNodeImpl(N, Prev, BRC, BR);
  712. if (piece) {
  713. piece->setTag(getTag());
  714. if (PathDiagnosticEventPiece *ev=dyn_cast<PathDiagnosticEventPiece>(piece))
  715. ev->setPrunable(true, /* override */ false);
  716. }
  717. return piece;
  718. }
  719. PathDiagnosticPiece *ConditionBRVisitor::VisitNodeImpl(const ExplodedNode *N,
  720. const ExplodedNode *Prev,
  721. BugReporterContext &BRC,
  722. BugReport &BR) {
  723. ProgramPoint progPoint = N->getLocation();
  724. ProgramStateRef CurrentState = N->getState();
  725. ProgramStateRef PrevState = Prev->getState();
  726. // Compare the GDMs of the state, because that is where constraints
  727. // are managed. Note that ensure that we only look at nodes that
  728. // were generated by the analyzer engine proper, not checkers.
  729. if (CurrentState->getGDM().getRoot() ==
  730. PrevState->getGDM().getRoot())
  731. return 0;
  732. // If an assumption was made on a branch, it should be caught
  733. // here by looking at the state transition.
  734. if (const BlockEdge *BE = dyn_cast<BlockEdge>(&progPoint)) {
  735. const CFGBlock *srcBlk = BE->getSrc();
  736. if (const Stmt *term = srcBlk->getTerminator())
  737. return VisitTerminator(term, N, srcBlk, BE->getDst(), BR, BRC);
  738. return 0;
  739. }
  740. if (const PostStmt *PS = dyn_cast<PostStmt>(&progPoint)) {
  741. // FIXME: Assuming that BugReporter is a GRBugReporter is a layering
  742. // violation.
  743. const std::pair<const ProgramPointTag *, const ProgramPointTag *> &tags =
  744. cast<GRBugReporter>(BRC.getBugReporter()).
  745. getEngine().geteagerlyAssumeBinOpBifurcationTags();
  746. const ProgramPointTag *tag = PS->getTag();
  747. if (tag == tags.first)
  748. return VisitTrueTest(cast<Expr>(PS->getStmt()), true,
  749. BRC, BR, N);
  750. if (tag == tags.second)
  751. return VisitTrueTest(cast<Expr>(PS->getStmt()), false,
  752. BRC, BR, N);
  753. return 0;
  754. }
  755. return 0;
  756. }
  757. PathDiagnosticPiece *
  758. ConditionBRVisitor::VisitTerminator(const Stmt *Term,
  759. const ExplodedNode *N,
  760. const CFGBlock *srcBlk,
  761. const CFGBlock *dstBlk,
  762. BugReport &R,
  763. BugReporterContext &BRC) {
  764. const Expr *Cond = 0;
  765. switch (Term->getStmtClass()) {
  766. default:
  767. return 0;
  768. case Stmt::IfStmtClass:
  769. Cond = cast<IfStmt>(Term)->getCond();
  770. break;
  771. case Stmt::ConditionalOperatorClass:
  772. Cond = cast<ConditionalOperator>(Term)->getCond();
  773. break;
  774. }
  775. assert(Cond);
  776. assert(srcBlk->succ_size() == 2);
  777. const bool tookTrue = *(srcBlk->succ_begin()) == dstBlk;
  778. return VisitTrueTest(Cond, tookTrue, BRC, R, N);
  779. }
  780. PathDiagnosticPiece *
  781. ConditionBRVisitor::VisitTrueTest(const Expr *Cond,
  782. bool tookTrue,
  783. BugReporterContext &BRC,
  784. BugReport &R,
  785. const ExplodedNode *N) {
  786. const Expr *Ex = Cond;
  787. while (true) {
  788. Ex = Ex->IgnoreParenCasts();
  789. switch (Ex->getStmtClass()) {
  790. default:
  791. return 0;
  792. case Stmt::BinaryOperatorClass:
  793. return VisitTrueTest(Cond, cast<BinaryOperator>(Ex), tookTrue, BRC,
  794. R, N);
  795. case Stmt::DeclRefExprClass:
  796. return VisitTrueTest(Cond, cast<DeclRefExpr>(Ex), tookTrue, BRC,
  797. R, N);
  798. case Stmt::UnaryOperatorClass: {
  799. const UnaryOperator *UO = cast<UnaryOperator>(Ex);
  800. if (UO->getOpcode() == UO_LNot) {
  801. tookTrue = !tookTrue;
  802. Ex = UO->getSubExpr();
  803. continue;
  804. }
  805. return 0;
  806. }
  807. }
  808. }
  809. }
  810. bool ConditionBRVisitor::patternMatch(const Expr *Ex, raw_ostream &Out,
  811. BugReporterContext &BRC,
  812. BugReport &report,
  813. const ExplodedNode *N,
  814. Optional<bool> &prunable) {
  815. const Expr *OriginalExpr = Ex;
  816. Ex = Ex->IgnoreParenCasts();
  817. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Ex)) {
  818. const bool quotes = isa<VarDecl>(DR->getDecl());
  819. if (quotes) {
  820. Out << '\'';
  821. const LocationContext *LCtx = N->getLocationContext();
  822. const ProgramState *state = N->getState().getPtr();
  823. if (const MemRegion *R = state->getLValue(cast<VarDecl>(DR->getDecl()),
  824. LCtx).getAsRegion()) {
  825. if (report.isInteresting(R))
  826. prunable = false;
  827. else {
  828. const ProgramState *state = N->getState().getPtr();
  829. SVal V = state->getSVal(R);
  830. if (report.isInteresting(V))
  831. prunable = false;
  832. }
  833. }
  834. }
  835. Out << DR->getDecl()->getDeclName().getAsString();
  836. if (quotes)
  837. Out << '\'';
  838. return quotes;
  839. }
  840. if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(Ex)) {
  841. QualType OriginalTy = OriginalExpr->getType();
  842. if (OriginalTy->isPointerType()) {
  843. if (IL->getValue() == 0) {
  844. Out << "null";
  845. return false;
  846. }
  847. }
  848. else if (OriginalTy->isObjCObjectPointerType()) {
  849. if (IL->getValue() == 0) {
  850. Out << "nil";
  851. return false;
  852. }
  853. }
  854. Out << IL->getValue();
  855. return false;
  856. }
  857. return false;
  858. }
  859. PathDiagnosticPiece *
  860. ConditionBRVisitor::VisitTrueTest(const Expr *Cond,
  861. const BinaryOperator *BExpr,
  862. const bool tookTrue,
  863. BugReporterContext &BRC,
  864. BugReport &R,
  865. const ExplodedNode *N) {
  866. bool shouldInvert = false;
  867. Optional<bool> shouldPrune;
  868. SmallString<128> LhsString, RhsString;
  869. {
  870. llvm::raw_svector_ostream OutLHS(LhsString), OutRHS(RhsString);
  871. const bool isVarLHS = patternMatch(BExpr->getLHS(), OutLHS, BRC, R, N,
  872. shouldPrune);
  873. const bool isVarRHS = patternMatch(BExpr->getRHS(), OutRHS, BRC, R, N,
  874. shouldPrune);
  875. shouldInvert = !isVarLHS && isVarRHS;
  876. }
  877. BinaryOperator::Opcode Op = BExpr->getOpcode();
  878. if (BinaryOperator::isAssignmentOp(Op)) {
  879. // For assignment operators, all that we care about is that the LHS
  880. // evaluates to "true" or "false".
  881. return VisitConditionVariable(LhsString, BExpr->getLHS(), tookTrue,
  882. BRC, R, N);
  883. }
  884. // For non-assignment operations, we require that we can understand
  885. // both the LHS and RHS.
  886. if (LhsString.empty() || RhsString.empty())
  887. return 0;
  888. // Should we invert the strings if the LHS is not a variable name?
  889. SmallString<256> buf;
  890. llvm::raw_svector_ostream Out(buf);
  891. Out << "Assuming " << (shouldInvert ? RhsString : LhsString) << " is ";
  892. // Do we need to invert the opcode?
  893. if (shouldInvert)
  894. switch (Op) {
  895. default: break;
  896. case BO_LT: Op = BO_GT; break;
  897. case BO_GT: Op = BO_LT; break;
  898. case BO_LE: Op = BO_GE; break;
  899. case BO_GE: Op = BO_LE; break;
  900. }
  901. if (!tookTrue)
  902. switch (Op) {
  903. case BO_EQ: Op = BO_NE; break;
  904. case BO_NE: Op = BO_EQ; break;
  905. case BO_LT: Op = BO_GE; break;
  906. case BO_GT: Op = BO_LE; break;
  907. case BO_LE: Op = BO_GT; break;
  908. case BO_GE: Op = BO_LT; break;
  909. default:
  910. return 0;
  911. }
  912. switch (Op) {
  913. case BO_EQ:
  914. Out << "equal to ";
  915. break;
  916. case BO_NE:
  917. Out << "not equal to ";
  918. break;
  919. default:
  920. Out << BinaryOperator::getOpcodeStr(Op) << ' ';
  921. break;
  922. }
  923. Out << (shouldInvert ? LhsString : RhsString);
  924. const LocationContext *LCtx = N->getLocationContext();
  925. PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
  926. PathDiagnosticEventPiece *event =
  927. new PathDiagnosticEventPiece(Loc, Out.str());
  928. if (shouldPrune.hasValue())
  929. event->setPrunable(shouldPrune.getValue());
  930. return event;
  931. }
  932. PathDiagnosticPiece *
  933. ConditionBRVisitor::VisitConditionVariable(StringRef LhsString,
  934. const Expr *CondVarExpr,
  935. const bool tookTrue,
  936. BugReporterContext &BRC,
  937. BugReport &report,
  938. const ExplodedNode *N) {
  939. // FIXME: If there's already a constraint tracker for this variable,
  940. // we shouldn't emit anything here (c.f. the double note in
  941. // test/Analysis/inlining/path-notes.c)
  942. SmallString<256> buf;
  943. llvm::raw_svector_ostream Out(buf);
  944. Out << "Assuming " << LhsString << " is ";
  945. QualType Ty = CondVarExpr->getType();
  946. if (Ty->isPointerType())
  947. Out << (tookTrue ? "not null" : "null");
  948. else if (Ty->isObjCObjectPointerType())
  949. Out << (tookTrue ? "not nil" : "nil");
  950. else if (Ty->isBooleanType())
  951. Out << (tookTrue ? "true" : "false");
  952. else if (Ty->isIntegerType())
  953. Out << (tookTrue ? "non-zero" : "zero");
  954. else
  955. return 0;
  956. const LocationContext *LCtx = N->getLocationContext();
  957. PathDiagnosticLocation Loc(CondVarExpr, BRC.getSourceManager(), LCtx);
  958. PathDiagnosticEventPiece *event =
  959. new PathDiagnosticEventPiece(Loc, Out.str());
  960. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(CondVarExpr)) {
  961. if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
  962. const ProgramState *state = N->getState().getPtr();
  963. if (const MemRegion *R = state->getLValue(VD, LCtx).getAsRegion()) {
  964. if (report.isInteresting(R))
  965. event->setPrunable(false);
  966. }
  967. }
  968. }
  969. return event;
  970. }
  971. PathDiagnosticPiece *
  972. ConditionBRVisitor::VisitTrueTest(const Expr *Cond,
  973. const DeclRefExpr *DR,
  974. const bool tookTrue,
  975. BugReporterContext &BRC,
  976. BugReport &report,
  977. const ExplodedNode *N) {
  978. const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
  979. if (!VD)
  980. return 0;
  981. SmallString<256> Buf;
  982. llvm::raw_svector_ostream Out(Buf);
  983. Out << "Assuming '";
  984. VD->getDeclName().printName(Out);
  985. Out << "' is ";
  986. QualType VDTy = VD->getType();
  987. if (VDTy->isPointerType())
  988. Out << (tookTrue ? "non-null" : "null");
  989. else if (VDTy->isObjCObjectPointerType())
  990. Out << (tookTrue ? "non-nil" : "nil");
  991. else if (VDTy->isScalarType())
  992. Out << (tookTrue ? "not equal to 0" : "0");
  993. else
  994. return 0;
  995. const LocationContext *LCtx = N->getLocationContext();
  996. PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
  997. PathDiagnosticEventPiece *event =
  998. new PathDiagnosticEventPiece(Loc, Out.str());
  999. const ProgramState *state = N->getState().getPtr();
  1000. if (const MemRegion *R = state->getLValue(VD, LCtx).getAsRegion()) {
  1001. if (report.isInteresting(R))
  1002. event->setPrunable(false);
  1003. else {
  1004. SVal V = state->getSVal(R);
  1005. if (report.isInteresting(V))
  1006. event->setPrunable(false);
  1007. }
  1008. }
  1009. return event;
  1010. }
  1011. PathDiagnosticPiece *
  1012. LikelyFalsePositiveSuppressionBRVisitor::getEndPath(BugReporterContext &BRC,
  1013. const ExplodedNode *N,
  1014. BugReport &BR) {
  1015. const Stmt *S = BR.getStmt();
  1016. if (!S)
  1017. return 0;
  1018. // Here we suppress false positives coming from system macros. This list is
  1019. // based on known issues.
  1020. // Skip reports within the sys/queue.h macros as we do not have the ability to
  1021. // reason about data structure shapes.
  1022. SourceManager &SM = BRC.getSourceManager();
  1023. SourceLocation Loc = S->getLocStart();
  1024. while (Loc.isMacroID()) {
  1025. if (SM.isInSystemMacro(Loc) &&
  1026. (SM.getFilename(SM.getSpellingLoc(Loc)).endswith("sys/queue.h"))) {
  1027. BR.markInvalid(getTag(), 0);
  1028. return 0;
  1029. }
  1030. Loc = SM.getSpellingLoc(Loc);
  1031. }
  1032. return 0;
  1033. }
  1034. PathDiagnosticPiece *
  1035. UndefOrNullArgVisitor::VisitNode(const ExplodedNode *N,
  1036. const ExplodedNode *PrevN,
  1037. BugReporterContext &BRC,
  1038. BugReport &BR) {
  1039. ProgramStateRef State = N->getState();
  1040. ProgramPoint ProgLoc = N->getLocation();
  1041. // We are only interested in visiting CallEnter nodes.
  1042. CallEnter *CEnter = dyn_cast<CallEnter>(&ProgLoc);
  1043. if (!CEnter)
  1044. return 0;
  1045. // Check if one of the arguments is the region the visitor is tracking.
  1046. CallEventManager &CEMgr = BRC.getStateManager().getCallEventManager();
  1047. CallEventRef<> Call = CEMgr.getCaller(CEnter->getCalleeContext(), State);
  1048. unsigned Idx = 0;
  1049. for (CallEvent::param_iterator I = Call->param_begin(),
  1050. E = Call->param_end(); I != E; ++I, ++Idx) {
  1051. const MemRegion *ArgReg = Call->getArgSVal(Idx).getAsRegion();
  1052. // Are we tracking the argument or its subregion?
  1053. if ( !ArgReg || (ArgReg != R && !R->isSubRegionOf(ArgReg->StripCasts())))
  1054. continue;
  1055. // Check the function parameter type.
  1056. const ParmVarDecl *ParamDecl = *I;
  1057. assert(ParamDecl && "Formal parameter has no decl?");
  1058. QualType T = ParamDecl->getType();
  1059. if (!(T->isAnyPointerType() || T->isReferenceType())) {
  1060. // Function can only change the value passed in by address.
  1061. continue;
  1062. }
  1063. // If it is a const pointer value, the function does not intend to
  1064. // change the value.
  1065. if (T->getPointeeType().isConstQualified())
  1066. continue;
  1067. // Mark the call site (LocationContext) as interesting if the value of the
  1068. // argument is undefined or '0'/'NULL'.
  1069. SVal BoundVal = State->getSVal(R);
  1070. if (BoundVal.isUndef() || BoundVal.isZeroConstant()) {
  1071. BR.markInteresting(CEnter->getCalleeContext());
  1072. return 0;
  1073. }
  1074. }
  1075. return 0;
  1076. }