BugReporterVisitors.cpp 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634
  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. using llvm::FoldingSetNodeID;
  29. //===----------------------------------------------------------------------===//
  30. // Utility functions.
  31. //===----------------------------------------------------------------------===//
  32. bool bugreporter::isDeclRefExprToReference(const Expr *E) {
  33. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  34. return DRE->getDecl()->getType()->isReferenceType();
  35. }
  36. return false;
  37. }
  38. const Expr *bugreporter::getDerefExpr(const Stmt *S) {
  39. // Pattern match for a few useful cases:
  40. // a[0], p->f, *p
  41. const Expr *E = dyn_cast<Expr>(S);
  42. if (!E)
  43. return nullptr;
  44. E = E->IgnoreParenCasts();
  45. while (true) {
  46. if (const BinaryOperator *B = dyn_cast<BinaryOperator>(E)) {
  47. assert(B->isAssignmentOp());
  48. E = B->getLHS()->IgnoreParenCasts();
  49. continue;
  50. }
  51. else if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
  52. if (U->getOpcode() == UO_Deref)
  53. return U->getSubExpr()->IgnoreParenCasts();
  54. }
  55. else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  56. if (ME->isArrow() || isDeclRefExprToReference(ME->getBase())) {
  57. return ME->getBase()->IgnoreParenCasts();
  58. } else {
  59. // If we have a member expr with a dot, the base must have been
  60. // dereferenced.
  61. return getDerefExpr(ME->getBase());
  62. }
  63. }
  64. else if (const ObjCIvarRefExpr *IvarRef = dyn_cast<ObjCIvarRefExpr>(E)) {
  65. return IvarRef->getBase()->IgnoreParenCasts();
  66. }
  67. else if (const ArraySubscriptExpr *AE = dyn_cast<ArraySubscriptExpr>(E)) {
  68. return AE->getBase();
  69. }
  70. else if (isDeclRefExprToReference(E)) {
  71. return E;
  72. }
  73. break;
  74. }
  75. return nullptr;
  76. }
  77. const Stmt *bugreporter::GetDenomExpr(const ExplodedNode *N) {
  78. const Stmt *S = N->getLocationAs<PreStmt>()->getStmt();
  79. if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(S))
  80. return BE->getRHS();
  81. return nullptr;
  82. }
  83. const Stmt *bugreporter::GetRetValExpr(const ExplodedNode *N) {
  84. const Stmt *S = N->getLocationAs<PostStmt>()->getStmt();
  85. if (const ReturnStmt *RS = dyn_cast<ReturnStmt>(S))
  86. return RS->getRetValue();
  87. return nullptr;
  88. }
  89. //===----------------------------------------------------------------------===//
  90. // Definitions for bug reporter visitors.
  91. //===----------------------------------------------------------------------===//
  92. std::unique_ptr<PathDiagnosticPiece>
  93. BugReporterVisitor::getEndPath(BugReporterContext &BRC,
  94. const ExplodedNode *EndPathNode, BugReport &BR) {
  95. return nullptr;
  96. }
  97. std::unique_ptr<PathDiagnosticPiece> BugReporterVisitor::getDefaultEndPath(
  98. BugReporterContext &BRC, const ExplodedNode *EndPathNode, BugReport &BR) {
  99. PathDiagnosticLocation L =
  100. PathDiagnosticLocation::createEndOfPath(EndPathNode,BRC.getSourceManager());
  101. const auto &Ranges = BR.getRanges();
  102. // Only add the statement itself as a range if we didn't specify any
  103. // special ranges for this report.
  104. auto P = llvm::make_unique<PathDiagnosticEventPiece>(
  105. L, BR.getDescription(), Ranges.begin() == Ranges.end());
  106. for (const SourceRange &Range : Ranges)
  107. P->addRange(Range);
  108. return std::move(P);
  109. }
  110. namespace {
  111. /// Emits an extra note at the return statement of an interesting stack frame.
  112. ///
  113. /// The returned value is marked as an interesting value, and if it's null,
  114. /// adds a visitor to track where it became null.
  115. ///
  116. /// This visitor is intended to be used when another visitor discovers that an
  117. /// interesting value comes from an inlined function call.
  118. class ReturnVisitor : public BugReporterVisitorImpl<ReturnVisitor> {
  119. const StackFrameContext *StackFrame;
  120. enum {
  121. Initial,
  122. MaybeUnsuppress,
  123. Satisfied
  124. } Mode;
  125. bool EnableNullFPSuppression;
  126. public:
  127. ReturnVisitor(const StackFrameContext *Frame, bool Suppressed)
  128. : StackFrame(Frame), Mode(Initial), EnableNullFPSuppression(Suppressed) {}
  129. static void *getTag() {
  130. static int Tag = 0;
  131. return static_cast<void *>(&Tag);
  132. }
  133. void Profile(llvm::FoldingSetNodeID &ID) const override {
  134. ID.AddPointer(ReturnVisitor::getTag());
  135. ID.AddPointer(StackFrame);
  136. ID.AddBoolean(EnableNullFPSuppression);
  137. }
  138. /// Adds a ReturnVisitor if the given statement represents a call that was
  139. /// inlined.
  140. ///
  141. /// This will search back through the ExplodedGraph, starting from the given
  142. /// node, looking for when the given statement was processed. If it turns out
  143. /// the statement is a call that was inlined, we add the visitor to the
  144. /// bug report, so it can print a note later.
  145. static void addVisitorIfNecessary(const ExplodedNode *Node, const Stmt *S,
  146. BugReport &BR,
  147. bool InEnableNullFPSuppression) {
  148. if (!CallEvent::isCallStmt(S))
  149. return;
  150. // First, find when we processed the statement.
  151. do {
  152. if (Optional<CallExitEnd> CEE = Node->getLocationAs<CallExitEnd>())
  153. if (CEE->getCalleeContext()->getCallSite() == S)
  154. break;
  155. if (Optional<StmtPoint> SP = Node->getLocationAs<StmtPoint>())
  156. if (SP->getStmt() == S)
  157. break;
  158. Node = Node->getFirstPred();
  159. } while (Node);
  160. // Next, step over any post-statement checks.
  161. while (Node && Node->getLocation().getAs<PostStmt>())
  162. Node = Node->getFirstPred();
  163. if (!Node)
  164. return;
  165. // Finally, see if we inlined the call.
  166. Optional<CallExitEnd> CEE = Node->getLocationAs<CallExitEnd>();
  167. if (!CEE)
  168. return;
  169. const StackFrameContext *CalleeContext = CEE->getCalleeContext();
  170. if (CalleeContext->getCallSite() != S)
  171. return;
  172. // Check the return value.
  173. ProgramStateRef State = Node->getState();
  174. SVal RetVal = State->getSVal(S, Node->getLocationContext());
  175. // Handle cases where a reference is returned and then immediately used.
  176. if (cast<Expr>(S)->isGLValue())
  177. if (Optional<Loc> LValue = RetVal.getAs<Loc>())
  178. RetVal = State->getSVal(*LValue);
  179. // See if the return value is NULL. If so, suppress the report.
  180. SubEngine *Eng = State->getStateManager().getOwningEngine();
  181. assert(Eng && "Cannot file a bug report without an owning engine");
  182. AnalyzerOptions &Options = Eng->getAnalysisManager().options;
  183. bool EnableNullFPSuppression = false;
  184. if (InEnableNullFPSuppression && Options.shouldSuppressNullReturnPaths())
  185. if (Optional<Loc> RetLoc = RetVal.getAs<Loc>())
  186. EnableNullFPSuppression = State->isNull(*RetLoc).isConstrainedTrue();
  187. BR.markInteresting(CalleeContext);
  188. BR.addVisitor(llvm::make_unique<ReturnVisitor>(CalleeContext,
  189. EnableNullFPSuppression));
  190. }
  191. /// Returns true if any counter-suppression heuristics are enabled for
  192. /// ReturnVisitor.
  193. static bool hasCounterSuppression(AnalyzerOptions &Options) {
  194. return Options.shouldAvoidSuppressingNullArgumentPaths();
  195. }
  196. PathDiagnosticPiece *visitNodeInitial(const ExplodedNode *N,
  197. const ExplodedNode *PrevN,
  198. BugReporterContext &BRC,
  199. BugReport &BR) {
  200. // Only print a message at the interesting return statement.
  201. if (N->getLocationContext() != StackFrame)
  202. return nullptr;
  203. Optional<StmtPoint> SP = N->getLocationAs<StmtPoint>();
  204. if (!SP)
  205. return nullptr;
  206. const ReturnStmt *Ret = dyn_cast<ReturnStmt>(SP->getStmt());
  207. if (!Ret)
  208. return nullptr;
  209. // Okay, we're at the right return statement, but do we have the return
  210. // value available?
  211. ProgramStateRef State = N->getState();
  212. SVal V = State->getSVal(Ret, StackFrame);
  213. if (V.isUnknownOrUndef())
  214. return nullptr;
  215. // Don't print any more notes after this one.
  216. Mode = Satisfied;
  217. const Expr *RetE = Ret->getRetValue();
  218. assert(RetE && "Tracking a return value for a void function");
  219. // Handle cases where a reference is returned and then immediately used.
  220. Optional<Loc> LValue;
  221. if (RetE->isGLValue()) {
  222. if ((LValue = V.getAs<Loc>())) {
  223. SVal RValue = State->getRawSVal(*LValue, RetE->getType());
  224. if (RValue.getAs<DefinedSVal>())
  225. V = RValue;
  226. }
  227. }
  228. // Ignore aggregate rvalues.
  229. if (V.getAs<nonloc::LazyCompoundVal>() ||
  230. V.getAs<nonloc::CompoundVal>())
  231. return nullptr;
  232. RetE = RetE->IgnoreParenCasts();
  233. // 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->isNull(V).isConstrainedTrue()) {
  236. BR.markInteresting(V);
  237. ReturnVisitor::addVisitorIfNecessary(N, RetE, BR,
  238. EnableNullFPSuppression);
  239. return nullptr;
  240. }
  241. // If we're returning 0, we should track where that 0 came from.
  242. bugreporter::trackNullOrUndefValue(N, RetE, BR, /*IsArg*/ false,
  243. EnableNullFPSuppression);
  244. // Build an appropriate message based on the return value.
  245. SmallString<64> Msg;
  246. llvm::raw_svector_ostream Out(Msg);
  247. if (V.getAs<Loc>()) {
  248. // If we have counter-suppression enabled, make sure we keep visiting
  249. // future nodes. We want to emit a path note as well, in case
  250. // the report is resurrected as valid later on.
  251. ExprEngine &Eng = BRC.getBugReporter().getEngine();
  252. AnalyzerOptions &Options = Eng.getAnalysisManager().options;
  253. if (EnableNullFPSuppression && hasCounterSuppression(Options))
  254. Mode = MaybeUnsuppress;
  255. if (RetE->getType()->isObjCObjectPointerType())
  256. Out << "Returning nil";
  257. else
  258. Out << "Returning null pointer";
  259. } else {
  260. Out << "Returning zero";
  261. }
  262. if (LValue) {
  263. if (const MemRegion *MR = LValue->getAsRegion()) {
  264. if (MR->canPrintPretty()) {
  265. Out << " (reference to ";
  266. MR->printPretty(Out);
  267. Out << ")";
  268. }
  269. }
  270. } else {
  271. // FIXME: We should have a more generalized location printing mechanism.
  272. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(RetE))
  273. if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(DR->getDecl()))
  274. Out << " (loaded from '" << *DD << "')";
  275. }
  276. PathDiagnosticLocation L(Ret, BRC.getSourceManager(), StackFrame);
  277. return new PathDiagnosticEventPiece(L, Out.str());
  278. }
  279. PathDiagnosticPiece *visitNodeMaybeUnsuppress(const ExplodedNode *N,
  280. const ExplodedNode *PrevN,
  281. BugReporterContext &BRC,
  282. BugReport &BR) {
  283. #ifndef NDEBUG
  284. ExprEngine &Eng = BRC.getBugReporter().getEngine();
  285. AnalyzerOptions &Options = Eng.getAnalysisManager().options;
  286. assert(hasCounterSuppression(Options));
  287. #endif
  288. // Are we at the entry node for this call?
  289. Optional<CallEnter> CE = N->getLocationAs<CallEnter>();
  290. if (!CE)
  291. return nullptr;
  292. if (CE->getCalleeContext() != StackFrame)
  293. return nullptr;
  294. Mode = Satisfied;
  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. ProgramStateRef State = N->getState();
  301. CallEventRef<> Call = CallMgr.getCaller(StackFrame, State);
  302. for (unsigned I = 0, E = Call->getNumArgs(); I != E; ++I) {
  303. Optional<Loc> ArgV = Call->getArgSVal(I).getAs<Loc>();
  304. if (!ArgV)
  305. continue;
  306. const Expr *ArgE = Call->getArgExpr(I);
  307. if (!ArgE)
  308. continue;
  309. // Is it possible for this argument to be non-null?
  310. if (!State->isNull(*ArgV).isConstrainedTrue())
  311. continue;
  312. if (bugreporter::trackNullOrUndefValue(N, ArgE, BR, /*IsArg=*/true,
  313. EnableNullFPSuppression))
  314. BR.removeInvalidation(ReturnVisitor::getTag(), StackFrame);
  315. // If we /can't/ track the null pointer, we should err on the side of
  316. // false negatives, and continue towards marking this report invalid.
  317. // (We will still look at the other arguments, though.)
  318. }
  319. return nullptr;
  320. }
  321. PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
  322. const ExplodedNode *PrevN,
  323. BugReporterContext &BRC,
  324. BugReport &BR) override {
  325. switch (Mode) {
  326. case Initial:
  327. return visitNodeInitial(N, PrevN, BRC, BR);
  328. case MaybeUnsuppress:
  329. return visitNodeMaybeUnsuppress(N, PrevN, BRC, BR);
  330. case Satisfied:
  331. return nullptr;
  332. }
  333. llvm_unreachable("Invalid visit mode!");
  334. }
  335. std::unique_ptr<PathDiagnosticPiece> getEndPath(BugReporterContext &BRC,
  336. const ExplodedNode *N,
  337. BugReport &BR) override {
  338. if (EnableNullFPSuppression)
  339. BR.markInvalid(ReturnVisitor::getTag(), StackFrame);
  340. return nullptr;
  341. }
  342. };
  343. } // end anonymous namespace
  344. void FindLastStoreBRVisitor ::Profile(llvm::FoldingSetNodeID &ID) const {
  345. static int tag = 0;
  346. ID.AddPointer(&tag);
  347. ID.AddPointer(R);
  348. ID.Add(V);
  349. ID.AddBoolean(EnableNullFPSuppression);
  350. }
  351. /// Returns true if \p N represents the DeclStmt declaring and initializing
  352. /// \p VR.
  353. static bool isInitializationOfVar(const ExplodedNode *N, const VarRegion *VR) {
  354. Optional<PostStmt> P = N->getLocationAs<PostStmt>();
  355. if (!P)
  356. return false;
  357. const DeclStmt *DS = P->getStmtAs<DeclStmt>();
  358. if (!DS)
  359. return false;
  360. if (DS->getSingleDecl() != VR->getDecl())
  361. return false;
  362. const MemSpaceRegion *VarSpace = VR->getMemorySpace();
  363. const StackSpaceRegion *FrameSpace = dyn_cast<StackSpaceRegion>(VarSpace);
  364. if (!FrameSpace) {
  365. // If we ever directly evaluate global DeclStmts, this assertion will be
  366. // invalid, but this still seems preferable to silently accepting an
  367. // initialization that may be for a path-sensitive variable.
  368. assert(VR->getDecl()->isStaticLocal() && "non-static stackless VarRegion");
  369. return true;
  370. }
  371. assert(VR->getDecl()->hasLocalStorage());
  372. const LocationContext *LCtx = N->getLocationContext();
  373. return FrameSpace->getStackFrame() == LCtx->getCurrentStackFrame();
  374. }
  375. PathDiagnosticPiece *FindLastStoreBRVisitor::VisitNode(const ExplodedNode *Succ,
  376. const ExplodedNode *Pred,
  377. BugReporterContext &BRC,
  378. BugReport &BR) {
  379. if (Satisfied)
  380. return nullptr;
  381. const ExplodedNode *StoreSite = nullptr;
  382. const Expr *InitE = nullptr;
  383. bool IsParam = false;
  384. // First see if we reached the declaration of the region.
  385. if (const VarRegion *VR = dyn_cast<VarRegion>(R)) {
  386. if (isInitializationOfVar(Pred, VR)) {
  387. StoreSite = Pred;
  388. InitE = VR->getDecl()->getInit();
  389. }
  390. }
  391. // If this is a post initializer expression, initializing the region, we
  392. // should track the initializer expression.
  393. if (Optional<PostInitializer> PIP = Pred->getLocationAs<PostInitializer>()) {
  394. const MemRegion *FieldReg = (const MemRegion *)PIP->getLocationValue();
  395. if (FieldReg && FieldReg == R) {
  396. StoreSite = Pred;
  397. InitE = PIP->getInitializer()->getInit();
  398. }
  399. }
  400. // Otherwise, see if this is the store site:
  401. // (1) Succ has this binding and Pred does not, i.e. this is
  402. // where the binding first occurred.
  403. // (2) Succ has this binding and is a PostStore node for this region, i.e.
  404. // the same binding was re-assigned here.
  405. if (!StoreSite) {
  406. if (Succ->getState()->getSVal(R) != V)
  407. return nullptr;
  408. if (Pred->getState()->getSVal(R) == V) {
  409. Optional<PostStore> PS = Succ->getLocationAs<PostStore>();
  410. if (!PS || PS->getLocationValue() != R)
  411. return nullptr;
  412. }
  413. StoreSite = Succ;
  414. // If this is an assignment expression, we can track the value
  415. // being assigned.
  416. if (Optional<PostStmt> P = Succ->getLocationAs<PostStmt>())
  417. if (const BinaryOperator *BO = P->getStmtAs<BinaryOperator>())
  418. if (BO->isAssignmentOp())
  419. InitE = BO->getRHS();
  420. // If this is a call entry, the variable should be a parameter.
  421. // FIXME: Handle CXXThisRegion as well. (This is not a priority because
  422. // 'this' should never be NULL, but this visitor isn't just for NULL and
  423. // UndefinedVal.)
  424. if (Optional<CallEnter> CE = Succ->getLocationAs<CallEnter>()) {
  425. if (const VarRegion *VR = dyn_cast<VarRegion>(R)) {
  426. const ParmVarDecl *Param = cast<ParmVarDecl>(VR->getDecl());
  427. ProgramStateManager &StateMgr = BRC.getStateManager();
  428. CallEventManager &CallMgr = StateMgr.getCallEventManager();
  429. CallEventRef<> Call = CallMgr.getCaller(CE->getCalleeContext(),
  430. Succ->getState());
  431. InitE = Call->getArgExpr(Param->getFunctionScopeIndex());
  432. IsParam = true;
  433. }
  434. }
  435. // If this is a CXXTempObjectRegion, the Expr responsible for its creation
  436. // is wrapped inside of it.
  437. if (const CXXTempObjectRegion *TmpR = dyn_cast<CXXTempObjectRegion>(R))
  438. InitE = TmpR->getExpr();
  439. }
  440. if (!StoreSite)
  441. return nullptr;
  442. Satisfied = true;
  443. // If we have an expression that provided the value, try to track where it
  444. // came from.
  445. if (InitE) {
  446. if (V.isUndef() ||
  447. V.getAs<loc::ConcreteInt>() || V.getAs<nonloc::ConcreteInt>()) {
  448. if (!IsParam)
  449. InitE = InitE->IgnoreParenCasts();
  450. bugreporter::trackNullOrUndefValue(StoreSite, InitE, BR, IsParam,
  451. EnableNullFPSuppression);
  452. } else {
  453. ReturnVisitor::addVisitorIfNecessary(StoreSite, InitE->IgnoreParenCasts(),
  454. BR, EnableNullFPSuppression);
  455. }
  456. }
  457. // Okay, we've found the binding. Emit an appropriate message.
  458. SmallString<256> sbuf;
  459. llvm::raw_svector_ostream os(sbuf);
  460. if (Optional<PostStmt> PS = StoreSite->getLocationAs<PostStmt>()) {
  461. const Stmt *S = PS->getStmt();
  462. const char *action = nullptr;
  463. const DeclStmt *DS = dyn_cast<DeclStmt>(S);
  464. const VarRegion *VR = dyn_cast<VarRegion>(R);
  465. if (DS) {
  466. action = R->canPrintPretty() ? "initialized to " :
  467. "Initializing to ";
  468. } else if (isa<BlockExpr>(S)) {
  469. action = R->canPrintPretty() ? "captured by block as " :
  470. "Captured by block as ";
  471. if (VR) {
  472. // See if we can get the BlockVarRegion.
  473. ProgramStateRef State = StoreSite->getState();
  474. SVal V = State->getSVal(S, PS->getLocationContext());
  475. if (const BlockDataRegion *BDR =
  476. dyn_cast_or_null<BlockDataRegion>(V.getAsRegion())) {
  477. if (const VarRegion *OriginalR = BDR->getOriginalRegion(VR)) {
  478. if (Optional<KnownSVal> KV =
  479. State->getSVal(OriginalR).getAs<KnownSVal>())
  480. BR.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
  481. *KV, OriginalR, EnableNullFPSuppression));
  482. }
  483. }
  484. }
  485. }
  486. if (action) {
  487. if (R->canPrintPretty()) {
  488. R->printPretty(os);
  489. os << " ";
  490. }
  491. if (V.getAs<loc::ConcreteInt>()) {
  492. bool b = false;
  493. if (R->isBoundable()) {
  494. if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R)) {
  495. if (TR->getValueType()->isObjCObjectPointerType()) {
  496. os << action << "nil";
  497. b = true;
  498. }
  499. }
  500. }
  501. if (!b)
  502. os << action << "a null pointer value";
  503. } else if (Optional<nonloc::ConcreteInt> CVal =
  504. V.getAs<nonloc::ConcreteInt>()) {
  505. os << action << CVal->getValue();
  506. }
  507. else if (DS) {
  508. if (V.isUndef()) {
  509. if (isa<VarRegion>(R)) {
  510. const VarDecl *VD = cast<VarDecl>(DS->getSingleDecl());
  511. if (VD->getInit()) {
  512. os << (R->canPrintPretty() ? "initialized" : "Initializing")
  513. << " to a garbage value";
  514. } else {
  515. os << (R->canPrintPretty() ? "declared" : "Declaring")
  516. << " without an initial value";
  517. }
  518. }
  519. }
  520. else {
  521. os << (R->canPrintPretty() ? "initialized" : "Initialized")
  522. << " here";
  523. }
  524. }
  525. }
  526. } else if (StoreSite->getLocation().getAs<CallEnter>()) {
  527. if (const VarRegion *VR = dyn_cast<VarRegion>(R)) {
  528. const ParmVarDecl *Param = cast<ParmVarDecl>(VR->getDecl());
  529. os << "Passing ";
  530. if (V.getAs<loc::ConcreteInt>()) {
  531. if (Param->getType()->isObjCObjectPointerType())
  532. os << "nil object reference";
  533. else
  534. os << "null pointer value";
  535. } else if (V.isUndef()) {
  536. os << "uninitialized value";
  537. } else if (Optional<nonloc::ConcreteInt> CI =
  538. V.getAs<nonloc::ConcreteInt>()) {
  539. os << "the value " << CI->getValue();
  540. } else {
  541. os << "value";
  542. }
  543. // Printed parameter indexes are 1-based, not 0-based.
  544. unsigned Idx = Param->getFunctionScopeIndex() + 1;
  545. os << " via " << Idx << llvm::getOrdinalSuffix(Idx) << " parameter";
  546. if (R->canPrintPretty()) {
  547. os << " ";
  548. R->printPretty(os);
  549. }
  550. }
  551. }
  552. if (os.str().empty()) {
  553. if (V.getAs<loc::ConcreteInt>()) {
  554. bool b = false;
  555. if (R->isBoundable()) {
  556. if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R)) {
  557. if (TR->getValueType()->isObjCObjectPointerType()) {
  558. os << "nil object reference stored";
  559. b = true;
  560. }
  561. }
  562. }
  563. if (!b) {
  564. if (R->canPrintPretty())
  565. os << "Null pointer value stored";
  566. else
  567. os << "Storing null pointer value";
  568. }
  569. } else if (V.isUndef()) {
  570. if (R->canPrintPretty())
  571. os << "Uninitialized value stored";
  572. else
  573. os << "Storing uninitialized value";
  574. } else if (Optional<nonloc::ConcreteInt> CV =
  575. V.getAs<nonloc::ConcreteInt>()) {
  576. if (R->canPrintPretty())
  577. os << "The value " << CV->getValue() << " is assigned";
  578. else
  579. os << "Assigning " << CV->getValue();
  580. } else {
  581. if (R->canPrintPretty())
  582. os << "Value assigned";
  583. else
  584. os << "Assigning value";
  585. }
  586. if (R->canPrintPretty()) {
  587. os << " to ";
  588. R->printPretty(os);
  589. }
  590. }
  591. // Construct a new PathDiagnosticPiece.
  592. ProgramPoint P = StoreSite->getLocation();
  593. PathDiagnosticLocation L;
  594. if (P.getAs<CallEnter>() && InitE)
  595. L = PathDiagnosticLocation(InitE, BRC.getSourceManager(),
  596. P.getLocationContext());
  597. if (!L.isValid() || !L.asLocation().isValid())
  598. L = PathDiagnosticLocation::create(P, BRC.getSourceManager());
  599. if (!L.isValid() || !L.asLocation().isValid())
  600. return nullptr;
  601. return new PathDiagnosticEventPiece(L, os.str());
  602. }
  603. void TrackConstraintBRVisitor::Profile(llvm::FoldingSetNodeID &ID) const {
  604. static int tag = 0;
  605. ID.AddPointer(&tag);
  606. ID.AddBoolean(Assumption);
  607. ID.Add(Constraint);
  608. }
  609. /// Return the tag associated with this visitor. This tag will be used
  610. /// to make all PathDiagnosticPieces created by this visitor.
  611. const char *TrackConstraintBRVisitor::getTag() {
  612. return "TrackConstraintBRVisitor";
  613. }
  614. bool TrackConstraintBRVisitor::isUnderconstrained(const ExplodedNode *N) const {
  615. if (IsZeroCheck)
  616. return N->getState()->isNull(Constraint).isUnderconstrained();
  617. return (bool)N->getState()->assume(Constraint, !Assumption);
  618. }
  619. PathDiagnosticPiece *
  620. TrackConstraintBRVisitor::VisitNode(const ExplodedNode *N,
  621. const ExplodedNode *PrevN,
  622. BugReporterContext &BRC,
  623. BugReport &BR) {
  624. if (IsSatisfied)
  625. return nullptr;
  626. // Start tracking after we see the first state in which the value is
  627. // constrained.
  628. if (!IsTrackingTurnedOn)
  629. if (!isUnderconstrained(N))
  630. IsTrackingTurnedOn = true;
  631. if (!IsTrackingTurnedOn)
  632. return nullptr;
  633. // Check if in the previous state it was feasible for this constraint
  634. // to *not* be true.
  635. if (isUnderconstrained(PrevN)) {
  636. IsSatisfied = true;
  637. // As a sanity check, make sure that the negation of the constraint
  638. // was infeasible in the current state. If it is feasible, we somehow
  639. // missed the transition point.
  640. assert(!isUnderconstrained(N));
  641. // We found the transition point for the constraint. We now need to
  642. // pretty-print the constraint. (work-in-progress)
  643. SmallString<64> sbuf;
  644. llvm::raw_svector_ostream os(sbuf);
  645. if (Constraint.getAs<Loc>()) {
  646. os << "Assuming pointer value is ";
  647. os << (Assumption ? "non-null" : "null");
  648. }
  649. if (os.str().empty())
  650. return nullptr;
  651. // Construct a new PathDiagnosticPiece.
  652. ProgramPoint P = N->getLocation();
  653. PathDiagnosticLocation L =
  654. PathDiagnosticLocation::create(P, BRC.getSourceManager());
  655. if (!L.isValid())
  656. return nullptr;
  657. PathDiagnosticEventPiece *X = new PathDiagnosticEventPiece(L, os.str());
  658. X->setTag(getTag());
  659. return X;
  660. }
  661. return nullptr;
  662. }
  663. SuppressInlineDefensiveChecksVisitor::
  664. SuppressInlineDefensiveChecksVisitor(DefinedSVal Value, const ExplodedNode *N)
  665. : V(Value), IsSatisfied(false), IsTrackingTurnedOn(false) {
  666. // Check if the visitor is disabled.
  667. SubEngine *Eng = N->getState()->getStateManager().getOwningEngine();
  668. assert(Eng && "Cannot file a bug report without an owning engine");
  669. AnalyzerOptions &Options = Eng->getAnalysisManager().options;
  670. if (!Options.shouldSuppressInlinedDefensiveChecks())
  671. IsSatisfied = true;
  672. assert(N->getState()->isNull(V).isConstrainedTrue() &&
  673. "The visitor only tracks the cases where V is constrained to 0");
  674. }
  675. void SuppressInlineDefensiveChecksVisitor::Profile(FoldingSetNodeID &ID) const {
  676. static int id = 0;
  677. ID.AddPointer(&id);
  678. ID.Add(V);
  679. }
  680. const char *SuppressInlineDefensiveChecksVisitor::getTag() {
  681. return "IDCVisitor";
  682. }
  683. PathDiagnosticPiece *
  684. SuppressInlineDefensiveChecksVisitor::VisitNode(const ExplodedNode *Succ,
  685. const ExplodedNode *Pred,
  686. BugReporterContext &BRC,
  687. BugReport &BR) {
  688. if (IsSatisfied)
  689. return nullptr;
  690. // Start tracking after we see the first state in which the value is null.
  691. if (!IsTrackingTurnedOn)
  692. if (Succ->getState()->isNull(V).isConstrainedTrue())
  693. IsTrackingTurnedOn = true;
  694. if (!IsTrackingTurnedOn)
  695. return nullptr;
  696. // Check if in the previous state it was feasible for this value
  697. // to *not* be null.
  698. if (!Pred->getState()->isNull(V).isConstrainedTrue()) {
  699. IsSatisfied = true;
  700. assert(Succ->getState()->isNull(V).isConstrainedTrue());
  701. // Check if this is inlined defensive checks.
  702. const LocationContext *CurLC =Succ->getLocationContext();
  703. const LocationContext *ReportLC = BR.getErrorNode()->getLocationContext();
  704. if (CurLC != ReportLC && !CurLC->isParentOf(ReportLC))
  705. BR.markInvalid("Suppress IDC", CurLC);
  706. }
  707. return nullptr;
  708. }
  709. static const MemRegion *getLocationRegionIfReference(const Expr *E,
  710. const ExplodedNode *N) {
  711. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
  712. if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
  713. if (!VD->getType()->isReferenceType())
  714. return nullptr;
  715. ProgramStateManager &StateMgr = N->getState()->getStateManager();
  716. MemRegionManager &MRMgr = StateMgr.getRegionManager();
  717. return MRMgr.getVarRegion(VD, N->getLocationContext());
  718. }
  719. }
  720. // FIXME: This does not handle other kinds of null references,
  721. // for example, references from FieldRegions:
  722. // struct Wrapper { int &ref; };
  723. // Wrapper w = { *(int *)0 };
  724. // w.ref = 1;
  725. return nullptr;
  726. }
  727. static const Expr *peelOffOuterExpr(const Expr *Ex,
  728. const ExplodedNode *N) {
  729. Ex = Ex->IgnoreParenCasts();
  730. if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Ex))
  731. return peelOffOuterExpr(EWC->getSubExpr(), N);
  732. if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Ex))
  733. return peelOffOuterExpr(OVE->getSourceExpr(), N);
  734. // Peel off the ternary operator.
  735. if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(Ex)) {
  736. // Find a node where the branching occurred and find out which branch
  737. // we took (true/false) by looking at the ExplodedGraph.
  738. const ExplodedNode *NI = N;
  739. do {
  740. ProgramPoint ProgPoint = NI->getLocation();
  741. if (Optional<BlockEdge> BE = ProgPoint.getAs<BlockEdge>()) {
  742. const CFGBlock *srcBlk = BE->getSrc();
  743. if (const Stmt *term = srcBlk->getTerminator()) {
  744. if (term == CO) {
  745. bool TookTrueBranch = (*(srcBlk->succ_begin()) == BE->getDst());
  746. if (TookTrueBranch)
  747. return peelOffOuterExpr(CO->getTrueExpr(), N);
  748. else
  749. return peelOffOuterExpr(CO->getFalseExpr(), N);
  750. }
  751. }
  752. }
  753. NI = NI->getFirstPred();
  754. } while (NI);
  755. }
  756. return Ex;
  757. }
  758. bool bugreporter::trackNullOrUndefValue(const ExplodedNode *N,
  759. const Stmt *S,
  760. BugReport &report, bool IsArg,
  761. bool EnableNullFPSuppression) {
  762. if (!S || !N)
  763. return false;
  764. if (const Expr *Ex = dyn_cast<Expr>(S)) {
  765. Ex = Ex->IgnoreParenCasts();
  766. const Expr *PeeledEx = peelOffOuterExpr(Ex, N);
  767. if (Ex != PeeledEx)
  768. S = PeeledEx;
  769. }
  770. const Expr *Inner = nullptr;
  771. if (const Expr *Ex = dyn_cast<Expr>(S)) {
  772. Ex = Ex->IgnoreParenCasts();
  773. if (ExplodedGraph::isInterestingLValueExpr(Ex) || CallEvent::isCallStmt(Ex))
  774. Inner = Ex;
  775. }
  776. if (IsArg && !Inner) {
  777. assert(N->getLocation().getAs<CallEnter>() && "Tracking arg but not at call");
  778. } else {
  779. // Walk through nodes until we get one that matches the statement exactly.
  780. // Alternately, if we hit a known lvalue for the statement, we know we've
  781. // gone too far (though we can likely track the lvalue better anyway).
  782. do {
  783. const ProgramPoint &pp = N->getLocation();
  784. if (Optional<StmtPoint> ps = pp.getAs<StmtPoint>()) {
  785. if (ps->getStmt() == S || ps->getStmt() == Inner)
  786. break;
  787. } else if (Optional<CallExitEnd> CEE = pp.getAs<CallExitEnd>()) {
  788. if (CEE->getCalleeContext()->getCallSite() == S ||
  789. CEE->getCalleeContext()->getCallSite() == Inner)
  790. break;
  791. }
  792. N = N->getFirstPred();
  793. } while (N);
  794. if (!N)
  795. return false;
  796. }
  797. ProgramStateRef state = N->getState();
  798. // The message send could be nil due to the receiver being nil.
  799. // At this point in the path, the receiver should be live since we are at the
  800. // message send expr. If it is nil, start tracking it.
  801. if (const Expr *Receiver = NilReceiverBRVisitor::getNilReceiver(S, N))
  802. trackNullOrUndefValue(N, Receiver, report, false, EnableNullFPSuppression);
  803. // See if the expression we're interested refers to a variable.
  804. // If so, we can track both its contents and constraints on its value.
  805. if (Inner && ExplodedGraph::isInterestingLValueExpr(Inner)) {
  806. const MemRegion *R = nullptr;
  807. // Find the ExplodedNode where the lvalue (the value of 'Ex')
  808. // was computed. We need this for getting the location value.
  809. const ExplodedNode *LVNode = N;
  810. while (LVNode) {
  811. if (Optional<PostStmt> P = LVNode->getLocation().getAs<PostStmt>()) {
  812. if (P->getStmt() == Inner)
  813. break;
  814. }
  815. LVNode = LVNode->getFirstPred();
  816. }
  817. assert(LVNode && "Unable to find the lvalue node.");
  818. ProgramStateRef LVState = LVNode->getState();
  819. SVal LVal = LVState->getSVal(Inner, LVNode->getLocationContext());
  820. if (LVState->isNull(LVal).isConstrainedTrue()) {
  821. // In case of C++ references, we want to differentiate between a null
  822. // reference and reference to null pointer.
  823. // If the LVal is null, check if we are dealing with null reference.
  824. // For those, we want to track the location of the reference.
  825. if (const MemRegion *RR = getLocationRegionIfReference(Inner, N))
  826. R = RR;
  827. } else {
  828. R = LVState->getSVal(Inner, LVNode->getLocationContext()).getAsRegion();
  829. // If this is a C++ reference to a null pointer, we are tracking the
  830. // pointer. In additon, we should find the store at which the reference
  831. // got initialized.
  832. if (const MemRegion *RR = getLocationRegionIfReference(Inner, N)) {
  833. if (Optional<KnownSVal> KV = LVal.getAs<KnownSVal>())
  834. report.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
  835. *KV, RR, EnableNullFPSuppression));
  836. }
  837. }
  838. if (R) {
  839. // Mark both the variable region and its contents as interesting.
  840. SVal V = LVState->getRawSVal(loc::MemRegionVal(R));
  841. report.markInteresting(R);
  842. report.markInteresting(V);
  843. report.addVisitor(llvm::make_unique<UndefOrNullArgVisitor>(R));
  844. // If the contents are symbolic, find out when they became null.
  845. if (V.getAsLocSymbol(/*IncludeBaseRegions*/ true))
  846. report.addVisitor(llvm::make_unique<TrackConstraintBRVisitor>(
  847. V.castAs<DefinedSVal>(), false));
  848. // Add visitor, which will suppress inline defensive checks.
  849. if (Optional<DefinedSVal> DV = V.getAs<DefinedSVal>()) {
  850. if (!DV->isZeroConstant() && LVState->isNull(*DV).isConstrainedTrue() &&
  851. EnableNullFPSuppression) {
  852. report.addVisitor(
  853. llvm::make_unique<SuppressInlineDefensiveChecksVisitor>(*DV,
  854. LVNode));
  855. }
  856. }
  857. if (Optional<KnownSVal> KV = V.getAs<KnownSVal>())
  858. report.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
  859. *KV, R, EnableNullFPSuppression));
  860. return true;
  861. }
  862. }
  863. // If the expression is not an "lvalue expression", we can still
  864. // track the constraints on its contents.
  865. SVal V = state->getSValAsScalarOrLoc(S, N->getLocationContext());
  866. // If the value came from an inlined function call, we should at least make
  867. // sure that function isn't pruned in our output.
  868. if (const Expr *E = dyn_cast<Expr>(S))
  869. S = E->IgnoreParenCasts();
  870. ReturnVisitor::addVisitorIfNecessary(N, S, report, EnableNullFPSuppression);
  871. // Uncomment this to find cases where we aren't properly getting the
  872. // base value that was dereferenced.
  873. // assert(!V.isUnknownOrUndef());
  874. // Is it a symbolic value?
  875. if (Optional<loc::MemRegionVal> L = V.getAs<loc::MemRegionVal>()) {
  876. // At this point we are dealing with the region's LValue.
  877. // However, if the rvalue is a symbolic region, we should track it as well.
  878. // Try to use the correct type when looking up the value.
  879. SVal RVal;
  880. if (const Expr *E = dyn_cast<Expr>(S))
  881. RVal = state->getRawSVal(L.getValue(), E->getType());
  882. else
  883. RVal = state->getSVal(L->getRegion());
  884. const MemRegion *RegionRVal = RVal.getAsRegion();
  885. report.addVisitor(llvm::make_unique<UndefOrNullArgVisitor>(L->getRegion()));
  886. if (RegionRVal && isa<SymbolicRegion>(RegionRVal)) {
  887. report.markInteresting(RegionRVal);
  888. report.addVisitor(llvm::make_unique<TrackConstraintBRVisitor>(
  889. loc::MemRegionVal(RegionRVal), false));
  890. }
  891. }
  892. return true;
  893. }
  894. const Expr *NilReceiverBRVisitor::getNilReceiver(const Stmt *S,
  895. const ExplodedNode *N) {
  896. const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S);
  897. if (!ME)
  898. return nullptr;
  899. if (const Expr *Receiver = ME->getInstanceReceiver()) {
  900. ProgramStateRef state = N->getState();
  901. SVal V = state->getSVal(Receiver, N->getLocationContext());
  902. if (state->isNull(V).isConstrainedTrue())
  903. return Receiver;
  904. }
  905. return nullptr;
  906. }
  907. PathDiagnosticPiece *NilReceiverBRVisitor::VisitNode(const ExplodedNode *N,
  908. const ExplodedNode *PrevN,
  909. BugReporterContext &BRC,
  910. BugReport &BR) {
  911. Optional<PreStmt> P = N->getLocationAs<PreStmt>();
  912. if (!P)
  913. return nullptr;
  914. const Stmt *S = P->getStmt();
  915. const Expr *Receiver = getNilReceiver(S, N);
  916. if (!Receiver)
  917. return nullptr;
  918. llvm::SmallString<256> Buf;
  919. llvm::raw_svector_ostream OS(Buf);
  920. if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
  921. OS << "'";
  922. ME->getSelector().print(OS);
  923. OS << "' not called";
  924. }
  925. else {
  926. OS << "No method is called";
  927. }
  928. OS << " because the receiver is nil";
  929. // The receiver was nil, and hence the method was skipped.
  930. // Register a BugReporterVisitor to issue a message telling us how
  931. // the receiver was null.
  932. bugreporter::trackNullOrUndefValue(N, Receiver, BR, /*IsArg*/ false,
  933. /*EnableNullFPSuppression*/ false);
  934. // Issue a message saying that the method was skipped.
  935. PathDiagnosticLocation L(Receiver, BRC.getSourceManager(),
  936. N->getLocationContext());
  937. return new PathDiagnosticEventPiece(L, OS.str());
  938. }
  939. // Registers every VarDecl inside a Stmt with a last store visitor.
  940. void FindLastStoreBRVisitor::registerStatementVarDecls(BugReport &BR,
  941. const Stmt *S,
  942. bool EnableNullFPSuppression) {
  943. const ExplodedNode *N = BR.getErrorNode();
  944. std::deque<const Stmt *> WorkList;
  945. WorkList.push_back(S);
  946. while (!WorkList.empty()) {
  947. const Stmt *Head = WorkList.front();
  948. WorkList.pop_front();
  949. ProgramStateRef state = N->getState();
  950. ProgramStateManager &StateMgr = state->getStateManager();
  951. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Head)) {
  952. if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
  953. const VarRegion *R =
  954. StateMgr.getRegionManager().getVarRegion(VD, N->getLocationContext());
  955. // What did we load?
  956. SVal V = state->getSVal(S, N->getLocationContext());
  957. if (V.getAs<loc::ConcreteInt>() || V.getAs<nonloc::ConcreteInt>()) {
  958. // Register a new visitor with the BugReport.
  959. BR.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
  960. V.castAs<KnownSVal>(), R, EnableNullFPSuppression));
  961. }
  962. }
  963. }
  964. for (Stmt::const_child_iterator I = Head->child_begin();
  965. I != Head->child_end(); ++I)
  966. WorkList.push_back(*I);
  967. }
  968. }
  969. //===----------------------------------------------------------------------===//
  970. // Visitor that tries to report interesting diagnostics from conditions.
  971. //===----------------------------------------------------------------------===//
  972. /// Return the tag associated with this visitor. This tag will be used
  973. /// to make all PathDiagnosticPieces created by this visitor.
  974. const char *ConditionBRVisitor::getTag() {
  975. return "ConditionBRVisitor";
  976. }
  977. PathDiagnosticPiece *ConditionBRVisitor::VisitNode(const ExplodedNode *N,
  978. const ExplodedNode *Prev,
  979. BugReporterContext &BRC,
  980. BugReport &BR) {
  981. PathDiagnosticPiece *piece = VisitNodeImpl(N, Prev, BRC, BR);
  982. if (piece) {
  983. piece->setTag(getTag());
  984. if (PathDiagnosticEventPiece *ev=dyn_cast<PathDiagnosticEventPiece>(piece))
  985. ev->setPrunable(true, /* override */ false);
  986. }
  987. return piece;
  988. }
  989. PathDiagnosticPiece *ConditionBRVisitor::VisitNodeImpl(const ExplodedNode *N,
  990. const ExplodedNode *Prev,
  991. BugReporterContext &BRC,
  992. BugReport &BR) {
  993. ProgramPoint progPoint = N->getLocation();
  994. ProgramStateRef CurrentState = N->getState();
  995. ProgramStateRef PrevState = Prev->getState();
  996. // Compare the GDMs of the state, because that is where constraints
  997. // are managed. Note that ensure that we only look at nodes that
  998. // were generated by the analyzer engine proper, not checkers.
  999. if (CurrentState->getGDM().getRoot() ==
  1000. PrevState->getGDM().getRoot())
  1001. return nullptr;
  1002. // If an assumption was made on a branch, it should be caught
  1003. // here by looking at the state transition.
  1004. if (Optional<BlockEdge> BE = progPoint.getAs<BlockEdge>()) {
  1005. const CFGBlock *srcBlk = BE->getSrc();
  1006. if (const Stmt *term = srcBlk->getTerminator())
  1007. return VisitTerminator(term, N, srcBlk, BE->getDst(), BR, BRC);
  1008. return nullptr;
  1009. }
  1010. if (Optional<PostStmt> PS = progPoint.getAs<PostStmt>()) {
  1011. // FIXME: Assuming that BugReporter is a GRBugReporter is a layering
  1012. // violation.
  1013. const std::pair<const ProgramPointTag *, const ProgramPointTag *> &tags =
  1014. cast<GRBugReporter>(BRC.getBugReporter()).
  1015. getEngine().geteagerlyAssumeBinOpBifurcationTags();
  1016. const ProgramPointTag *tag = PS->getTag();
  1017. if (tag == tags.first)
  1018. return VisitTrueTest(cast<Expr>(PS->getStmt()), true,
  1019. BRC, BR, N);
  1020. if (tag == tags.second)
  1021. return VisitTrueTest(cast<Expr>(PS->getStmt()), false,
  1022. BRC, BR, N);
  1023. return nullptr;
  1024. }
  1025. return nullptr;
  1026. }
  1027. PathDiagnosticPiece *
  1028. ConditionBRVisitor::VisitTerminator(const Stmt *Term,
  1029. const ExplodedNode *N,
  1030. const CFGBlock *srcBlk,
  1031. const CFGBlock *dstBlk,
  1032. BugReport &R,
  1033. BugReporterContext &BRC) {
  1034. const Expr *Cond = nullptr;
  1035. switch (Term->getStmtClass()) {
  1036. default:
  1037. return nullptr;
  1038. case Stmt::IfStmtClass:
  1039. Cond = cast<IfStmt>(Term)->getCond();
  1040. break;
  1041. case Stmt::ConditionalOperatorClass:
  1042. Cond = cast<ConditionalOperator>(Term)->getCond();
  1043. break;
  1044. }
  1045. assert(Cond);
  1046. assert(srcBlk->succ_size() == 2);
  1047. const bool tookTrue = *(srcBlk->succ_begin()) == dstBlk;
  1048. return VisitTrueTest(Cond, tookTrue, BRC, R, N);
  1049. }
  1050. PathDiagnosticPiece *
  1051. ConditionBRVisitor::VisitTrueTest(const Expr *Cond,
  1052. bool tookTrue,
  1053. BugReporterContext &BRC,
  1054. BugReport &R,
  1055. const ExplodedNode *N) {
  1056. const Expr *Ex = Cond;
  1057. while (true) {
  1058. Ex = Ex->IgnoreParenCasts();
  1059. switch (Ex->getStmtClass()) {
  1060. default:
  1061. return nullptr;
  1062. case Stmt::BinaryOperatorClass:
  1063. return VisitTrueTest(Cond, cast<BinaryOperator>(Ex), tookTrue, BRC,
  1064. R, N);
  1065. case Stmt::DeclRefExprClass:
  1066. return VisitTrueTest(Cond, cast<DeclRefExpr>(Ex), tookTrue, BRC,
  1067. R, N);
  1068. case Stmt::UnaryOperatorClass: {
  1069. const UnaryOperator *UO = cast<UnaryOperator>(Ex);
  1070. if (UO->getOpcode() == UO_LNot) {
  1071. tookTrue = !tookTrue;
  1072. Ex = UO->getSubExpr();
  1073. continue;
  1074. }
  1075. return nullptr;
  1076. }
  1077. }
  1078. }
  1079. }
  1080. bool ConditionBRVisitor::patternMatch(const Expr *Ex, raw_ostream &Out,
  1081. BugReporterContext &BRC,
  1082. BugReport &report,
  1083. const ExplodedNode *N,
  1084. Optional<bool> &prunable) {
  1085. const Expr *OriginalExpr = Ex;
  1086. Ex = Ex->IgnoreParenCasts();
  1087. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Ex)) {
  1088. const bool quotes = isa<VarDecl>(DR->getDecl());
  1089. if (quotes) {
  1090. Out << '\'';
  1091. const LocationContext *LCtx = N->getLocationContext();
  1092. const ProgramState *state = N->getState().get();
  1093. if (const MemRegion *R = state->getLValue(cast<VarDecl>(DR->getDecl()),
  1094. LCtx).getAsRegion()) {
  1095. if (report.isInteresting(R))
  1096. prunable = false;
  1097. else {
  1098. const ProgramState *state = N->getState().get();
  1099. SVal V = state->getSVal(R);
  1100. if (report.isInteresting(V))
  1101. prunable = false;
  1102. }
  1103. }
  1104. }
  1105. Out << DR->getDecl()->getDeclName().getAsString();
  1106. if (quotes)
  1107. Out << '\'';
  1108. return quotes;
  1109. }
  1110. if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(Ex)) {
  1111. QualType OriginalTy = OriginalExpr->getType();
  1112. if (OriginalTy->isPointerType()) {
  1113. if (IL->getValue() == 0) {
  1114. Out << "null";
  1115. return false;
  1116. }
  1117. }
  1118. else if (OriginalTy->isObjCObjectPointerType()) {
  1119. if (IL->getValue() == 0) {
  1120. Out << "nil";
  1121. return false;
  1122. }
  1123. }
  1124. Out << IL->getValue();
  1125. return false;
  1126. }
  1127. return false;
  1128. }
  1129. PathDiagnosticPiece *
  1130. ConditionBRVisitor::VisitTrueTest(const Expr *Cond,
  1131. const BinaryOperator *BExpr,
  1132. const bool tookTrue,
  1133. BugReporterContext &BRC,
  1134. BugReport &R,
  1135. const ExplodedNode *N) {
  1136. bool shouldInvert = false;
  1137. Optional<bool> shouldPrune;
  1138. SmallString<128> LhsString, RhsString;
  1139. {
  1140. llvm::raw_svector_ostream OutLHS(LhsString), OutRHS(RhsString);
  1141. const bool isVarLHS = patternMatch(BExpr->getLHS(), OutLHS, BRC, R, N,
  1142. shouldPrune);
  1143. const bool isVarRHS = patternMatch(BExpr->getRHS(), OutRHS, BRC, R, N,
  1144. shouldPrune);
  1145. shouldInvert = !isVarLHS && isVarRHS;
  1146. }
  1147. BinaryOperator::Opcode Op = BExpr->getOpcode();
  1148. if (BinaryOperator::isAssignmentOp(Op)) {
  1149. // For assignment operators, all that we care about is that the LHS
  1150. // evaluates to "true" or "false".
  1151. return VisitConditionVariable(LhsString, BExpr->getLHS(), tookTrue,
  1152. BRC, R, N);
  1153. }
  1154. // For non-assignment operations, we require that we can understand
  1155. // both the LHS and RHS.
  1156. if (LhsString.empty() || RhsString.empty() ||
  1157. !BinaryOperator::isComparisonOp(Op))
  1158. return nullptr;
  1159. // Should we invert the strings if the LHS is not a variable name?
  1160. SmallString<256> buf;
  1161. llvm::raw_svector_ostream Out(buf);
  1162. Out << "Assuming " << (shouldInvert ? RhsString : LhsString) << " is ";
  1163. // Do we need to invert the opcode?
  1164. if (shouldInvert)
  1165. switch (Op) {
  1166. default: break;
  1167. case BO_LT: Op = BO_GT; break;
  1168. case BO_GT: Op = BO_LT; break;
  1169. case BO_LE: Op = BO_GE; break;
  1170. case BO_GE: Op = BO_LE; break;
  1171. }
  1172. if (!tookTrue)
  1173. switch (Op) {
  1174. case BO_EQ: Op = BO_NE; break;
  1175. case BO_NE: Op = BO_EQ; break;
  1176. case BO_LT: Op = BO_GE; break;
  1177. case BO_GT: Op = BO_LE; break;
  1178. case BO_LE: Op = BO_GT; break;
  1179. case BO_GE: Op = BO_LT; break;
  1180. default:
  1181. return nullptr;
  1182. }
  1183. switch (Op) {
  1184. case BO_EQ:
  1185. Out << "equal to ";
  1186. break;
  1187. case BO_NE:
  1188. Out << "not equal to ";
  1189. break;
  1190. default:
  1191. Out << BinaryOperator::getOpcodeStr(Op) << ' ';
  1192. break;
  1193. }
  1194. Out << (shouldInvert ? LhsString : RhsString);
  1195. const LocationContext *LCtx = N->getLocationContext();
  1196. PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
  1197. PathDiagnosticEventPiece *event =
  1198. new PathDiagnosticEventPiece(Loc, Out.str());
  1199. if (shouldPrune.hasValue())
  1200. event->setPrunable(shouldPrune.getValue());
  1201. return event;
  1202. }
  1203. PathDiagnosticPiece *
  1204. ConditionBRVisitor::VisitConditionVariable(StringRef LhsString,
  1205. const Expr *CondVarExpr,
  1206. const bool tookTrue,
  1207. BugReporterContext &BRC,
  1208. BugReport &report,
  1209. const ExplodedNode *N) {
  1210. // FIXME: If there's already a constraint tracker for this variable,
  1211. // we shouldn't emit anything here (c.f. the double note in
  1212. // test/Analysis/inlining/path-notes.c)
  1213. SmallString<256> buf;
  1214. llvm::raw_svector_ostream Out(buf);
  1215. Out << "Assuming " << LhsString << " is ";
  1216. QualType Ty = CondVarExpr->getType();
  1217. if (Ty->isPointerType())
  1218. Out << (tookTrue ? "not null" : "null");
  1219. else if (Ty->isObjCObjectPointerType())
  1220. Out << (tookTrue ? "not nil" : "nil");
  1221. else if (Ty->isBooleanType())
  1222. Out << (tookTrue ? "true" : "false");
  1223. else if (Ty->isIntegralOrEnumerationType())
  1224. Out << (tookTrue ? "non-zero" : "zero");
  1225. else
  1226. return nullptr;
  1227. const LocationContext *LCtx = N->getLocationContext();
  1228. PathDiagnosticLocation Loc(CondVarExpr, BRC.getSourceManager(), LCtx);
  1229. PathDiagnosticEventPiece *event =
  1230. new PathDiagnosticEventPiece(Loc, Out.str());
  1231. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(CondVarExpr)) {
  1232. if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
  1233. const ProgramState *state = N->getState().get();
  1234. if (const MemRegion *R = state->getLValue(VD, LCtx).getAsRegion()) {
  1235. if (report.isInteresting(R))
  1236. event->setPrunable(false);
  1237. }
  1238. }
  1239. }
  1240. return event;
  1241. }
  1242. PathDiagnosticPiece *
  1243. ConditionBRVisitor::VisitTrueTest(const Expr *Cond,
  1244. const DeclRefExpr *DR,
  1245. const bool tookTrue,
  1246. BugReporterContext &BRC,
  1247. BugReport &report,
  1248. const ExplodedNode *N) {
  1249. const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
  1250. if (!VD)
  1251. return nullptr;
  1252. SmallString<256> Buf;
  1253. llvm::raw_svector_ostream Out(Buf);
  1254. Out << "Assuming '" << VD->getDeclName() << "' is ";
  1255. QualType VDTy = VD->getType();
  1256. if (VDTy->isPointerType())
  1257. Out << (tookTrue ? "non-null" : "null");
  1258. else if (VDTy->isObjCObjectPointerType())
  1259. Out << (tookTrue ? "non-nil" : "nil");
  1260. else if (VDTy->isScalarType())
  1261. Out << (tookTrue ? "not equal to 0" : "0");
  1262. else
  1263. return nullptr;
  1264. const LocationContext *LCtx = N->getLocationContext();
  1265. PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
  1266. PathDiagnosticEventPiece *event =
  1267. new PathDiagnosticEventPiece(Loc, Out.str());
  1268. const ProgramState *state = N->getState().get();
  1269. if (const MemRegion *R = state->getLValue(VD, LCtx).getAsRegion()) {
  1270. if (report.isInteresting(R))
  1271. event->setPrunable(false);
  1272. else {
  1273. SVal V = state->getSVal(R);
  1274. if (report.isInteresting(V))
  1275. event->setPrunable(false);
  1276. }
  1277. }
  1278. return event;
  1279. }
  1280. // FIXME: Copied from ExprEngineCallAndReturn.cpp.
  1281. static bool isInStdNamespace(const Decl *D) {
  1282. const DeclContext *DC = D->getDeclContext()->getEnclosingNamespaceContext();
  1283. const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC);
  1284. if (!ND)
  1285. return false;
  1286. while (const NamespaceDecl *Parent = dyn_cast<NamespaceDecl>(ND->getParent()))
  1287. ND = Parent;
  1288. return ND->isStdNamespace();
  1289. }
  1290. std::unique_ptr<PathDiagnosticPiece>
  1291. LikelyFalsePositiveSuppressionBRVisitor::getEndPath(BugReporterContext &BRC,
  1292. const ExplodedNode *N,
  1293. BugReport &BR) {
  1294. // Here we suppress false positives coming from system headers. This list is
  1295. // based on known issues.
  1296. ExprEngine &Eng = BRC.getBugReporter().getEngine();
  1297. AnalyzerOptions &Options = Eng.getAnalysisManager().options;
  1298. const Decl *D = N->getLocationContext()->getDecl();
  1299. if (isInStdNamespace(D)) {
  1300. // Skip reports within the 'std' namespace. Although these can sometimes be
  1301. // the user's fault, we currently don't report them very well, and
  1302. // Note that this will not help for any other data structure libraries, like
  1303. // TR1, Boost, or llvm/ADT.
  1304. if (Options.shouldSuppressFromCXXStandardLibrary()) {
  1305. BR.markInvalid(getTag(), nullptr);
  1306. return nullptr;
  1307. } else {
  1308. // If the complete 'std' suppression is not enabled, suppress reports
  1309. // from the 'std' namespace that are known to produce false positives.
  1310. // The analyzer issues a false use-after-free when std::list::pop_front
  1311. // or std::list::pop_back are called multiple times because we cannot
  1312. // reason about the internal invariants of the datastructure.
  1313. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
  1314. const CXXRecordDecl *CD = MD->getParent();
  1315. if (CD->getName() == "list") {
  1316. BR.markInvalid(getTag(), nullptr);
  1317. return nullptr;
  1318. }
  1319. }
  1320. // The analyzer issues a false positive on
  1321. // std::basic_string<uint8_t> v; v.push_back(1);
  1322. // and
  1323. // std::u16string s; s += u'a';
  1324. // because we cannot reason about the internal invariants of the
  1325. // datastructure.
  1326. for (const LocationContext *LCtx = N->getLocationContext(); LCtx;
  1327. LCtx = LCtx->getParent()) {
  1328. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LCtx->getDecl());
  1329. if (!MD)
  1330. continue;
  1331. const CXXRecordDecl *CD = MD->getParent();
  1332. if (CD->getName() == "basic_string") {
  1333. BR.markInvalid(getTag(), nullptr);
  1334. return nullptr;
  1335. }
  1336. }
  1337. }
  1338. }
  1339. // Skip reports within the sys/queue.h macros as we do not have the ability to
  1340. // reason about data structure shapes.
  1341. SourceManager &SM = BRC.getSourceManager();
  1342. FullSourceLoc Loc = BR.getLocation(SM).asLocation();
  1343. while (Loc.isMacroID()) {
  1344. Loc = Loc.getSpellingLoc();
  1345. if (SM.getFilename(Loc).endswith("sys/queue.h")) {
  1346. BR.markInvalid(getTag(), nullptr);
  1347. return nullptr;
  1348. }
  1349. }
  1350. return nullptr;
  1351. }
  1352. PathDiagnosticPiece *
  1353. UndefOrNullArgVisitor::VisitNode(const ExplodedNode *N,
  1354. const ExplodedNode *PrevN,
  1355. BugReporterContext &BRC,
  1356. BugReport &BR) {
  1357. ProgramStateRef State = N->getState();
  1358. ProgramPoint ProgLoc = N->getLocation();
  1359. // We are only interested in visiting CallEnter nodes.
  1360. Optional<CallEnter> CEnter = ProgLoc.getAs<CallEnter>();
  1361. if (!CEnter)
  1362. return nullptr;
  1363. // Check if one of the arguments is the region the visitor is tracking.
  1364. CallEventManager &CEMgr = BRC.getStateManager().getCallEventManager();
  1365. CallEventRef<> Call = CEMgr.getCaller(CEnter->getCalleeContext(), State);
  1366. unsigned Idx = 0;
  1367. ArrayRef<ParmVarDecl*> parms = Call->parameters();
  1368. for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
  1369. I != E; ++I, ++Idx) {
  1370. const MemRegion *ArgReg = Call->getArgSVal(Idx).getAsRegion();
  1371. // Are we tracking the argument or its subregion?
  1372. if ( !ArgReg || (ArgReg != R && !R->isSubRegionOf(ArgReg->StripCasts())))
  1373. continue;
  1374. // Check the function parameter type.
  1375. const ParmVarDecl *ParamDecl = *I;
  1376. assert(ParamDecl && "Formal parameter has no decl?");
  1377. QualType T = ParamDecl->getType();
  1378. if (!(T->isAnyPointerType() || T->isReferenceType())) {
  1379. // Function can only change the value passed in by address.
  1380. continue;
  1381. }
  1382. // If it is a const pointer value, the function does not intend to
  1383. // change the value.
  1384. if (T->getPointeeType().isConstQualified())
  1385. continue;
  1386. // Mark the call site (LocationContext) as interesting if the value of the
  1387. // argument is undefined or '0'/'NULL'.
  1388. SVal BoundVal = State->getSVal(R);
  1389. if (BoundVal.isUndef() || BoundVal.isZeroConstant()) {
  1390. BR.markInteresting(CEnter->getCalleeContext());
  1391. return nullptr;
  1392. }
  1393. }
  1394. return nullptr;
  1395. }