BugReporterVisitors.cpp 66 KB

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