BugReporterVisitors.cpp 67 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920
  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 = Node->getSVal(S);
  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. /// Show diagnostics for initializing or declaring a region \p R with a bad value.
  411. void showBRDiagnostics(const char *action,
  412. llvm::raw_svector_ostream& os,
  413. const MemRegion *R,
  414. SVal V,
  415. const DeclStmt *DS) {
  416. if (R->canPrintPretty()) {
  417. R->printPretty(os);
  418. os << " ";
  419. }
  420. if (V.getAs<loc::ConcreteInt>()) {
  421. bool b = false;
  422. if (R->isBoundable()) {
  423. if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R)) {
  424. if (TR->getValueType()->isObjCObjectPointerType()) {
  425. os << action << "nil";
  426. b = true;
  427. }
  428. }
  429. }
  430. if (!b)
  431. os << action << "a null pointer value";
  432. } else if (auto CVal = V.getAs<nonloc::ConcreteInt>()) {
  433. os << action << CVal->getValue();
  434. } else if (DS) {
  435. if (V.isUndef()) {
  436. if (isa<VarRegion>(R)) {
  437. const VarDecl *VD = cast<VarDecl>(DS->getSingleDecl());
  438. if (VD->getInit()) {
  439. os << (R->canPrintPretty() ? "initialized" : "Initializing")
  440. << " to a garbage value";
  441. } else {
  442. os << (R->canPrintPretty() ? "declared" : "Declaring")
  443. << " without an initial value";
  444. }
  445. }
  446. } else {
  447. os << (R->canPrintPretty() ? "initialized" : "Initialized")
  448. << " here";
  449. }
  450. }
  451. }
  452. /// Display diagnostics for passing bad region as a parameter.
  453. static void showBRParamDiagnostics(llvm::raw_svector_ostream& os,
  454. const VarRegion *VR,
  455. SVal V) {
  456. const auto *Param = cast<ParmVarDecl>(VR->getDecl());
  457. os << "Passing ";
  458. if (V.getAs<loc::ConcreteInt>()) {
  459. if (Param->getType()->isObjCObjectPointerType())
  460. os << "nil object reference";
  461. else
  462. os << "null pointer value";
  463. } else if (V.isUndef()) {
  464. os << "uninitialized value";
  465. } else if (auto CI = V.getAs<nonloc::ConcreteInt>()) {
  466. os << "the value " << CI->getValue();
  467. } else {
  468. os << "value";
  469. }
  470. // Printed parameter indexes are 1-based, not 0-based.
  471. unsigned Idx = Param->getFunctionScopeIndex() + 1;
  472. os << " via " << Idx << llvm::getOrdinalSuffix(Idx) << " parameter";
  473. if (VR->canPrintPretty()) {
  474. os << " ";
  475. VR->printPretty(os);
  476. }
  477. }
  478. /// Show default diagnostics for storing bad region.
  479. static void showBRDefaultDiagnostics(llvm::raw_svector_ostream& os,
  480. const MemRegion *R,
  481. SVal V) {
  482. if (V.getAs<loc::ConcreteInt>()) {
  483. bool b = false;
  484. if (R->isBoundable()) {
  485. if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R)) {
  486. if (TR->getValueType()->isObjCObjectPointerType()) {
  487. os << "nil object reference stored";
  488. b = true;
  489. }
  490. }
  491. }
  492. if (!b) {
  493. if (R->canPrintPretty())
  494. os << "Null pointer value stored";
  495. else
  496. os << "Storing null pointer value";
  497. }
  498. } else if (V.isUndef()) {
  499. if (R->canPrintPretty())
  500. os << "Uninitialized value stored";
  501. else
  502. os << "Storing uninitialized value";
  503. } else if (auto CV = V.getAs<nonloc::ConcreteInt>()) {
  504. if (R->canPrintPretty())
  505. os << "The value " << CV->getValue() << " is assigned";
  506. else
  507. os << "Assigning " << CV->getValue();
  508. } else {
  509. if (R->canPrintPretty())
  510. os << "Value assigned";
  511. else
  512. os << "Assigning value";
  513. }
  514. if (R->canPrintPretty()) {
  515. os << " to ";
  516. R->printPretty(os);
  517. }
  518. }
  519. std::shared_ptr<PathDiagnosticPiece>
  520. FindLastStoreBRVisitor::VisitNode(const ExplodedNode *Succ,
  521. const ExplodedNode *Pred,
  522. BugReporterContext &BRC, BugReport &BR) {
  523. if (Satisfied)
  524. return nullptr;
  525. const ExplodedNode *StoreSite = nullptr;
  526. const Expr *InitE = nullptr;
  527. bool IsParam = false;
  528. // First see if we reached the declaration of the region.
  529. if (const VarRegion *VR = dyn_cast<VarRegion>(R)) {
  530. if (isInitializationOfVar(Pred, VR)) {
  531. StoreSite = Pred;
  532. InitE = VR->getDecl()->getInit();
  533. }
  534. }
  535. // If this is a post initializer expression, initializing the region, we
  536. // should track the initializer expression.
  537. if (Optional<PostInitializer> PIP = Pred->getLocationAs<PostInitializer>()) {
  538. const MemRegion *FieldReg = (const MemRegion *)PIP->getLocationValue();
  539. if (FieldReg && FieldReg == R) {
  540. StoreSite = Pred;
  541. InitE = PIP->getInitializer()->getInit();
  542. }
  543. }
  544. // Otherwise, see if this is the store site:
  545. // (1) Succ has this binding and Pred does not, i.e. this is
  546. // where the binding first occurred.
  547. // (2) Succ has this binding and is a PostStore node for this region, i.e.
  548. // the same binding was re-assigned here.
  549. if (!StoreSite) {
  550. if (Succ->getState()->getSVal(R) != V)
  551. return nullptr;
  552. if (Pred->getState()->getSVal(R) == V) {
  553. Optional<PostStore> PS = Succ->getLocationAs<PostStore>();
  554. if (!PS || PS->getLocationValue() != R)
  555. return nullptr;
  556. }
  557. StoreSite = Succ;
  558. // If this is an assignment expression, we can track the value
  559. // being assigned.
  560. if (Optional<PostStmt> P = Succ->getLocationAs<PostStmt>())
  561. if (const BinaryOperator *BO = P->getStmtAs<BinaryOperator>())
  562. if (BO->isAssignmentOp())
  563. InitE = BO->getRHS();
  564. // If this is a call entry, the variable should be a parameter.
  565. // FIXME: Handle CXXThisRegion as well. (This is not a priority because
  566. // 'this' should never be NULL, but this visitor isn't just for NULL and
  567. // UndefinedVal.)
  568. if (Optional<CallEnter> CE = Succ->getLocationAs<CallEnter>()) {
  569. if (const VarRegion *VR = dyn_cast<VarRegion>(R)) {
  570. const ParmVarDecl *Param = cast<ParmVarDecl>(VR->getDecl());
  571. ProgramStateManager &StateMgr = BRC.getStateManager();
  572. CallEventManager &CallMgr = StateMgr.getCallEventManager();
  573. CallEventRef<> Call = CallMgr.getCaller(CE->getCalleeContext(),
  574. Succ->getState());
  575. InitE = Call->getArgExpr(Param->getFunctionScopeIndex());
  576. IsParam = true;
  577. }
  578. }
  579. // If this is a CXXTempObjectRegion, the Expr responsible for its creation
  580. // is wrapped inside of it.
  581. if (const CXXTempObjectRegion *TmpR = dyn_cast<CXXTempObjectRegion>(R))
  582. InitE = TmpR->getExpr();
  583. }
  584. if (!StoreSite)
  585. return nullptr;
  586. Satisfied = true;
  587. // If we have an expression that provided the value, try to track where it
  588. // came from.
  589. if (InitE) {
  590. if (V.isUndef() ||
  591. V.getAs<loc::ConcreteInt>() || V.getAs<nonloc::ConcreteInt>()) {
  592. if (!IsParam)
  593. InitE = InitE->IgnoreParenCasts();
  594. bugreporter::trackNullOrUndefValue(StoreSite, InitE, BR, IsParam,
  595. EnableNullFPSuppression);
  596. } else {
  597. ReturnVisitor::addVisitorIfNecessary(StoreSite, InitE->IgnoreParenCasts(),
  598. BR, EnableNullFPSuppression);
  599. }
  600. }
  601. // Okay, we've found the binding. Emit an appropriate message.
  602. SmallString<256> sbuf;
  603. llvm::raw_svector_ostream os(sbuf);
  604. if (Optional<PostStmt> PS = StoreSite->getLocationAs<PostStmt>()) {
  605. const Stmt *S = PS->getStmt();
  606. const char *action = nullptr;
  607. const DeclStmt *DS = dyn_cast<DeclStmt>(S);
  608. const VarRegion *VR = dyn_cast<VarRegion>(R);
  609. if (DS) {
  610. action = R->canPrintPretty() ? "initialized to " :
  611. "Initializing to ";
  612. } else if (isa<BlockExpr>(S)) {
  613. action = R->canPrintPretty() ? "captured by block as " :
  614. "Captured by block as ";
  615. if (VR) {
  616. // See if we can get the BlockVarRegion.
  617. ProgramStateRef State = StoreSite->getState();
  618. SVal V = StoreSite->getSVal(S);
  619. if (const BlockDataRegion *BDR =
  620. dyn_cast_or_null<BlockDataRegion>(V.getAsRegion())) {
  621. if (const VarRegion *OriginalR = BDR->getOriginalRegion(VR)) {
  622. if (Optional<KnownSVal> KV =
  623. State->getSVal(OriginalR).getAs<KnownSVal>())
  624. BR.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
  625. *KV, OriginalR, EnableNullFPSuppression));
  626. }
  627. }
  628. }
  629. }
  630. if (action)
  631. showBRDiagnostics(action, os, R, V, DS);
  632. } else if (StoreSite->getLocation().getAs<CallEnter>()) {
  633. if (const VarRegion *VR = dyn_cast<VarRegion>(R))
  634. showBRParamDiagnostics(os, VR, V);
  635. }
  636. if (os.str().empty())
  637. showBRDefaultDiagnostics(os, R, V);
  638. // Construct a new PathDiagnosticPiece.
  639. ProgramPoint P = StoreSite->getLocation();
  640. PathDiagnosticLocation L;
  641. if (P.getAs<CallEnter>() && InitE)
  642. L = PathDiagnosticLocation(InitE, BRC.getSourceManager(),
  643. P.getLocationContext());
  644. if (!L.isValid() || !L.asLocation().isValid())
  645. L = PathDiagnosticLocation::create(P, BRC.getSourceManager());
  646. if (!L.isValid() || !L.asLocation().isValid())
  647. return nullptr;
  648. return std::make_shared<PathDiagnosticEventPiece>(L, os.str());
  649. }
  650. void TrackConstraintBRVisitor::Profile(llvm::FoldingSetNodeID &ID) const {
  651. static int tag = 0;
  652. ID.AddPointer(&tag);
  653. ID.AddBoolean(Assumption);
  654. ID.Add(Constraint);
  655. }
  656. /// Return the tag associated with this visitor. This tag will be used
  657. /// to make all PathDiagnosticPieces created by this visitor.
  658. const char *TrackConstraintBRVisitor::getTag() {
  659. return "TrackConstraintBRVisitor";
  660. }
  661. bool TrackConstraintBRVisitor::isUnderconstrained(const ExplodedNode *N) const {
  662. if (IsZeroCheck)
  663. return N->getState()->isNull(Constraint).isUnderconstrained();
  664. return (bool)N->getState()->assume(Constraint, !Assumption);
  665. }
  666. std::shared_ptr<PathDiagnosticPiece>
  667. TrackConstraintBRVisitor::VisitNode(const ExplodedNode *N,
  668. const ExplodedNode *PrevN,
  669. BugReporterContext &BRC, BugReport &BR) {
  670. if (IsSatisfied)
  671. return nullptr;
  672. // Start tracking after we see the first state in which the value is
  673. // constrained.
  674. if (!IsTrackingTurnedOn)
  675. if (!isUnderconstrained(N))
  676. IsTrackingTurnedOn = true;
  677. if (!IsTrackingTurnedOn)
  678. return nullptr;
  679. // Check if in the previous state it was feasible for this constraint
  680. // to *not* be true.
  681. if (isUnderconstrained(PrevN)) {
  682. IsSatisfied = true;
  683. // As a sanity check, make sure that the negation of the constraint
  684. // was infeasible in the current state. If it is feasible, we somehow
  685. // missed the transition point.
  686. assert(!isUnderconstrained(N));
  687. // We found the transition point for the constraint. We now need to
  688. // pretty-print the constraint. (work-in-progress)
  689. SmallString<64> sbuf;
  690. llvm::raw_svector_ostream os(sbuf);
  691. if (Constraint.getAs<Loc>()) {
  692. os << "Assuming pointer value is ";
  693. os << (Assumption ? "non-null" : "null");
  694. }
  695. if (os.str().empty())
  696. return nullptr;
  697. // Construct a new PathDiagnosticPiece.
  698. ProgramPoint P = N->getLocation();
  699. PathDiagnosticLocation L =
  700. PathDiagnosticLocation::create(P, BRC.getSourceManager());
  701. if (!L.isValid())
  702. return nullptr;
  703. auto X = std::make_shared<PathDiagnosticEventPiece>(L, os.str());
  704. X->setTag(getTag());
  705. return std::move(X);
  706. }
  707. return nullptr;
  708. }
  709. SuppressInlineDefensiveChecksVisitor::
  710. SuppressInlineDefensiveChecksVisitor(DefinedSVal Value, const ExplodedNode *N)
  711. : V(Value), IsSatisfied(false), IsTrackingTurnedOn(false) {
  712. // Check if the visitor is disabled.
  713. SubEngine *Eng = N->getState()->getStateManager().getOwningEngine();
  714. assert(Eng && "Cannot file a bug report without an owning engine");
  715. AnalyzerOptions &Options = Eng->getAnalysisManager().options;
  716. if (!Options.shouldSuppressInlinedDefensiveChecks())
  717. IsSatisfied = true;
  718. assert(N->getState()->isNull(V).isConstrainedTrue() &&
  719. "The visitor only tracks the cases where V is constrained to 0");
  720. }
  721. void SuppressInlineDefensiveChecksVisitor::Profile(FoldingSetNodeID &ID) const {
  722. static int id = 0;
  723. ID.AddPointer(&id);
  724. ID.Add(V);
  725. }
  726. const char *SuppressInlineDefensiveChecksVisitor::getTag() {
  727. return "IDCVisitor";
  728. }
  729. /// \return name of the macro inside the location \p Loc.
  730. static StringRef getMacroName(SourceLocation Loc,
  731. BugReporterContext &BRC) {
  732. return Lexer::getImmediateMacroName(
  733. Loc, BRC.getSourceManager(), BRC.getASTContext().getLangOpts());
  734. }
  735. std::shared_ptr<PathDiagnosticPiece>
  736. SuppressInlineDefensiveChecksVisitor::VisitNode(const ExplodedNode *Succ,
  737. const ExplodedNode *Pred,
  738. BugReporterContext &BRC,
  739. BugReport &BR) {
  740. if (IsSatisfied)
  741. return nullptr;
  742. // Start tracking after we see the first state in which the value is null.
  743. if (!IsTrackingTurnedOn)
  744. if (Succ->getState()->isNull(V).isConstrainedTrue())
  745. IsTrackingTurnedOn = true;
  746. if (!IsTrackingTurnedOn)
  747. return nullptr;
  748. // Check if in the previous state it was feasible for this value
  749. // to *not* be null.
  750. if (!Pred->getState()->isNull(V).isConstrainedTrue()) {
  751. IsSatisfied = true;
  752. assert(Succ->getState()->isNull(V).isConstrainedTrue());
  753. // Check if this is inlined defensive checks.
  754. const LocationContext *CurLC =Succ->getLocationContext();
  755. const LocationContext *ReportLC = BR.getErrorNode()->getLocationContext();
  756. if (CurLC != ReportLC && !CurLC->isParentOf(ReportLC)) {
  757. BR.markInvalid("Suppress IDC", CurLC);
  758. return nullptr;
  759. }
  760. // Treat defensive checks in function-like macros as if they were an inlined
  761. // defensive check. If the bug location is not in a macro and the
  762. // terminator for the current location is in a macro then suppress the
  763. // warning.
  764. auto BugPoint = BR.getErrorNode()->getLocation().getAs<StmtPoint>();
  765. if (!BugPoint)
  766. return nullptr;
  767. ProgramPoint CurPoint = Succ->getLocation();
  768. const Stmt *CurTerminatorStmt = nullptr;
  769. if (auto BE = CurPoint.getAs<BlockEdge>()) {
  770. CurTerminatorStmt = BE->getSrc()->getTerminator().getStmt();
  771. } else if (auto SP = CurPoint.getAs<StmtPoint>()) {
  772. const Stmt *CurStmt = SP->getStmt();
  773. if (!CurStmt->getLocStart().isMacroID())
  774. return nullptr;
  775. CFGStmtMap *Map = CurLC->getAnalysisDeclContext()->getCFGStmtMap();
  776. CurTerminatorStmt = Map->getBlock(CurStmt)->getTerminator();
  777. } else {
  778. return nullptr;
  779. }
  780. if (!CurTerminatorStmt)
  781. return nullptr;
  782. SourceLocation TerminatorLoc = CurTerminatorStmt->getLocStart();
  783. if (TerminatorLoc.isMacroID()) {
  784. const SourceManager &SMgr = BRC.getSourceManager();
  785. std::pair<FileID, unsigned> TLInfo = SMgr.getDecomposedLoc(TerminatorLoc);
  786. SrcMgr::SLocEntry SE = SMgr.getSLocEntry(TLInfo.first);
  787. const SrcMgr::ExpansionInfo &EInfo = SE.getExpansion();
  788. if (EInfo.isFunctionMacroExpansion()) {
  789. SourceLocation BugLoc = BugPoint->getStmt()->getLocStart();
  790. // Suppress reports unless we are in that same macro.
  791. if (!BugLoc.isMacroID() ||
  792. getMacroName(BugLoc, BRC) != getMacroName(TerminatorLoc, BRC)) {
  793. BR.markInvalid("Suppress Macro IDC", CurLC);
  794. }
  795. return nullptr;
  796. }
  797. }
  798. }
  799. return nullptr;
  800. }
  801. static const MemRegion *getLocationRegionIfReference(const Expr *E,
  802. const ExplodedNode *N) {
  803. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
  804. if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
  805. if (!VD->getType()->isReferenceType())
  806. return nullptr;
  807. ProgramStateManager &StateMgr = N->getState()->getStateManager();
  808. MemRegionManager &MRMgr = StateMgr.getRegionManager();
  809. return MRMgr.getVarRegion(VD, N->getLocationContext());
  810. }
  811. }
  812. // FIXME: This does not handle other kinds of null references,
  813. // for example, references from FieldRegions:
  814. // struct Wrapper { int &ref; };
  815. // Wrapper w = { *(int *)0 };
  816. // w.ref = 1;
  817. return nullptr;
  818. }
  819. static const Expr *peelOffOuterExpr(const Expr *Ex,
  820. const ExplodedNode *N) {
  821. Ex = Ex->IgnoreParenCasts();
  822. if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Ex))
  823. return peelOffOuterExpr(EWC->getSubExpr(), N);
  824. if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Ex))
  825. return peelOffOuterExpr(OVE->getSourceExpr(), N);
  826. if (auto *POE = dyn_cast<PseudoObjectExpr>(Ex)) {
  827. auto *PropRef = dyn_cast<ObjCPropertyRefExpr>(POE->getSyntacticForm());
  828. if (PropRef && PropRef->isMessagingGetter()) {
  829. const Expr *GetterMessageSend =
  830. POE->getSemanticExpr(POE->getNumSemanticExprs() - 1);
  831. assert(isa<ObjCMessageExpr>(GetterMessageSend->IgnoreParenCasts()));
  832. return peelOffOuterExpr(GetterMessageSend, N);
  833. }
  834. }
  835. // Peel off the ternary operator.
  836. if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(Ex)) {
  837. // Find a node where the branching occurred and find out which branch
  838. // we took (true/false) by looking at the ExplodedGraph.
  839. const ExplodedNode *NI = N;
  840. do {
  841. ProgramPoint ProgPoint = NI->getLocation();
  842. if (Optional<BlockEdge> BE = ProgPoint.getAs<BlockEdge>()) {
  843. const CFGBlock *srcBlk = BE->getSrc();
  844. if (const Stmt *term = srcBlk->getTerminator()) {
  845. if (term == CO) {
  846. bool TookTrueBranch = (*(srcBlk->succ_begin()) == BE->getDst());
  847. if (TookTrueBranch)
  848. return peelOffOuterExpr(CO->getTrueExpr(), N);
  849. else
  850. return peelOffOuterExpr(CO->getFalseExpr(), N);
  851. }
  852. }
  853. }
  854. NI = NI->getFirstPred();
  855. } while (NI);
  856. }
  857. return Ex;
  858. }
  859. /// Walk through nodes until we get one that matches the statement exactly.
  860. /// Alternately, if we hit a known lvalue for the statement, we know we've
  861. /// gone too far (though we can likely track the lvalue better anyway).
  862. static const ExplodedNode* findNodeForStatement(const ExplodedNode *N,
  863. const Stmt *S,
  864. const Expr *Inner) {
  865. do {
  866. const ProgramPoint &pp = N->getLocation();
  867. if (auto ps = pp.getAs<StmtPoint>()) {
  868. if (ps->getStmt() == S || ps->getStmt() == Inner)
  869. break;
  870. } else if (auto CEE = pp.getAs<CallExitEnd>()) {
  871. if (CEE->getCalleeContext()->getCallSite() == S ||
  872. CEE->getCalleeContext()->getCallSite() == Inner)
  873. break;
  874. }
  875. N = N->getFirstPred();
  876. } while (N);
  877. return N;
  878. }
  879. /// Find the ExplodedNode where the lvalue (the value of 'Ex')
  880. /// was computed.
  881. static const ExplodedNode* findNodeForExpression(const ExplodedNode *N,
  882. const Expr *Inner) {
  883. while (N) {
  884. if (auto P = N->getLocation().getAs<PostStmt>()) {
  885. if (P->getStmt() == Inner)
  886. break;
  887. }
  888. N = N->getFirstPred();
  889. }
  890. assert(N && "Unable to find the lvalue node.");
  891. return N;
  892. }
  893. /// Performing operator `&' on an lvalue expression is essentially a no-op.
  894. /// Then, if we are taking addresses of fields or elements, these are also
  895. /// unlikely to matter.
  896. static const Expr* peelOfOuterAddrOf(const Expr* Ex) {
  897. Ex = Ex->IgnoreParenCasts();
  898. // FIXME: There's a hack in our Store implementation that always computes
  899. // field offsets around null pointers as if they are always equal to 0.
  900. // The idea here is to report accesses to fields as null dereferences
  901. // even though the pointer value that's being dereferenced is actually
  902. // the offset of the field rather than exactly 0.
  903. // See the FIXME in StoreManager's getLValueFieldOrIvar() method.
  904. // This code interacts heavily with this hack; otherwise the value
  905. // would not be null at all for most fields, so we'd be unable to track it.
  906. if (const auto *Op = dyn_cast<UnaryOperator>(Ex))
  907. if (Op->getOpcode() == UO_AddrOf && Op->getSubExpr()->isLValue())
  908. if (const Expr *DerefEx = bugreporter::getDerefExpr(Op->getSubExpr()))
  909. return DerefEx;
  910. return Ex;
  911. }
  912. bool bugreporter::trackNullOrUndefValue(const ExplodedNode *N,
  913. const Stmt *S,
  914. BugReport &report, bool IsArg,
  915. bool EnableNullFPSuppression) {
  916. if (!S || !N)
  917. return false;
  918. if (const auto *Ex = dyn_cast<Expr>(S))
  919. S = peelOffOuterExpr(Ex, N);
  920. const Expr *Inner = nullptr;
  921. if (const auto *Ex = dyn_cast<Expr>(S)) {
  922. Ex = peelOfOuterAddrOf(Ex);
  923. Ex = Ex->IgnoreParenCasts();
  924. if (Ex && (ExplodedGraph::isInterestingLValueExpr(Ex)
  925. || CallEvent::isCallStmt(Ex)))
  926. Inner = Ex;
  927. }
  928. if (IsArg && !Inner) {
  929. assert(N->getLocation().getAs<CallEnter>() && "Tracking arg but not at call");
  930. } else {
  931. N = findNodeForStatement(N, S, Inner);
  932. if (!N)
  933. return false;
  934. }
  935. ProgramStateRef state = N->getState();
  936. // The message send could be nil due to the receiver being nil.
  937. // At this point in the path, the receiver should be live since we are at the
  938. // message send expr. If it is nil, start tracking it.
  939. if (const Expr *Receiver = NilReceiverBRVisitor::getNilReceiver(S, N))
  940. trackNullOrUndefValue(N, Receiver, report, /* IsArg=*/ false,
  941. EnableNullFPSuppression);
  942. // See if the expression we're interested refers to a variable.
  943. // If so, we can track both its contents and constraints on its value.
  944. if (Inner && ExplodedGraph::isInterestingLValueExpr(Inner)) {
  945. const ExplodedNode *LVNode = findNodeForExpression(N, Inner);
  946. ProgramStateRef LVState = LVNode->getState();
  947. SVal LVal = LVNode->getSVal(Inner);
  948. const MemRegion *RR = getLocationRegionIfReference(Inner, N);
  949. bool LVIsNull = LVState->isNull(LVal).isConstrainedTrue();
  950. // If this is a C++ reference to a null pointer, we are tracking the
  951. // pointer. In addition, we should find the store at which the reference
  952. // got initialized.
  953. if (RR && !LVIsNull) {
  954. if (auto KV = LVal.getAs<KnownSVal>())
  955. report.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
  956. *KV, RR, EnableNullFPSuppression));
  957. }
  958. // In case of C++ references, we want to differentiate between a null
  959. // reference and reference to null pointer.
  960. // If the LVal is null, check if we are dealing with null reference.
  961. // For those, we want to track the location of the reference.
  962. const MemRegion *R = (RR && LVIsNull) ? RR :
  963. LVNode->getSVal(Inner).getAsRegion();
  964. if (R) {
  965. // Mark both the variable region and its contents as interesting.
  966. SVal V = LVState->getRawSVal(loc::MemRegionVal(R));
  967. report.markInteresting(R);
  968. report.markInteresting(V);
  969. report.addVisitor(llvm::make_unique<UndefOrNullArgVisitor>(R));
  970. // If the contents are symbolic, find out when they became null.
  971. if (V.getAsLocSymbol(/*IncludeBaseRegions*/ true))
  972. report.addVisitor(llvm::make_unique<TrackConstraintBRVisitor>(
  973. V.castAs<DefinedSVal>(), false));
  974. // Add visitor, which will suppress inline defensive checks.
  975. if (auto DV = V.getAs<DefinedSVal>()) {
  976. if (!DV->isZeroConstant() && LVState->isNull(*DV).isConstrainedTrue() &&
  977. EnableNullFPSuppression) {
  978. report.addVisitor(
  979. llvm::make_unique<SuppressInlineDefensiveChecksVisitor>(*DV,
  980. LVNode));
  981. }
  982. }
  983. if (auto KV = V.getAs<KnownSVal>())
  984. report.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
  985. *KV, R, EnableNullFPSuppression));
  986. return true;
  987. }
  988. }
  989. // If the expression is not an "lvalue expression", we can still
  990. // track the constraints on its contents.
  991. SVal V = state->getSValAsScalarOrLoc(S, N->getLocationContext());
  992. // If the value came from an inlined function call, we should at least make
  993. // sure that function isn't pruned in our output.
  994. if (const auto *E = dyn_cast<Expr>(S))
  995. S = E->IgnoreParenCasts();
  996. ReturnVisitor::addVisitorIfNecessary(N, S, report, EnableNullFPSuppression);
  997. // Uncomment this to find cases where we aren't properly getting the
  998. // base value that was dereferenced.
  999. // assert(!V.isUnknownOrUndef());
  1000. // Is it a symbolic value?
  1001. if (auto L = V.getAs<loc::MemRegionVal>()) {
  1002. report.addVisitor(llvm::make_unique<UndefOrNullArgVisitor>(L->getRegion()));
  1003. // At this point we are dealing with the region's LValue.
  1004. // However, if the rvalue is a symbolic region, we should track it as well.
  1005. // Try to use the correct type when looking up the value.
  1006. SVal RVal;
  1007. if (const auto *E = dyn_cast<Expr>(S))
  1008. RVal = state->getRawSVal(L.getValue(), E->getType());
  1009. else
  1010. RVal = state->getSVal(L->getRegion());
  1011. if (auto KV = RVal.getAs<KnownSVal>())
  1012. report.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
  1013. *KV, L->getRegion(), EnableNullFPSuppression));
  1014. const MemRegion *RegionRVal = RVal.getAsRegion();
  1015. if (RegionRVal && isa<SymbolicRegion>(RegionRVal)) {
  1016. report.markInteresting(RegionRVal);
  1017. report.addVisitor(llvm::make_unique<TrackConstraintBRVisitor>(
  1018. loc::MemRegionVal(RegionRVal), false));
  1019. }
  1020. }
  1021. return true;
  1022. }
  1023. const Expr *NilReceiverBRVisitor::getNilReceiver(const Stmt *S,
  1024. const ExplodedNode *N) {
  1025. const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S);
  1026. if (!ME)
  1027. return nullptr;
  1028. if (const Expr *Receiver = ME->getInstanceReceiver()) {
  1029. ProgramStateRef state = N->getState();
  1030. SVal V = N->getSVal(Receiver);
  1031. if (state->isNull(V).isConstrainedTrue())
  1032. return Receiver;
  1033. }
  1034. return nullptr;
  1035. }
  1036. std::shared_ptr<PathDiagnosticPiece>
  1037. NilReceiverBRVisitor::VisitNode(const ExplodedNode *N,
  1038. const ExplodedNode *PrevN,
  1039. BugReporterContext &BRC, BugReport &BR) {
  1040. Optional<PreStmt> P = N->getLocationAs<PreStmt>();
  1041. if (!P)
  1042. return nullptr;
  1043. const Stmt *S = P->getStmt();
  1044. const Expr *Receiver = getNilReceiver(S, N);
  1045. if (!Receiver)
  1046. return nullptr;
  1047. llvm::SmallString<256> Buf;
  1048. llvm::raw_svector_ostream OS(Buf);
  1049. if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
  1050. OS << "'";
  1051. ME->getSelector().print(OS);
  1052. OS << "' not called";
  1053. }
  1054. else {
  1055. OS << "No method is called";
  1056. }
  1057. OS << " because the receiver is nil";
  1058. // The receiver was nil, and hence the method was skipped.
  1059. // Register a BugReporterVisitor to issue a message telling us how
  1060. // the receiver was null.
  1061. bugreporter::trackNullOrUndefValue(N, Receiver, BR, /*IsArg*/ false,
  1062. /*EnableNullFPSuppression*/ false);
  1063. // Issue a message saying that the method was skipped.
  1064. PathDiagnosticLocation L(Receiver, BRC.getSourceManager(),
  1065. N->getLocationContext());
  1066. return std::make_shared<PathDiagnosticEventPiece>(L, OS.str());
  1067. }
  1068. // Registers every VarDecl inside a Stmt with a last store visitor.
  1069. void FindLastStoreBRVisitor::registerStatementVarDecls(BugReport &BR,
  1070. const Stmt *S,
  1071. bool EnableNullFPSuppression) {
  1072. const ExplodedNode *N = BR.getErrorNode();
  1073. std::deque<const Stmt *> WorkList;
  1074. WorkList.push_back(S);
  1075. while (!WorkList.empty()) {
  1076. const Stmt *Head = WorkList.front();
  1077. WorkList.pop_front();
  1078. ProgramStateManager &StateMgr = N->getState()->getStateManager();
  1079. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Head)) {
  1080. if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
  1081. const VarRegion *R =
  1082. StateMgr.getRegionManager().getVarRegion(VD, N->getLocationContext());
  1083. // What did we load?
  1084. SVal V = N->getSVal(S);
  1085. if (V.getAs<loc::ConcreteInt>() || V.getAs<nonloc::ConcreteInt>()) {
  1086. // Register a new visitor with the BugReport.
  1087. BR.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
  1088. V.castAs<KnownSVal>(), R, EnableNullFPSuppression));
  1089. }
  1090. }
  1091. }
  1092. for (const Stmt *SubStmt : Head->children())
  1093. WorkList.push_back(SubStmt);
  1094. }
  1095. }
  1096. //===----------------------------------------------------------------------===//
  1097. // Visitor that tries to report interesting diagnostics from conditions.
  1098. //===----------------------------------------------------------------------===//
  1099. /// Return the tag associated with this visitor. This tag will be used
  1100. /// to make all PathDiagnosticPieces created by this visitor.
  1101. const char *ConditionBRVisitor::getTag() {
  1102. return "ConditionBRVisitor";
  1103. }
  1104. std::shared_ptr<PathDiagnosticPiece>
  1105. ConditionBRVisitor::VisitNode(const ExplodedNode *N, const ExplodedNode *Prev,
  1106. BugReporterContext &BRC, BugReport &BR) {
  1107. auto piece = VisitNodeImpl(N, Prev, BRC, BR);
  1108. if (piece) {
  1109. piece->setTag(getTag());
  1110. if (auto *ev = dyn_cast<PathDiagnosticEventPiece>(piece.get()))
  1111. ev->setPrunable(true, /* override */ false);
  1112. }
  1113. return piece;
  1114. }
  1115. std::shared_ptr<PathDiagnosticPiece>
  1116. ConditionBRVisitor::VisitNodeImpl(const ExplodedNode *N,
  1117. const ExplodedNode *Prev,
  1118. BugReporterContext &BRC, BugReport &BR) {
  1119. ProgramPoint progPoint = N->getLocation();
  1120. ProgramStateRef CurrentState = N->getState();
  1121. ProgramStateRef PrevState = Prev->getState();
  1122. // Compare the GDMs of the state, because that is where constraints
  1123. // are managed. Note that ensure that we only look at nodes that
  1124. // were generated by the analyzer engine proper, not checkers.
  1125. if (CurrentState->getGDM().getRoot() ==
  1126. PrevState->getGDM().getRoot())
  1127. return nullptr;
  1128. // If an assumption was made on a branch, it should be caught
  1129. // here by looking at the state transition.
  1130. if (Optional<BlockEdge> BE = progPoint.getAs<BlockEdge>()) {
  1131. const CFGBlock *srcBlk = BE->getSrc();
  1132. if (const Stmt *term = srcBlk->getTerminator())
  1133. return VisitTerminator(term, N, srcBlk, BE->getDst(), BR, BRC);
  1134. return nullptr;
  1135. }
  1136. if (Optional<PostStmt> PS = progPoint.getAs<PostStmt>()) {
  1137. // FIXME: Assuming that BugReporter is a GRBugReporter is a layering
  1138. // violation.
  1139. const std::pair<const ProgramPointTag *, const ProgramPointTag *> &tags =
  1140. cast<GRBugReporter>(BRC.getBugReporter()).
  1141. getEngine().geteagerlyAssumeBinOpBifurcationTags();
  1142. const ProgramPointTag *tag = PS->getTag();
  1143. if (tag == tags.first)
  1144. return VisitTrueTest(cast<Expr>(PS->getStmt()), true,
  1145. BRC, BR, N);
  1146. if (tag == tags.second)
  1147. return VisitTrueTest(cast<Expr>(PS->getStmt()), false,
  1148. BRC, BR, N);
  1149. return nullptr;
  1150. }
  1151. return nullptr;
  1152. }
  1153. std::shared_ptr<PathDiagnosticPiece> ConditionBRVisitor::VisitTerminator(
  1154. const Stmt *Term, const ExplodedNode *N, const CFGBlock *srcBlk,
  1155. const CFGBlock *dstBlk, BugReport &R, BugReporterContext &BRC) {
  1156. const Expr *Cond = nullptr;
  1157. // In the code below, Term is a CFG terminator and Cond is a branch condition
  1158. // expression upon which the decision is made on this terminator.
  1159. //
  1160. // For example, in "if (x == 0)", the "if (x == 0)" statement is a terminator,
  1161. // and "x == 0" is the respective condition.
  1162. //
  1163. // Another example: in "if (x && y)", we've got two terminators and two
  1164. // conditions due to short-circuit nature of operator "&&":
  1165. // 1. The "if (x && y)" statement is a terminator,
  1166. // and "y" is the respective condition.
  1167. // 2. Also "x && ..." is another terminator,
  1168. // and "x" is its condition.
  1169. switch (Term->getStmtClass()) {
  1170. // FIXME: Stmt::SwitchStmtClass is worth handling, however it is a bit
  1171. // more tricky because there are more than two branches to account for.
  1172. default:
  1173. return nullptr;
  1174. case Stmt::IfStmtClass:
  1175. Cond = cast<IfStmt>(Term)->getCond();
  1176. break;
  1177. case Stmt::ConditionalOperatorClass:
  1178. Cond = cast<ConditionalOperator>(Term)->getCond();
  1179. break;
  1180. case Stmt::BinaryOperatorClass:
  1181. // When we encounter a logical operator (&& or ||) as a CFG terminator,
  1182. // then the condition is actually its LHS; otherwise, we'd encounter
  1183. // the parent, such as if-statement, as a terminator.
  1184. const auto *BO = cast<BinaryOperator>(Term);
  1185. assert(BO->isLogicalOp() &&
  1186. "CFG terminator is not a short-circuit operator!");
  1187. Cond = BO->getLHS();
  1188. break;
  1189. }
  1190. // However, when we encounter a logical operator as a branch condition,
  1191. // then the condition is actually its RHS, because LHS would be
  1192. // the condition for the logical operator terminator.
  1193. while (const auto *InnerBO = dyn_cast<BinaryOperator>(Cond)) {
  1194. if (!InnerBO->isLogicalOp())
  1195. break;
  1196. Cond = InnerBO->getRHS()->IgnoreParens();
  1197. }
  1198. assert(Cond);
  1199. assert(srcBlk->succ_size() == 2);
  1200. const bool tookTrue = *(srcBlk->succ_begin()) == dstBlk;
  1201. return VisitTrueTest(Cond, tookTrue, BRC, R, N);
  1202. }
  1203. std::shared_ptr<PathDiagnosticPiece>
  1204. ConditionBRVisitor::VisitTrueTest(const Expr *Cond, bool tookTrue,
  1205. BugReporterContext &BRC, BugReport &R,
  1206. const ExplodedNode *N) {
  1207. // These will be modified in code below, but we need to preserve the original
  1208. // values in case we want to throw the generic message.
  1209. const Expr *CondTmp = Cond;
  1210. bool tookTrueTmp = tookTrue;
  1211. while (true) {
  1212. CondTmp = CondTmp->IgnoreParenCasts();
  1213. switch (CondTmp->getStmtClass()) {
  1214. default:
  1215. break;
  1216. case Stmt::BinaryOperatorClass:
  1217. if (auto P = VisitTrueTest(Cond, cast<BinaryOperator>(CondTmp),
  1218. tookTrueTmp, BRC, R, N))
  1219. return P;
  1220. break;
  1221. case Stmt::DeclRefExprClass:
  1222. if (auto P = VisitTrueTest(Cond, cast<DeclRefExpr>(CondTmp),
  1223. tookTrueTmp, BRC, R, N))
  1224. return P;
  1225. break;
  1226. case Stmt::UnaryOperatorClass: {
  1227. const UnaryOperator *UO = cast<UnaryOperator>(CondTmp);
  1228. if (UO->getOpcode() == UO_LNot) {
  1229. tookTrueTmp = !tookTrueTmp;
  1230. CondTmp = UO->getSubExpr();
  1231. continue;
  1232. }
  1233. break;
  1234. }
  1235. }
  1236. break;
  1237. }
  1238. // Condition too complex to explain? Just say something so that the user
  1239. // knew we've made some path decision at this point.
  1240. const LocationContext *LCtx = N->getLocationContext();
  1241. PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
  1242. if (!Loc.isValid() || !Loc.asLocation().isValid())
  1243. return nullptr;
  1244. return std::make_shared<PathDiagnosticEventPiece>(
  1245. Loc, tookTrue ? GenericTrueMessage : GenericFalseMessage);
  1246. }
  1247. bool ConditionBRVisitor::patternMatch(const Expr *Ex,
  1248. const Expr *ParentEx,
  1249. raw_ostream &Out,
  1250. BugReporterContext &BRC,
  1251. BugReport &report,
  1252. const ExplodedNode *N,
  1253. Optional<bool> &prunable) {
  1254. const Expr *OriginalExpr = Ex;
  1255. Ex = Ex->IgnoreParenCasts();
  1256. // Use heuristics to determine if Ex is a macro expending to a literal and
  1257. // if so, use the macro's name.
  1258. SourceLocation LocStart = Ex->getLocStart();
  1259. SourceLocation LocEnd = Ex->getLocEnd();
  1260. if (LocStart.isMacroID() && LocEnd.isMacroID() &&
  1261. (isa<GNUNullExpr>(Ex) ||
  1262. isa<ObjCBoolLiteralExpr>(Ex) ||
  1263. isa<CXXBoolLiteralExpr>(Ex) ||
  1264. isa<IntegerLiteral>(Ex) ||
  1265. isa<FloatingLiteral>(Ex))) {
  1266. StringRef StartName = Lexer::getImmediateMacroNameForDiagnostics(LocStart,
  1267. BRC.getSourceManager(), BRC.getASTContext().getLangOpts());
  1268. StringRef EndName = Lexer::getImmediateMacroNameForDiagnostics(LocEnd,
  1269. BRC.getSourceManager(), BRC.getASTContext().getLangOpts());
  1270. bool beginAndEndAreTheSameMacro = StartName.equals(EndName);
  1271. bool partOfParentMacro = false;
  1272. if (ParentEx->getLocStart().isMacroID()) {
  1273. StringRef PName = Lexer::getImmediateMacroNameForDiagnostics(
  1274. ParentEx->getLocStart(), BRC.getSourceManager(),
  1275. BRC.getASTContext().getLangOpts());
  1276. partOfParentMacro = PName.equals(StartName);
  1277. }
  1278. if (beginAndEndAreTheSameMacro && !partOfParentMacro ) {
  1279. // Get the location of the macro name as written by the caller.
  1280. SourceLocation Loc = LocStart;
  1281. while (LocStart.isMacroID()) {
  1282. Loc = LocStart;
  1283. LocStart = BRC.getSourceManager().getImmediateMacroCallerLoc(LocStart);
  1284. }
  1285. StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
  1286. Loc, BRC.getSourceManager(), BRC.getASTContext().getLangOpts());
  1287. // Return the macro name.
  1288. Out << MacroName;
  1289. return false;
  1290. }
  1291. }
  1292. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Ex)) {
  1293. const bool quotes = isa<VarDecl>(DR->getDecl());
  1294. if (quotes) {
  1295. Out << '\'';
  1296. const LocationContext *LCtx = N->getLocationContext();
  1297. const ProgramState *state = N->getState().get();
  1298. if (const MemRegion *R = state->getLValue(cast<VarDecl>(DR->getDecl()),
  1299. LCtx).getAsRegion()) {
  1300. if (report.isInteresting(R))
  1301. prunable = false;
  1302. else {
  1303. const ProgramState *state = N->getState().get();
  1304. SVal V = state->getSVal(R);
  1305. if (report.isInteresting(V))
  1306. prunable = false;
  1307. }
  1308. }
  1309. }
  1310. Out << DR->getDecl()->getDeclName().getAsString();
  1311. if (quotes)
  1312. Out << '\'';
  1313. return quotes;
  1314. }
  1315. if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(Ex)) {
  1316. QualType OriginalTy = OriginalExpr->getType();
  1317. if (OriginalTy->isPointerType()) {
  1318. if (IL->getValue() == 0) {
  1319. Out << "null";
  1320. return false;
  1321. }
  1322. }
  1323. else if (OriginalTy->isObjCObjectPointerType()) {
  1324. if (IL->getValue() == 0) {
  1325. Out << "nil";
  1326. return false;
  1327. }
  1328. }
  1329. Out << IL->getValue();
  1330. return false;
  1331. }
  1332. return false;
  1333. }
  1334. std::shared_ptr<PathDiagnosticPiece>
  1335. ConditionBRVisitor::VisitTrueTest(const Expr *Cond, const BinaryOperator *BExpr,
  1336. const bool tookTrue, BugReporterContext &BRC,
  1337. BugReport &R, const ExplodedNode *N) {
  1338. bool shouldInvert = false;
  1339. Optional<bool> shouldPrune;
  1340. SmallString<128> LhsString, RhsString;
  1341. {
  1342. llvm::raw_svector_ostream OutLHS(LhsString), OutRHS(RhsString);
  1343. const bool isVarLHS = patternMatch(BExpr->getLHS(), BExpr, OutLHS,
  1344. BRC, R, N, shouldPrune);
  1345. const bool isVarRHS = patternMatch(BExpr->getRHS(), BExpr, OutRHS,
  1346. BRC, R, N, shouldPrune);
  1347. shouldInvert = !isVarLHS && isVarRHS;
  1348. }
  1349. BinaryOperator::Opcode Op = BExpr->getOpcode();
  1350. if (BinaryOperator::isAssignmentOp(Op)) {
  1351. // For assignment operators, all that we care about is that the LHS
  1352. // evaluates to "true" or "false".
  1353. return VisitConditionVariable(LhsString, BExpr->getLHS(), tookTrue,
  1354. BRC, R, N);
  1355. }
  1356. // For non-assignment operations, we require that we can understand
  1357. // both the LHS and RHS.
  1358. if (LhsString.empty() || RhsString.empty() ||
  1359. !BinaryOperator::isComparisonOp(Op) || Op == BO_Cmp)
  1360. return nullptr;
  1361. // Should we invert the strings if the LHS is not a variable name?
  1362. SmallString<256> buf;
  1363. llvm::raw_svector_ostream Out(buf);
  1364. Out << "Assuming " << (shouldInvert ? RhsString : LhsString) << " is ";
  1365. // Do we need to invert the opcode?
  1366. if (shouldInvert)
  1367. switch (Op) {
  1368. default: break;
  1369. case BO_LT: Op = BO_GT; break;
  1370. case BO_GT: Op = BO_LT; break;
  1371. case BO_LE: Op = BO_GE; break;
  1372. case BO_GE: Op = BO_LE; break;
  1373. }
  1374. if (!tookTrue)
  1375. switch (Op) {
  1376. case BO_EQ: Op = BO_NE; break;
  1377. case BO_NE: Op = BO_EQ; break;
  1378. case BO_LT: Op = BO_GE; break;
  1379. case BO_GT: Op = BO_LE; break;
  1380. case BO_LE: Op = BO_GT; break;
  1381. case BO_GE: Op = BO_LT; break;
  1382. default:
  1383. return nullptr;
  1384. }
  1385. switch (Op) {
  1386. case BO_EQ:
  1387. Out << "equal to ";
  1388. break;
  1389. case BO_NE:
  1390. Out << "not equal to ";
  1391. break;
  1392. default:
  1393. Out << BinaryOperator::getOpcodeStr(Op) << ' ';
  1394. break;
  1395. }
  1396. Out << (shouldInvert ? LhsString : RhsString);
  1397. const LocationContext *LCtx = N->getLocationContext();
  1398. PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
  1399. auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str());
  1400. if (shouldPrune.hasValue())
  1401. event->setPrunable(shouldPrune.getValue());
  1402. return event;
  1403. }
  1404. std::shared_ptr<PathDiagnosticPiece> ConditionBRVisitor::VisitConditionVariable(
  1405. StringRef LhsString, const Expr *CondVarExpr, const bool tookTrue,
  1406. BugReporterContext &BRC, BugReport &report, const ExplodedNode *N) {
  1407. // FIXME: If there's already a constraint tracker for this variable,
  1408. // we shouldn't emit anything here (c.f. the double note in
  1409. // test/Analysis/inlining/path-notes.c)
  1410. SmallString<256> buf;
  1411. llvm::raw_svector_ostream Out(buf);
  1412. Out << "Assuming " << LhsString << " is ";
  1413. QualType Ty = CondVarExpr->getType();
  1414. if (Ty->isPointerType())
  1415. Out << (tookTrue ? "not null" : "null");
  1416. else if (Ty->isObjCObjectPointerType())
  1417. Out << (tookTrue ? "not nil" : "nil");
  1418. else if (Ty->isBooleanType())
  1419. Out << (tookTrue ? "true" : "false");
  1420. else if (Ty->isIntegralOrEnumerationType())
  1421. Out << (tookTrue ? "non-zero" : "zero");
  1422. else
  1423. return nullptr;
  1424. const LocationContext *LCtx = N->getLocationContext();
  1425. PathDiagnosticLocation Loc(CondVarExpr, BRC.getSourceManager(), LCtx);
  1426. auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str());
  1427. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(CondVarExpr)) {
  1428. if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
  1429. const ProgramState *state = N->getState().get();
  1430. if (const MemRegion *R = state->getLValue(VD, LCtx).getAsRegion()) {
  1431. if (report.isInteresting(R))
  1432. event->setPrunable(false);
  1433. }
  1434. }
  1435. }
  1436. return event;
  1437. }
  1438. std::shared_ptr<PathDiagnosticPiece>
  1439. ConditionBRVisitor::VisitTrueTest(const Expr *Cond, const DeclRefExpr *DR,
  1440. const bool tookTrue, BugReporterContext &BRC,
  1441. BugReport &report, const ExplodedNode *N) {
  1442. const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
  1443. if (!VD)
  1444. return nullptr;
  1445. SmallString<256> Buf;
  1446. llvm::raw_svector_ostream Out(Buf);
  1447. Out << "Assuming '" << VD->getDeclName() << "' is ";
  1448. QualType VDTy = VD->getType();
  1449. if (VDTy->isPointerType())
  1450. Out << (tookTrue ? "non-null" : "null");
  1451. else if (VDTy->isObjCObjectPointerType())
  1452. Out << (tookTrue ? "non-nil" : "nil");
  1453. else if (VDTy->isScalarType())
  1454. Out << (tookTrue ? "not equal to 0" : "0");
  1455. else
  1456. return nullptr;
  1457. const LocationContext *LCtx = N->getLocationContext();
  1458. PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
  1459. auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str());
  1460. const ProgramState *state = N->getState().get();
  1461. if (const MemRegion *R = state->getLValue(VD, LCtx).getAsRegion()) {
  1462. if (report.isInteresting(R))
  1463. event->setPrunable(false);
  1464. else {
  1465. SVal V = state->getSVal(R);
  1466. if (report.isInteresting(V))
  1467. event->setPrunable(false);
  1468. }
  1469. }
  1470. return std::move(event);
  1471. }
  1472. const char *const ConditionBRVisitor::GenericTrueMessage =
  1473. "Assuming the condition is true";
  1474. const char *const ConditionBRVisitor::GenericFalseMessage =
  1475. "Assuming the condition is false";
  1476. bool ConditionBRVisitor::isPieceMessageGeneric(
  1477. const PathDiagnosticPiece *Piece) {
  1478. return Piece->getString() == GenericTrueMessage ||
  1479. Piece->getString() == GenericFalseMessage;
  1480. }
  1481. std::unique_ptr<PathDiagnosticPiece>
  1482. LikelyFalsePositiveSuppressionBRVisitor::getEndPath(BugReporterContext &BRC,
  1483. const ExplodedNode *N,
  1484. BugReport &BR) {
  1485. // Here we suppress false positives coming from system headers. This list is
  1486. // based on known issues.
  1487. ExprEngine &Eng = BRC.getBugReporter().getEngine();
  1488. AnalyzerOptions &Options = Eng.getAnalysisManager().options;
  1489. const Decl *D = N->getLocationContext()->getDecl();
  1490. if (AnalysisDeclContext::isInStdNamespace(D)) {
  1491. // Skip reports within the 'std' namespace. Although these can sometimes be
  1492. // the user's fault, we currently don't report them very well, and
  1493. // Note that this will not help for any other data structure libraries, like
  1494. // TR1, Boost, or llvm/ADT.
  1495. if (Options.shouldSuppressFromCXXStandardLibrary()) {
  1496. BR.markInvalid(getTag(), nullptr);
  1497. return nullptr;
  1498. } else {
  1499. // If the complete 'std' suppression is not enabled, suppress reports
  1500. // from the 'std' namespace that are known to produce false positives.
  1501. // The analyzer issues a false use-after-free when std::list::pop_front
  1502. // or std::list::pop_back are called multiple times because we cannot
  1503. // reason about the internal invariants of the data structure.
  1504. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
  1505. const CXXRecordDecl *CD = MD->getParent();
  1506. if (CD->getName() == "list") {
  1507. BR.markInvalid(getTag(), nullptr);
  1508. return nullptr;
  1509. }
  1510. }
  1511. // The analyzer issues a false positive when the constructor of
  1512. // std::__independent_bits_engine from algorithms is used.
  1513. if (const CXXConstructorDecl *MD = dyn_cast<CXXConstructorDecl>(D)) {
  1514. const CXXRecordDecl *CD = MD->getParent();
  1515. if (CD->getName() == "__independent_bits_engine") {
  1516. BR.markInvalid(getTag(), nullptr);
  1517. return nullptr;
  1518. }
  1519. }
  1520. for (const LocationContext *LCtx = N->getLocationContext(); LCtx;
  1521. LCtx = LCtx->getParent()) {
  1522. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LCtx->getDecl());
  1523. if (!MD)
  1524. continue;
  1525. const CXXRecordDecl *CD = MD->getParent();
  1526. // The analyzer issues a false positive on
  1527. // std::basic_string<uint8_t> v; v.push_back(1);
  1528. // and
  1529. // std::u16string s; s += u'a';
  1530. // because we cannot reason about the internal invariants of the
  1531. // data structure.
  1532. if (CD->getName() == "basic_string") {
  1533. BR.markInvalid(getTag(), nullptr);
  1534. return nullptr;
  1535. }
  1536. // The analyzer issues a false positive on
  1537. // std::shared_ptr<int> p(new int(1)); p = nullptr;
  1538. // because it does not reason properly about temporary destructors.
  1539. if (CD->getName() == "shared_ptr") {
  1540. BR.markInvalid(getTag(), nullptr);
  1541. return nullptr;
  1542. }
  1543. }
  1544. }
  1545. }
  1546. // Skip reports within the sys/queue.h macros as we do not have the ability to
  1547. // reason about data structure shapes.
  1548. SourceManager &SM = BRC.getSourceManager();
  1549. FullSourceLoc Loc = BR.getLocation(SM).asLocation();
  1550. while (Loc.isMacroID()) {
  1551. Loc = Loc.getSpellingLoc();
  1552. if (SM.getFilename(Loc).endswith("sys/queue.h")) {
  1553. BR.markInvalid(getTag(), nullptr);
  1554. return nullptr;
  1555. }
  1556. }
  1557. return nullptr;
  1558. }
  1559. std::shared_ptr<PathDiagnosticPiece>
  1560. UndefOrNullArgVisitor::VisitNode(const ExplodedNode *N,
  1561. const ExplodedNode *PrevN,
  1562. BugReporterContext &BRC, BugReport &BR) {
  1563. ProgramStateRef State = N->getState();
  1564. ProgramPoint ProgLoc = N->getLocation();
  1565. // We are only interested in visiting CallEnter nodes.
  1566. Optional<CallEnter> CEnter = ProgLoc.getAs<CallEnter>();
  1567. if (!CEnter)
  1568. return nullptr;
  1569. // Check if one of the arguments is the region the visitor is tracking.
  1570. CallEventManager &CEMgr = BRC.getStateManager().getCallEventManager();
  1571. CallEventRef<> Call = CEMgr.getCaller(CEnter->getCalleeContext(), State);
  1572. unsigned Idx = 0;
  1573. ArrayRef<ParmVarDecl*> parms = Call->parameters();
  1574. for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
  1575. I != E; ++I, ++Idx) {
  1576. const MemRegion *ArgReg = Call->getArgSVal(Idx).getAsRegion();
  1577. // Are we tracking the argument or its subregion?
  1578. if ( !ArgReg || !R->isSubRegionOf(ArgReg->StripCasts()))
  1579. continue;
  1580. // Check the function parameter type.
  1581. const ParmVarDecl *ParamDecl = *I;
  1582. assert(ParamDecl && "Formal parameter has no decl?");
  1583. QualType T = ParamDecl->getType();
  1584. if (!(T->isAnyPointerType() || T->isReferenceType())) {
  1585. // Function can only change the value passed in by address.
  1586. continue;
  1587. }
  1588. // If it is a const pointer value, the function does not intend to
  1589. // change the value.
  1590. if (T->getPointeeType().isConstQualified())
  1591. continue;
  1592. // Mark the call site (LocationContext) as interesting if the value of the
  1593. // argument is undefined or '0'/'NULL'.
  1594. SVal BoundVal = State->getSVal(R);
  1595. if (BoundVal.isUndef() || BoundVal.isZeroConstant()) {
  1596. BR.markInteresting(CEnter->getCalleeContext());
  1597. return nullptr;
  1598. }
  1599. }
  1600. return nullptr;
  1601. }
  1602. std::shared_ptr<PathDiagnosticPiece>
  1603. CXXSelfAssignmentBRVisitor::VisitNode(const ExplodedNode *Succ,
  1604. const ExplodedNode *Pred,
  1605. BugReporterContext &BRC, BugReport &BR) {
  1606. if (Satisfied)
  1607. return nullptr;
  1608. auto Edge = Succ->getLocation().getAs<BlockEdge>();
  1609. if (!Edge.hasValue())
  1610. return nullptr;
  1611. auto Tag = Edge->getTag();
  1612. if (!Tag)
  1613. return nullptr;
  1614. if (Tag->getTagDescription() != "cplusplus.SelfAssignment")
  1615. return nullptr;
  1616. Satisfied = true;
  1617. const auto *Met =
  1618. dyn_cast<CXXMethodDecl>(Succ->getCodeDecl().getAsFunction());
  1619. assert(Met && "Not a C++ method.");
  1620. assert((Met->isCopyAssignmentOperator() || Met->isMoveAssignmentOperator()) &&
  1621. "Not a copy/move assignment operator.");
  1622. const auto *LCtx = Edge->getLocationContext();
  1623. const auto &State = Succ->getState();
  1624. auto &SVB = State->getStateManager().getSValBuilder();
  1625. const auto Param =
  1626. State->getSVal(State->getRegion(Met->getParamDecl(0), LCtx));
  1627. const auto This =
  1628. State->getSVal(SVB.getCXXThis(Met, LCtx->getCurrentStackFrame()));
  1629. auto L = PathDiagnosticLocation::create(Met, BRC.getSourceManager());
  1630. if (!L.isValid() || !L.asLocation().isValid())
  1631. return nullptr;
  1632. SmallString<256> Buf;
  1633. llvm::raw_svector_ostream Out(Buf);
  1634. Out << "Assuming " << Met->getParamDecl(0)->getName() <<
  1635. ((Param == This) ? " == " : " != ") << "*this";
  1636. auto Piece = std::make_shared<PathDiagnosticEventPiece>(L, Out.str());
  1637. Piece->addRange(Met->getSourceRange());
  1638. return std::move(Piece);
  1639. }