BugReporterVisitors.cpp 88 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523
  1. //===- BugReporterVisitors.cpp - Helpers for reporting bugs ---------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file defines a set of BugReporter "visitors" which can be used to
  10. // enhance the diagnostics reported for a bug.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h"
  14. #include "clang/AST/ASTContext.h"
  15. #include "clang/AST/Decl.h"
  16. #include "clang/AST/DeclBase.h"
  17. #include "clang/AST/DeclCXX.h"
  18. #include "clang/AST/Expr.h"
  19. #include "clang/AST/ExprCXX.h"
  20. #include "clang/AST/ExprObjC.h"
  21. #include "clang/AST/Stmt.h"
  22. #include "clang/AST/Type.h"
  23. #include "clang/ASTMatchers/ASTMatchFinder.h"
  24. #include "clang/Analysis/AnalysisDeclContext.h"
  25. #include "clang/Analysis/CFG.h"
  26. #include "clang/Analysis/CFGStmtMap.h"
  27. #include "clang/Analysis/ProgramPoint.h"
  28. #include "clang/Basic/IdentifierTable.h"
  29. #include "clang/Basic/LLVM.h"
  30. #include "clang/Basic/SourceLocation.h"
  31. #include "clang/Basic/SourceManager.h"
  32. #include "clang/Lex/Lexer.h"
  33. #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
  34. #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
  35. #include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
  36. #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
  37. #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
  38. #include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
  39. #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
  40. #include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
  41. #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
  42. #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h"
  43. #include "clang/StaticAnalyzer/Core/PathSensitive/SMTConv.h"
  44. #include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h"
  45. #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
  46. #include "clang/StaticAnalyzer/Core/PathSensitive/SubEngine.h"
  47. #include "llvm/ADT/ArrayRef.h"
  48. #include "llvm/ADT/None.h"
  49. #include "llvm/ADT/Optional.h"
  50. #include "llvm/ADT/STLExtras.h"
  51. #include "llvm/ADT/SmallPtrSet.h"
  52. #include "llvm/ADT/SmallString.h"
  53. #include "llvm/ADT/SmallVector.h"
  54. #include "llvm/ADT/StringExtras.h"
  55. #include "llvm/ADT/StringRef.h"
  56. #include "llvm/Support/Casting.h"
  57. #include "llvm/Support/ErrorHandling.h"
  58. #include "llvm/Support/raw_ostream.h"
  59. #include <cassert>
  60. #include <deque>
  61. #include <memory>
  62. #include <string>
  63. #include <utility>
  64. using namespace clang;
  65. using namespace ento;
  66. //===----------------------------------------------------------------------===//
  67. // Utility functions.
  68. //===----------------------------------------------------------------------===//
  69. static const Expr *peelOffPointerArithmetic(const BinaryOperator *B) {
  70. if (B->isAdditiveOp() && B->getType()->isPointerType()) {
  71. if (B->getLHS()->getType()->isPointerType()) {
  72. return B->getLHS();
  73. } else if (B->getRHS()->getType()->isPointerType()) {
  74. return B->getRHS();
  75. }
  76. }
  77. return nullptr;
  78. }
  79. /// Given that expression S represents a pointer that would be dereferenced,
  80. /// try to find a sub-expression from which the pointer came from.
  81. /// This is used for tracking down origins of a null or undefined value:
  82. /// "this is null because that is null because that is null" etc.
  83. /// We wipe away field and element offsets because they merely add offsets.
  84. /// We also wipe away all casts except lvalue-to-rvalue casts, because the
  85. /// latter represent an actual pointer dereference; however, we remove
  86. /// the final lvalue-to-rvalue cast before returning from this function
  87. /// because it demonstrates more clearly from where the pointer rvalue was
  88. /// loaded. Examples:
  89. /// x->y.z ==> x (lvalue)
  90. /// foo()->y.z ==> foo() (rvalue)
  91. const Expr *bugreporter::getDerefExpr(const Stmt *S) {
  92. const auto *E = dyn_cast<Expr>(S);
  93. if (!E)
  94. return nullptr;
  95. while (true) {
  96. if (const auto *CE = dyn_cast<CastExpr>(E)) {
  97. if (CE->getCastKind() == CK_LValueToRValue) {
  98. // This cast represents the load we're looking for.
  99. break;
  100. }
  101. E = CE->getSubExpr();
  102. } else if (const auto *B = dyn_cast<BinaryOperator>(E)) {
  103. // Pointer arithmetic: '*(x + 2)' -> 'x') etc.
  104. if (const Expr *Inner = peelOffPointerArithmetic(B)) {
  105. E = Inner;
  106. } else {
  107. // Probably more arithmetic can be pattern-matched here,
  108. // but for now give up.
  109. break;
  110. }
  111. } else if (const auto *U = dyn_cast<UnaryOperator>(E)) {
  112. if (U->getOpcode() == UO_Deref || U->getOpcode() == UO_AddrOf ||
  113. (U->isIncrementDecrementOp() && U->getType()->isPointerType())) {
  114. // Operators '*' and '&' don't actually mean anything.
  115. // We look at casts instead.
  116. E = U->getSubExpr();
  117. } else {
  118. // Probably more arithmetic can be pattern-matched here,
  119. // but for now give up.
  120. break;
  121. }
  122. }
  123. // Pattern match for a few useful cases: a[0], p->f, *p etc.
  124. else if (const auto *ME = dyn_cast<MemberExpr>(E)) {
  125. E = ME->getBase();
  126. } else if (const auto *IvarRef = dyn_cast<ObjCIvarRefExpr>(E)) {
  127. E = IvarRef->getBase();
  128. } else if (const auto *AE = dyn_cast<ArraySubscriptExpr>(E)) {
  129. E = AE->getBase();
  130. } else if (const auto *PE = dyn_cast<ParenExpr>(E)) {
  131. E = PE->getSubExpr();
  132. } else if (const auto *FE = dyn_cast<FullExpr>(E)) {
  133. E = FE->getSubExpr();
  134. } else {
  135. // Other arbitrary stuff.
  136. break;
  137. }
  138. }
  139. // Special case: remove the final lvalue-to-rvalue cast, but do not recurse
  140. // deeper into the sub-expression. This way we return the lvalue from which
  141. // our pointer rvalue was loaded.
  142. if (const auto *CE = dyn_cast<ImplicitCastExpr>(E))
  143. if (CE->getCastKind() == CK_LValueToRValue)
  144. E = CE->getSubExpr();
  145. return E;
  146. }
  147. /// Comparing internal representations of symbolic values (via
  148. /// SVal::operator==()) is a valid way to check if the value was updated,
  149. /// unless it's a LazyCompoundVal that may have a different internal
  150. /// representation every time it is loaded from the state. In this function we
  151. /// do an approximate comparison for lazy compound values, checking that they
  152. /// are the immediate snapshots of the tracked region's bindings within the
  153. /// node's respective states but not really checking that these snapshots
  154. /// actually contain the same set of bindings.
  155. static bool hasVisibleUpdate(const ExplodedNode *LeftNode, SVal LeftVal,
  156. const ExplodedNode *RightNode, SVal RightVal) {
  157. if (LeftVal == RightVal)
  158. return true;
  159. const auto LLCV = LeftVal.getAs<nonloc::LazyCompoundVal>();
  160. if (!LLCV)
  161. return false;
  162. const auto RLCV = RightVal.getAs<nonloc::LazyCompoundVal>();
  163. if (!RLCV)
  164. return false;
  165. return LLCV->getRegion() == RLCV->getRegion() &&
  166. LLCV->getStore() == LeftNode->getState()->getStore() &&
  167. RLCV->getStore() == RightNode->getState()->getStore();
  168. }
  169. //===----------------------------------------------------------------------===//
  170. // Definitions for bug reporter visitors.
  171. //===----------------------------------------------------------------------===//
  172. std::shared_ptr<PathDiagnosticPiece>
  173. BugReporterVisitor::getEndPath(BugReporterContext &,
  174. const ExplodedNode *, BugReport &) {
  175. return nullptr;
  176. }
  177. void
  178. BugReporterVisitor::finalizeVisitor(BugReporterContext &,
  179. const ExplodedNode *, BugReport &) {}
  180. std::shared_ptr<PathDiagnosticPiece> BugReporterVisitor::getDefaultEndPath(
  181. BugReporterContext &BRC, const ExplodedNode *EndPathNode, BugReport &BR) {
  182. PathDiagnosticLocation L =
  183. PathDiagnosticLocation::createEndOfPath(EndPathNode,BRC.getSourceManager());
  184. const auto &Ranges = BR.getRanges();
  185. // Only add the statement itself as a range if we didn't specify any
  186. // special ranges for this report.
  187. auto P = std::make_shared<PathDiagnosticEventPiece>(
  188. L, BR.getDescription(), Ranges.begin() == Ranges.end());
  189. for (SourceRange Range : Ranges)
  190. P->addRange(Range);
  191. return P;
  192. }
  193. /// \return name of the macro inside the location \p Loc.
  194. static StringRef getMacroName(SourceLocation Loc,
  195. BugReporterContext &BRC) {
  196. return Lexer::getImmediateMacroName(
  197. Loc,
  198. BRC.getSourceManager(),
  199. BRC.getASTContext().getLangOpts());
  200. }
  201. /// \return Whether given spelling location corresponds to an expansion
  202. /// of a function-like macro.
  203. static bool isFunctionMacroExpansion(SourceLocation Loc,
  204. const SourceManager &SM) {
  205. if (!Loc.isMacroID())
  206. return false;
  207. while (SM.isMacroArgExpansion(Loc))
  208. Loc = SM.getImmediateExpansionRange(Loc).getBegin();
  209. std::pair<FileID, unsigned> TLInfo = SM.getDecomposedLoc(Loc);
  210. SrcMgr::SLocEntry SE = SM.getSLocEntry(TLInfo.first);
  211. const SrcMgr::ExpansionInfo &EInfo = SE.getExpansion();
  212. return EInfo.isFunctionMacroExpansion();
  213. }
  214. /// \return Whether \c RegionOfInterest was modified at \p N,
  215. /// where \p ReturnState is a state associated with the return
  216. /// from the current frame.
  217. static bool wasRegionOfInterestModifiedAt(
  218. const SubRegion *RegionOfInterest,
  219. const ExplodedNode *N,
  220. SVal ValueAfter) {
  221. ProgramStateRef State = N->getState();
  222. ProgramStateManager &Mgr = N->getState()->getStateManager();
  223. if (!N->getLocationAs<PostStore>()
  224. && !N->getLocationAs<PostInitializer>()
  225. && !N->getLocationAs<PostStmt>())
  226. return false;
  227. // Writing into region of interest.
  228. if (auto PS = N->getLocationAs<PostStmt>())
  229. if (auto *BO = PS->getStmtAs<BinaryOperator>())
  230. if (BO->isAssignmentOp() && RegionOfInterest->isSubRegionOf(
  231. N->getSVal(BO->getLHS()).getAsRegion()))
  232. return true;
  233. // SVal after the state is possibly different.
  234. SVal ValueAtN = N->getState()->getSVal(RegionOfInterest);
  235. if (!Mgr.getSValBuilder().areEqual(State, ValueAtN, ValueAfter).isConstrainedTrue() &&
  236. (!ValueAtN.isUndef() || !ValueAfter.isUndef()))
  237. return true;
  238. return false;
  239. }
  240. namespace {
  241. /// Put a diagnostic on return statement of all inlined functions
  242. /// for which the region of interest \p RegionOfInterest was passed into,
  243. /// but not written inside, and it has caused an undefined read or a null
  244. /// pointer dereference outside.
  245. class NoStoreFuncVisitor final : public BugReporterVisitor {
  246. const SubRegion *RegionOfInterest;
  247. MemRegionManager &MmrMgr;
  248. const SourceManager &SM;
  249. const PrintingPolicy &PP;
  250. /// Recursion limit for dereferencing fields when looking for the
  251. /// region of interest.
  252. /// The limit of two indicates that we will dereference fields only once.
  253. static const unsigned DEREFERENCE_LIMIT = 2;
  254. /// Frames writing into \c RegionOfInterest.
  255. /// This visitor generates a note only if a function does not write into
  256. /// a region of interest. This information is not immediately available
  257. /// by looking at the node associated with the exit from the function
  258. /// (usually the return statement). To avoid recomputing the same information
  259. /// many times (going up the path for each node and checking whether the
  260. /// region was written into) we instead lazily compute the
  261. /// stack frames along the path which write into the region of interest.
  262. llvm::SmallPtrSet<const StackFrameContext *, 32> FramesModifyingRegion;
  263. llvm::SmallPtrSet<const StackFrameContext *, 32> FramesModifyingCalculated;
  264. using RegionVector = SmallVector<const MemRegion *, 5>;
  265. public:
  266. NoStoreFuncVisitor(const SubRegion *R)
  267. : RegionOfInterest(R), MmrMgr(*R->getMemRegionManager()),
  268. SM(MmrMgr.getContext().getSourceManager()),
  269. PP(MmrMgr.getContext().getPrintingPolicy()) {}
  270. void Profile(llvm::FoldingSetNodeID &ID) const override {
  271. static int Tag = 0;
  272. ID.AddPointer(&Tag);
  273. ID.AddPointer(RegionOfInterest);
  274. }
  275. std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *N,
  276. BugReporterContext &BR,
  277. BugReport &) override {
  278. const LocationContext *Ctx = N->getLocationContext();
  279. const StackFrameContext *SCtx = Ctx->getStackFrame();
  280. ProgramStateRef State = N->getState();
  281. auto CallExitLoc = N->getLocationAs<CallExitBegin>();
  282. // No diagnostic if region was modified inside the frame.
  283. if (!CallExitLoc || isRegionOfInterestModifiedInFrame(N))
  284. return nullptr;
  285. CallEventRef<> Call =
  286. BR.getStateManager().getCallEventManager().getCaller(SCtx, State);
  287. if (SM.isInSystemHeader(Call->getDecl()->getSourceRange().getBegin()))
  288. return nullptr;
  289. // Region of interest corresponds to an IVar, exiting a method
  290. // which could have written into that IVar, but did not.
  291. if (const auto *MC = dyn_cast<ObjCMethodCall>(Call)) {
  292. if (const auto *IvarR = dyn_cast<ObjCIvarRegion>(RegionOfInterest)) {
  293. const MemRegion *SelfRegion = MC->getReceiverSVal().getAsRegion();
  294. if (RegionOfInterest->isSubRegionOf(SelfRegion) &&
  295. potentiallyWritesIntoIvar(Call->getRuntimeDefinition().getDecl(),
  296. IvarR->getDecl()))
  297. return notModifiedDiagnostics(N, {}, SelfRegion, "self",
  298. /*FirstIsReferenceType=*/false, 1);
  299. }
  300. }
  301. if (const auto *CCall = dyn_cast<CXXConstructorCall>(Call)) {
  302. const MemRegion *ThisR = CCall->getCXXThisVal().getAsRegion();
  303. if (RegionOfInterest->isSubRegionOf(ThisR)
  304. && !CCall->getDecl()->isImplicit())
  305. return notModifiedDiagnostics(N, {}, ThisR, "this",
  306. /*FirstIsReferenceType=*/false, 1);
  307. // Do not generate diagnostics for not modified parameters in
  308. // constructors.
  309. return nullptr;
  310. }
  311. ArrayRef<ParmVarDecl *> parameters = getCallParameters(Call);
  312. for (unsigned I = 0; I < Call->getNumArgs() && I < parameters.size(); ++I) {
  313. const ParmVarDecl *PVD = parameters[I];
  314. SVal S = Call->getArgSVal(I);
  315. bool ParamIsReferenceType = PVD->getType()->isReferenceType();
  316. std::string ParamName = PVD->getNameAsString();
  317. int IndirectionLevel = 1;
  318. QualType T = PVD->getType();
  319. while (const MemRegion *R = S.getAsRegion()) {
  320. if (RegionOfInterest->isSubRegionOf(R) && !isPointerToConst(T))
  321. return notModifiedDiagnostics(N, {}, R, ParamName,
  322. ParamIsReferenceType, IndirectionLevel);
  323. QualType PT = T->getPointeeType();
  324. if (PT.isNull() || PT->isVoidType()) break;
  325. if (const RecordDecl *RD = PT->getAsRecordDecl())
  326. if (auto P = findRegionOfInterestInRecord(RD, State, R))
  327. return notModifiedDiagnostics(N, *P, RegionOfInterest, ParamName,
  328. ParamIsReferenceType,
  329. IndirectionLevel);
  330. S = State->getSVal(R, PT);
  331. T = PT;
  332. IndirectionLevel++;
  333. }
  334. }
  335. return nullptr;
  336. }
  337. private:
  338. /// Attempts to find the region of interest in a given CXX decl,
  339. /// by either following the base classes or fields.
  340. /// Dereferences fields up to a given recursion limit.
  341. /// Note that \p Vec is passed by value, leading to quadratic copying cost,
  342. /// but it's OK in practice since its length is limited to DEREFERENCE_LIMIT.
  343. /// \return A chain fields leading to the region of interest or None.
  344. const Optional<RegionVector>
  345. findRegionOfInterestInRecord(const RecordDecl *RD, ProgramStateRef State,
  346. const MemRegion *R,
  347. const RegionVector &Vec = {},
  348. int depth = 0) {
  349. if (depth == DEREFERENCE_LIMIT) // Limit the recursion depth.
  350. return None;
  351. if (const auto *RDX = dyn_cast<CXXRecordDecl>(RD))
  352. if (!RDX->hasDefinition())
  353. return None;
  354. // Recursively examine the base classes.
  355. // Note that following base classes does not increase the recursion depth.
  356. if (const auto *RDX = dyn_cast<CXXRecordDecl>(RD))
  357. for (const auto II : RDX->bases())
  358. if (const RecordDecl *RRD = II.getType()->getAsRecordDecl())
  359. if (auto Out = findRegionOfInterestInRecord(RRD, State, R, Vec, depth))
  360. return Out;
  361. for (const FieldDecl *I : RD->fields()) {
  362. QualType FT = I->getType();
  363. const FieldRegion *FR = MmrMgr.getFieldRegion(I, cast<SubRegion>(R));
  364. const SVal V = State->getSVal(FR);
  365. const MemRegion *VR = V.getAsRegion();
  366. RegionVector VecF = Vec;
  367. VecF.push_back(FR);
  368. if (RegionOfInterest == VR)
  369. return VecF;
  370. if (const RecordDecl *RRD = FT->getAsRecordDecl())
  371. if (auto Out =
  372. findRegionOfInterestInRecord(RRD, State, FR, VecF, depth + 1))
  373. return Out;
  374. QualType PT = FT->getPointeeType();
  375. if (PT.isNull() || PT->isVoidType() || !VR) continue;
  376. if (const RecordDecl *RRD = PT->getAsRecordDecl())
  377. if (auto Out =
  378. findRegionOfInterestInRecord(RRD, State, VR, VecF, depth + 1))
  379. return Out;
  380. }
  381. return None;
  382. }
  383. /// \return Whether the method declaration \p Parent
  384. /// syntactically has a binary operation writing into the ivar \p Ivar.
  385. bool potentiallyWritesIntoIvar(const Decl *Parent,
  386. const ObjCIvarDecl *Ivar) {
  387. using namespace ast_matchers;
  388. const char * IvarBind = "Ivar";
  389. if (!Parent || !Parent->hasBody())
  390. return false;
  391. StatementMatcher WriteIntoIvarM = binaryOperator(
  392. hasOperatorName("="),
  393. hasLHS(ignoringParenImpCasts(
  394. objcIvarRefExpr(hasDeclaration(equalsNode(Ivar))).bind(IvarBind))));
  395. StatementMatcher ParentM = stmt(hasDescendant(WriteIntoIvarM));
  396. auto Matches = match(ParentM, *Parent->getBody(), Parent->getASTContext());
  397. for (BoundNodes &Match : Matches) {
  398. auto IvarRef = Match.getNodeAs<ObjCIvarRefExpr>(IvarBind);
  399. if (IvarRef->isFreeIvar())
  400. return true;
  401. const Expr *Base = IvarRef->getBase();
  402. if (const auto *ICE = dyn_cast<ImplicitCastExpr>(Base))
  403. Base = ICE->getSubExpr();
  404. if (const auto *DRE = dyn_cast<DeclRefExpr>(Base))
  405. if (const auto *ID = dyn_cast<ImplicitParamDecl>(DRE->getDecl()))
  406. if (ID->getParameterKind() == ImplicitParamDecl::ObjCSelf)
  407. return true;
  408. return false;
  409. }
  410. return false;
  411. }
  412. /// Check and lazily calculate whether the region of interest is
  413. /// modified in the stack frame to which \p N belongs.
  414. /// The calculation is cached in FramesModifyingRegion.
  415. bool isRegionOfInterestModifiedInFrame(const ExplodedNode *N) {
  416. const LocationContext *Ctx = N->getLocationContext();
  417. const StackFrameContext *SCtx = Ctx->getStackFrame();
  418. if (!FramesModifyingCalculated.count(SCtx))
  419. findModifyingFrames(N);
  420. return FramesModifyingRegion.count(SCtx);
  421. }
  422. /// Write to \c FramesModifyingRegion all stack frames along
  423. /// the path in the current stack frame which modify \c RegionOfInterest.
  424. void findModifyingFrames(const ExplodedNode *N) {
  425. assert(N->getLocationAs<CallExitBegin>());
  426. ProgramStateRef LastReturnState = N->getState();
  427. SVal ValueAtReturn = LastReturnState->getSVal(RegionOfInterest);
  428. const LocationContext *Ctx = N->getLocationContext();
  429. const StackFrameContext *OriginalSCtx = Ctx->getStackFrame();
  430. do {
  431. ProgramStateRef State = N->getState();
  432. auto CallExitLoc = N->getLocationAs<CallExitBegin>();
  433. if (CallExitLoc) {
  434. LastReturnState = State;
  435. ValueAtReturn = LastReturnState->getSVal(RegionOfInterest);
  436. }
  437. FramesModifyingCalculated.insert(
  438. N->getLocationContext()->getStackFrame());
  439. if (wasRegionOfInterestModifiedAt(RegionOfInterest, N, ValueAtReturn)) {
  440. const StackFrameContext *SCtx = N->getStackFrame();
  441. while (!SCtx->inTopFrame()) {
  442. auto p = FramesModifyingRegion.insert(SCtx);
  443. if (!p.second)
  444. break; // Frame and all its parents already inserted.
  445. SCtx = SCtx->getParent()->getStackFrame();
  446. }
  447. }
  448. // Stop calculation at the call to the current function.
  449. if (auto CE = N->getLocationAs<CallEnter>())
  450. if (CE->getCalleeContext() == OriginalSCtx)
  451. break;
  452. N = N->getFirstPred();
  453. } while (N);
  454. }
  455. /// Get parameters associated with runtime definition in order
  456. /// to get the correct parameter name.
  457. ArrayRef<ParmVarDecl *> getCallParameters(CallEventRef<> Call) {
  458. // Use runtime definition, if available.
  459. RuntimeDefinition RD = Call->getRuntimeDefinition();
  460. if (const auto *FD = dyn_cast_or_null<FunctionDecl>(RD.getDecl()))
  461. return FD->parameters();
  462. if (const auto *MD = dyn_cast_or_null<ObjCMethodDecl>(RD.getDecl()))
  463. return MD->parameters();
  464. return Call->parameters();
  465. }
  466. /// \return whether \p Ty points to a const type, or is a const reference.
  467. bool isPointerToConst(QualType Ty) {
  468. return !Ty->getPointeeType().isNull() &&
  469. Ty->getPointeeType().getCanonicalType().isConstQualified();
  470. }
  471. /// \return Diagnostics piece for region not modified in the current function.
  472. std::shared_ptr<PathDiagnosticPiece>
  473. notModifiedDiagnostics(const ExplodedNode *N, const RegionVector &FieldChain,
  474. const MemRegion *MatchedRegion, StringRef FirstElement,
  475. bool FirstIsReferenceType, unsigned IndirectionLevel) {
  476. PathDiagnosticLocation L =
  477. PathDiagnosticLocation::create(N->getLocation(), SM);
  478. SmallString<256> sbuf;
  479. llvm::raw_svector_ostream os(sbuf);
  480. os << "Returning without writing to '";
  481. // Do not generate the note if failed to pretty-print.
  482. if (!prettyPrintRegionName(FirstElement, FirstIsReferenceType,
  483. MatchedRegion, FieldChain, IndirectionLevel, os))
  484. return nullptr;
  485. os << "'";
  486. return std::make_shared<PathDiagnosticEventPiece>(L, os.str());
  487. }
  488. /// Pretty-print region \p MatchedRegion to \p os.
  489. /// \return Whether printing succeeded.
  490. bool prettyPrintRegionName(StringRef FirstElement, bool FirstIsReferenceType,
  491. const MemRegion *MatchedRegion,
  492. const RegionVector &FieldChain,
  493. int IndirectionLevel,
  494. llvm::raw_svector_ostream &os) {
  495. if (FirstIsReferenceType)
  496. IndirectionLevel--;
  497. RegionVector RegionSequence;
  498. // Add the regions in the reverse order, then reverse the resulting array.
  499. assert(RegionOfInterest->isSubRegionOf(MatchedRegion));
  500. const MemRegion *R = RegionOfInterest;
  501. while (R != MatchedRegion) {
  502. RegionSequence.push_back(R);
  503. R = cast<SubRegion>(R)->getSuperRegion();
  504. }
  505. std::reverse(RegionSequence.begin(), RegionSequence.end());
  506. RegionSequence.append(FieldChain.begin(), FieldChain.end());
  507. StringRef Sep;
  508. for (const MemRegion *R : RegionSequence) {
  509. // Just keep going up to the base region.
  510. // Element regions may appear due to casts.
  511. if (isa<CXXBaseObjectRegion>(R) || isa<CXXTempObjectRegion>(R))
  512. continue;
  513. if (Sep.empty())
  514. Sep = prettyPrintFirstElement(FirstElement,
  515. /*MoreItemsExpected=*/true,
  516. IndirectionLevel, os);
  517. os << Sep;
  518. // Can only reasonably pretty-print DeclRegions.
  519. if (!isa<DeclRegion>(R))
  520. return false;
  521. const auto *DR = cast<DeclRegion>(R);
  522. Sep = DR->getValueType()->isAnyPointerType() ? "->" : ".";
  523. DR->getDecl()->getDeclName().print(os, PP);
  524. }
  525. if (Sep.empty())
  526. prettyPrintFirstElement(FirstElement,
  527. /*MoreItemsExpected=*/false, IndirectionLevel,
  528. os);
  529. return true;
  530. }
  531. /// Print first item in the chain, return new separator.
  532. StringRef prettyPrintFirstElement(StringRef FirstElement,
  533. bool MoreItemsExpected,
  534. int IndirectionLevel,
  535. llvm::raw_svector_ostream &os) {
  536. StringRef Out = ".";
  537. if (IndirectionLevel > 0 && MoreItemsExpected) {
  538. IndirectionLevel--;
  539. Out = "->";
  540. }
  541. if (IndirectionLevel > 0 && MoreItemsExpected)
  542. os << "(";
  543. for (int i=0; i<IndirectionLevel; i++)
  544. os << "*";
  545. os << FirstElement;
  546. if (IndirectionLevel > 0 && MoreItemsExpected)
  547. os << ")";
  548. return Out;
  549. }
  550. };
  551. /// Suppress null-pointer-dereference bugs where dereferenced null was returned
  552. /// the macro.
  553. class MacroNullReturnSuppressionVisitor final : public BugReporterVisitor {
  554. const SubRegion *RegionOfInterest;
  555. const SVal ValueAtDereference;
  556. // Do not invalidate the reports where the value was modified
  557. // after it got assigned to from the macro.
  558. bool WasModified = false;
  559. public:
  560. MacroNullReturnSuppressionVisitor(const SubRegion *R,
  561. const SVal V) : RegionOfInterest(R),
  562. ValueAtDereference(V) {}
  563. std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *N,
  564. BugReporterContext &BRC,
  565. BugReport &BR) override {
  566. if (WasModified)
  567. return nullptr;
  568. auto BugPoint = BR.getErrorNode()->getLocation().getAs<StmtPoint>();
  569. if (!BugPoint)
  570. return nullptr;
  571. const SourceManager &SMgr = BRC.getSourceManager();
  572. if (auto Loc = matchAssignment(N)) {
  573. if (isFunctionMacroExpansion(*Loc, SMgr)) {
  574. std::string MacroName = getMacroName(*Loc, BRC);
  575. SourceLocation BugLoc = BugPoint->getStmt()->getBeginLoc();
  576. if (!BugLoc.isMacroID() || getMacroName(BugLoc, BRC) != MacroName)
  577. BR.markInvalid(getTag(), MacroName.c_str());
  578. }
  579. }
  580. if (wasRegionOfInterestModifiedAt(RegionOfInterest, N, ValueAtDereference))
  581. WasModified = true;
  582. return nullptr;
  583. }
  584. static void addMacroVisitorIfNecessary(
  585. const ExplodedNode *N, const MemRegion *R,
  586. bool EnableNullFPSuppression, BugReport &BR,
  587. const SVal V) {
  588. AnalyzerOptions &Options = N->getState()->getAnalysisManager().options;
  589. if (EnableNullFPSuppression &&
  590. Options.ShouldSuppressNullReturnPaths && V.getAs<Loc>())
  591. BR.addVisitor(llvm::make_unique<MacroNullReturnSuppressionVisitor>(
  592. R->getAs<SubRegion>(), V));
  593. }
  594. void* getTag() const {
  595. static int Tag = 0;
  596. return static_cast<void *>(&Tag);
  597. }
  598. void Profile(llvm::FoldingSetNodeID &ID) const override {
  599. ID.AddPointer(getTag());
  600. }
  601. private:
  602. /// \return Source location of right hand side of an assignment
  603. /// into \c RegionOfInterest, empty optional if none found.
  604. Optional<SourceLocation> matchAssignment(const ExplodedNode *N) {
  605. const Stmt *S = PathDiagnosticLocation::getStmt(N);
  606. ProgramStateRef State = N->getState();
  607. auto *LCtx = N->getLocationContext();
  608. if (!S)
  609. return None;
  610. if (const auto *DS = dyn_cast<DeclStmt>(S)) {
  611. if (const auto *VD = dyn_cast<VarDecl>(DS->getSingleDecl()))
  612. if (const Expr *RHS = VD->getInit())
  613. if (RegionOfInterest->isSubRegionOf(
  614. State->getLValue(VD, LCtx).getAsRegion()))
  615. return RHS->getBeginLoc();
  616. } else if (const auto *BO = dyn_cast<BinaryOperator>(S)) {
  617. const MemRegion *R = N->getSVal(BO->getLHS()).getAsRegion();
  618. const Expr *RHS = BO->getRHS();
  619. if (BO->isAssignmentOp() && RegionOfInterest->isSubRegionOf(R)) {
  620. return RHS->getBeginLoc();
  621. }
  622. }
  623. return None;
  624. }
  625. };
  626. /// Emits an extra note at the return statement of an interesting stack frame.
  627. ///
  628. /// The returned value is marked as an interesting value, and if it's null,
  629. /// adds a visitor to track where it became null.
  630. ///
  631. /// This visitor is intended to be used when another visitor discovers that an
  632. /// interesting value comes from an inlined function call.
  633. class ReturnVisitor : public BugReporterVisitor {
  634. const StackFrameContext *StackFrame;
  635. enum {
  636. Initial,
  637. MaybeUnsuppress,
  638. Satisfied
  639. } Mode = Initial;
  640. bool EnableNullFPSuppression;
  641. bool ShouldInvalidate = true;
  642. AnalyzerOptions& Options;
  643. public:
  644. ReturnVisitor(const StackFrameContext *Frame,
  645. bool Suppressed,
  646. AnalyzerOptions &Options)
  647. : StackFrame(Frame), EnableNullFPSuppression(Suppressed),
  648. Options(Options) {}
  649. static void *getTag() {
  650. static int Tag = 0;
  651. return static_cast<void *>(&Tag);
  652. }
  653. void Profile(llvm::FoldingSetNodeID &ID) const override {
  654. ID.AddPointer(ReturnVisitor::getTag());
  655. ID.AddPointer(StackFrame);
  656. ID.AddBoolean(EnableNullFPSuppression);
  657. }
  658. /// Adds a ReturnVisitor if the given statement represents a call that was
  659. /// inlined.
  660. ///
  661. /// This will search back through the ExplodedGraph, starting from the given
  662. /// node, looking for when the given statement was processed. If it turns out
  663. /// the statement is a call that was inlined, we add the visitor to the
  664. /// bug report, so it can print a note later.
  665. static void addVisitorIfNecessary(const ExplodedNode *Node, const Stmt *S,
  666. BugReport &BR,
  667. bool InEnableNullFPSuppression) {
  668. if (!CallEvent::isCallStmt(S))
  669. return;
  670. // First, find when we processed the statement.
  671. do {
  672. if (auto CEE = Node->getLocationAs<CallExitEnd>())
  673. if (CEE->getCalleeContext()->getCallSite() == S)
  674. break;
  675. if (auto SP = Node->getLocationAs<StmtPoint>())
  676. if (SP->getStmt() == S)
  677. break;
  678. Node = Node->getFirstPred();
  679. } while (Node);
  680. // Next, step over any post-statement checks.
  681. while (Node && Node->getLocation().getAs<PostStmt>())
  682. Node = Node->getFirstPred();
  683. if (!Node)
  684. return;
  685. // Finally, see if we inlined the call.
  686. Optional<CallExitEnd> CEE = Node->getLocationAs<CallExitEnd>();
  687. if (!CEE)
  688. return;
  689. const StackFrameContext *CalleeContext = CEE->getCalleeContext();
  690. if (CalleeContext->getCallSite() != S)
  691. return;
  692. // Check the return value.
  693. ProgramStateRef State = Node->getState();
  694. SVal RetVal = Node->getSVal(S);
  695. // Handle cases where a reference is returned and then immediately used.
  696. if (cast<Expr>(S)->isGLValue())
  697. if (Optional<Loc> LValue = RetVal.getAs<Loc>())
  698. RetVal = State->getSVal(*LValue);
  699. // See if the return value is NULL. If so, suppress the report.
  700. AnalyzerOptions &Options = State->getAnalysisManager().options;
  701. bool EnableNullFPSuppression = false;
  702. if (InEnableNullFPSuppression &&
  703. Options.ShouldSuppressNullReturnPaths)
  704. if (Optional<Loc> RetLoc = RetVal.getAs<Loc>())
  705. EnableNullFPSuppression = State->isNull(*RetLoc).isConstrainedTrue();
  706. BR.markInteresting(CalleeContext);
  707. BR.addVisitor(llvm::make_unique<ReturnVisitor>(CalleeContext,
  708. EnableNullFPSuppression,
  709. Options));
  710. }
  711. std::shared_ptr<PathDiagnosticPiece>
  712. visitNodeInitial(const ExplodedNode *N,
  713. BugReporterContext &BRC, BugReport &BR) {
  714. // Only print a message at the interesting return statement.
  715. if (N->getLocationContext() != StackFrame)
  716. return nullptr;
  717. Optional<StmtPoint> SP = N->getLocationAs<StmtPoint>();
  718. if (!SP)
  719. return nullptr;
  720. const auto *Ret = dyn_cast<ReturnStmt>(SP->getStmt());
  721. if (!Ret)
  722. return nullptr;
  723. // Okay, we're at the right return statement, but do we have the return
  724. // value available?
  725. ProgramStateRef State = N->getState();
  726. SVal V = State->getSVal(Ret, StackFrame);
  727. if (V.isUnknownOrUndef())
  728. return nullptr;
  729. // Don't print any more notes after this one.
  730. Mode = Satisfied;
  731. const Expr *RetE = Ret->getRetValue();
  732. assert(RetE && "Tracking a return value for a void function");
  733. // Handle cases where a reference is returned and then immediately used.
  734. Optional<Loc> LValue;
  735. if (RetE->isGLValue()) {
  736. if ((LValue = V.getAs<Loc>())) {
  737. SVal RValue = State->getRawSVal(*LValue, RetE->getType());
  738. if (RValue.getAs<DefinedSVal>())
  739. V = RValue;
  740. }
  741. }
  742. // Ignore aggregate rvalues.
  743. if (V.getAs<nonloc::LazyCompoundVal>() ||
  744. V.getAs<nonloc::CompoundVal>())
  745. return nullptr;
  746. RetE = RetE->IgnoreParenCasts();
  747. // If we're returning 0, we should track where that 0 came from.
  748. bugreporter::trackExpressionValue(N, RetE, BR, EnableNullFPSuppression);
  749. // Build an appropriate message based on the return value.
  750. SmallString<64> Msg;
  751. llvm::raw_svector_ostream Out(Msg);
  752. if (State->isNull(V).isConstrainedTrue()) {
  753. if (V.getAs<Loc>()) {
  754. // If we have counter-suppression enabled, make sure we keep visiting
  755. // future nodes. We want to emit a path note as well, in case
  756. // the report is resurrected as valid later on.
  757. if (EnableNullFPSuppression &&
  758. Options.ShouldAvoidSuppressingNullArgumentPaths)
  759. Mode = MaybeUnsuppress;
  760. if (RetE->getType()->isObjCObjectPointerType()) {
  761. Out << "Returning nil";
  762. } else {
  763. Out << "Returning null pointer";
  764. }
  765. } else {
  766. Out << "Returning zero";
  767. }
  768. } else {
  769. if (auto CI = V.getAs<nonloc::ConcreteInt>()) {
  770. Out << "Returning the value " << CI->getValue();
  771. } else if (V.getAs<Loc>()) {
  772. Out << "Returning pointer";
  773. } else {
  774. Out << "Returning value";
  775. }
  776. }
  777. if (LValue) {
  778. if (const MemRegion *MR = LValue->getAsRegion()) {
  779. if (MR->canPrintPretty()) {
  780. Out << " (reference to ";
  781. MR->printPretty(Out);
  782. Out << ")";
  783. }
  784. }
  785. } else {
  786. // FIXME: We should have a more generalized location printing mechanism.
  787. if (const auto *DR = dyn_cast<DeclRefExpr>(RetE))
  788. if (const auto *DD = dyn_cast<DeclaratorDecl>(DR->getDecl()))
  789. Out << " (loaded from '" << *DD << "')";
  790. }
  791. PathDiagnosticLocation L(Ret, BRC.getSourceManager(), StackFrame);
  792. if (!L.isValid() || !L.asLocation().isValid())
  793. return nullptr;
  794. return std::make_shared<PathDiagnosticEventPiece>(L, Out.str());
  795. }
  796. std::shared_ptr<PathDiagnosticPiece>
  797. visitNodeMaybeUnsuppress(const ExplodedNode *N,
  798. BugReporterContext &BRC, BugReport &BR) {
  799. #ifndef NDEBUG
  800. assert(Options.ShouldAvoidSuppressingNullArgumentPaths);
  801. #endif
  802. // Are we at the entry node for this call?
  803. Optional<CallEnter> CE = N->getLocationAs<CallEnter>();
  804. if (!CE)
  805. return nullptr;
  806. if (CE->getCalleeContext() != StackFrame)
  807. return nullptr;
  808. Mode = Satisfied;
  809. // Don't automatically suppress a report if one of the arguments is
  810. // known to be a null pointer. Instead, start tracking /that/ null
  811. // value back to its origin.
  812. ProgramStateManager &StateMgr = BRC.getStateManager();
  813. CallEventManager &CallMgr = StateMgr.getCallEventManager();
  814. ProgramStateRef State = N->getState();
  815. CallEventRef<> Call = CallMgr.getCaller(StackFrame, State);
  816. for (unsigned I = 0, E = Call->getNumArgs(); I != E; ++I) {
  817. Optional<Loc> ArgV = Call->getArgSVal(I).getAs<Loc>();
  818. if (!ArgV)
  819. continue;
  820. const Expr *ArgE = Call->getArgExpr(I);
  821. if (!ArgE)
  822. continue;
  823. // Is it possible for this argument to be non-null?
  824. if (!State->isNull(*ArgV).isConstrainedTrue())
  825. continue;
  826. if (bugreporter::trackExpressionValue(N, ArgE, BR, EnableNullFPSuppression))
  827. ShouldInvalidate = false;
  828. // If we /can't/ track the null pointer, we should err on the side of
  829. // false negatives, and continue towards marking this report invalid.
  830. // (We will still look at the other arguments, though.)
  831. }
  832. return nullptr;
  833. }
  834. std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *N,
  835. BugReporterContext &BRC,
  836. BugReport &BR) override {
  837. switch (Mode) {
  838. case Initial:
  839. return visitNodeInitial(N, BRC, BR);
  840. case MaybeUnsuppress:
  841. return visitNodeMaybeUnsuppress(N, BRC, BR);
  842. case Satisfied:
  843. return nullptr;
  844. }
  845. llvm_unreachable("Invalid visit mode!");
  846. }
  847. void finalizeVisitor(BugReporterContext &, const ExplodedNode *,
  848. BugReport &BR) override {
  849. if (EnableNullFPSuppression && ShouldInvalidate)
  850. BR.markInvalid(ReturnVisitor::getTag(), StackFrame);
  851. }
  852. };
  853. } // namespace
  854. void FindLastStoreBRVisitor::Profile(llvm::FoldingSetNodeID &ID) const {
  855. static int tag = 0;
  856. ID.AddPointer(&tag);
  857. ID.AddPointer(R);
  858. ID.Add(V);
  859. ID.AddBoolean(EnableNullFPSuppression);
  860. }
  861. /// Returns true if \p N represents the DeclStmt declaring and initializing
  862. /// \p VR.
  863. static bool isInitializationOfVar(const ExplodedNode *N, const VarRegion *VR) {
  864. Optional<PostStmt> P = N->getLocationAs<PostStmt>();
  865. if (!P)
  866. return false;
  867. const DeclStmt *DS = P->getStmtAs<DeclStmt>();
  868. if (!DS)
  869. return false;
  870. if (DS->getSingleDecl() != VR->getDecl())
  871. return false;
  872. const MemSpaceRegion *VarSpace = VR->getMemorySpace();
  873. const auto *FrameSpace = dyn_cast<StackSpaceRegion>(VarSpace);
  874. if (!FrameSpace) {
  875. // If we ever directly evaluate global DeclStmts, this assertion will be
  876. // invalid, but this still seems preferable to silently accepting an
  877. // initialization that may be for a path-sensitive variable.
  878. assert(VR->getDecl()->isStaticLocal() && "non-static stackless VarRegion");
  879. return true;
  880. }
  881. assert(VR->getDecl()->hasLocalStorage());
  882. const LocationContext *LCtx = N->getLocationContext();
  883. return FrameSpace->getStackFrame() == LCtx->getStackFrame();
  884. }
  885. /// Show diagnostics for initializing or declaring a region \p R with a bad value.
  886. static void showBRDiagnostics(const char *action, llvm::raw_svector_ostream &os,
  887. const MemRegion *R, SVal V, const DeclStmt *DS) {
  888. if (R->canPrintPretty()) {
  889. R->printPretty(os);
  890. os << " ";
  891. }
  892. if (V.getAs<loc::ConcreteInt>()) {
  893. bool b = false;
  894. if (R->isBoundable()) {
  895. if (const auto *TR = dyn_cast<TypedValueRegion>(R)) {
  896. if (TR->getValueType()->isObjCObjectPointerType()) {
  897. os << action << "nil";
  898. b = true;
  899. }
  900. }
  901. }
  902. if (!b)
  903. os << action << "a null pointer value";
  904. } else if (auto CVal = V.getAs<nonloc::ConcreteInt>()) {
  905. os << action << CVal->getValue();
  906. } else if (DS) {
  907. if (V.isUndef()) {
  908. if (isa<VarRegion>(R)) {
  909. const auto *VD = cast<VarDecl>(DS->getSingleDecl());
  910. if (VD->getInit()) {
  911. os << (R->canPrintPretty() ? "initialized" : "Initializing")
  912. << " to a garbage value";
  913. } else {
  914. os << (R->canPrintPretty() ? "declared" : "Declaring")
  915. << " without an initial value";
  916. }
  917. }
  918. } else {
  919. os << (R->canPrintPretty() ? "initialized" : "Initialized")
  920. << " here";
  921. }
  922. }
  923. }
  924. /// Display diagnostics for passing bad region as a parameter.
  925. static void showBRParamDiagnostics(llvm::raw_svector_ostream& os,
  926. const VarRegion *VR,
  927. SVal V) {
  928. const auto *Param = cast<ParmVarDecl>(VR->getDecl());
  929. os << "Passing ";
  930. if (V.getAs<loc::ConcreteInt>()) {
  931. if (Param->getType()->isObjCObjectPointerType())
  932. os << "nil object reference";
  933. else
  934. os << "null pointer value";
  935. } else if (V.isUndef()) {
  936. os << "uninitialized value";
  937. } else if (auto CI = V.getAs<nonloc::ConcreteInt>()) {
  938. os << "the value " << CI->getValue();
  939. } else {
  940. os << "value";
  941. }
  942. // Printed parameter indexes are 1-based, not 0-based.
  943. unsigned Idx = Param->getFunctionScopeIndex() + 1;
  944. os << " via " << Idx << llvm::getOrdinalSuffix(Idx) << " parameter";
  945. if (VR->canPrintPretty()) {
  946. os << " ";
  947. VR->printPretty(os);
  948. }
  949. }
  950. /// Show default diagnostics for storing bad region.
  951. static void showBRDefaultDiagnostics(llvm::raw_svector_ostream& os,
  952. const MemRegion *R,
  953. SVal V) {
  954. if (V.getAs<loc::ConcreteInt>()) {
  955. bool b = false;
  956. if (R->isBoundable()) {
  957. if (const auto *TR = dyn_cast<TypedValueRegion>(R)) {
  958. if (TR->getValueType()->isObjCObjectPointerType()) {
  959. os << "nil object reference stored";
  960. b = true;
  961. }
  962. }
  963. }
  964. if (!b) {
  965. if (R->canPrintPretty())
  966. os << "Null pointer value stored";
  967. else
  968. os << "Storing null pointer value";
  969. }
  970. } else if (V.isUndef()) {
  971. if (R->canPrintPretty())
  972. os << "Uninitialized value stored";
  973. else
  974. os << "Storing uninitialized value";
  975. } else if (auto CV = V.getAs<nonloc::ConcreteInt>()) {
  976. if (R->canPrintPretty())
  977. os << "The value " << CV->getValue() << " is assigned";
  978. else
  979. os << "Assigning " << CV->getValue();
  980. } else {
  981. if (R->canPrintPretty())
  982. os << "Value assigned";
  983. else
  984. os << "Assigning value";
  985. }
  986. if (R->canPrintPretty()) {
  987. os << " to ";
  988. R->printPretty(os);
  989. }
  990. }
  991. std::shared_ptr<PathDiagnosticPiece>
  992. FindLastStoreBRVisitor::VisitNode(const ExplodedNode *Succ,
  993. BugReporterContext &BRC, BugReport &BR) {
  994. if (Satisfied)
  995. return nullptr;
  996. const ExplodedNode *StoreSite = nullptr;
  997. const ExplodedNode *Pred = Succ->getFirstPred();
  998. const Expr *InitE = nullptr;
  999. bool IsParam = false;
  1000. // First see if we reached the declaration of the region.
  1001. if (const auto *VR = dyn_cast<VarRegion>(R)) {
  1002. if (isInitializationOfVar(Pred, VR)) {
  1003. StoreSite = Pred;
  1004. InitE = VR->getDecl()->getInit();
  1005. }
  1006. }
  1007. // If this is a post initializer expression, initializing the region, we
  1008. // should track the initializer expression.
  1009. if (Optional<PostInitializer> PIP = Pred->getLocationAs<PostInitializer>()) {
  1010. const MemRegion *FieldReg = (const MemRegion *)PIP->getLocationValue();
  1011. if (FieldReg && FieldReg == R) {
  1012. StoreSite = Pred;
  1013. InitE = PIP->getInitializer()->getInit();
  1014. }
  1015. }
  1016. // Otherwise, see if this is the store site:
  1017. // (1) Succ has this binding and Pred does not, i.e. this is
  1018. // where the binding first occurred.
  1019. // (2) Succ has this binding and is a PostStore node for this region, i.e.
  1020. // the same binding was re-assigned here.
  1021. if (!StoreSite) {
  1022. if (Succ->getState()->getSVal(R) != V)
  1023. return nullptr;
  1024. if (hasVisibleUpdate(Pred, Pred->getState()->getSVal(R), Succ, V)) {
  1025. Optional<PostStore> PS = Succ->getLocationAs<PostStore>();
  1026. if (!PS || PS->getLocationValue() != R)
  1027. return nullptr;
  1028. }
  1029. StoreSite = Succ;
  1030. // If this is an assignment expression, we can track the value
  1031. // being assigned.
  1032. if (Optional<PostStmt> P = Succ->getLocationAs<PostStmt>())
  1033. if (const BinaryOperator *BO = P->getStmtAs<BinaryOperator>())
  1034. if (BO->isAssignmentOp())
  1035. InitE = BO->getRHS();
  1036. // If this is a call entry, the variable should be a parameter.
  1037. // FIXME: Handle CXXThisRegion as well. (This is not a priority because
  1038. // 'this' should never be NULL, but this visitor isn't just for NULL and
  1039. // UndefinedVal.)
  1040. if (Optional<CallEnter> CE = Succ->getLocationAs<CallEnter>()) {
  1041. if (const auto *VR = dyn_cast<VarRegion>(R)) {
  1042. const auto *Param = cast<ParmVarDecl>(VR->getDecl());
  1043. ProgramStateManager &StateMgr = BRC.getStateManager();
  1044. CallEventManager &CallMgr = StateMgr.getCallEventManager();
  1045. CallEventRef<> Call = CallMgr.getCaller(CE->getCalleeContext(),
  1046. Succ->getState());
  1047. InitE = Call->getArgExpr(Param->getFunctionScopeIndex());
  1048. IsParam = true;
  1049. }
  1050. }
  1051. // If this is a CXXTempObjectRegion, the Expr responsible for its creation
  1052. // is wrapped inside of it.
  1053. if (const auto *TmpR = dyn_cast<CXXTempObjectRegion>(R))
  1054. InitE = TmpR->getExpr();
  1055. }
  1056. if (!StoreSite)
  1057. return nullptr;
  1058. Satisfied = true;
  1059. // If we have an expression that provided the value, try to track where it
  1060. // came from.
  1061. if (InitE) {
  1062. if (V.isUndef() ||
  1063. V.getAs<loc::ConcreteInt>() || V.getAs<nonloc::ConcreteInt>()) {
  1064. if (!IsParam)
  1065. InitE = InitE->IgnoreParenCasts();
  1066. bugreporter::trackExpressionValue(StoreSite, InitE, BR,
  1067. EnableNullFPSuppression);
  1068. }
  1069. ReturnVisitor::addVisitorIfNecessary(StoreSite, InitE->IgnoreParenCasts(),
  1070. BR, EnableNullFPSuppression);
  1071. }
  1072. // Okay, we've found the binding. Emit an appropriate message.
  1073. SmallString<256> sbuf;
  1074. llvm::raw_svector_ostream os(sbuf);
  1075. if (Optional<PostStmt> PS = StoreSite->getLocationAs<PostStmt>()) {
  1076. const Stmt *S = PS->getStmt();
  1077. const char *action = nullptr;
  1078. const auto *DS = dyn_cast<DeclStmt>(S);
  1079. const auto *VR = dyn_cast<VarRegion>(R);
  1080. if (DS) {
  1081. action = R->canPrintPretty() ? "initialized to " :
  1082. "Initializing to ";
  1083. } else if (isa<BlockExpr>(S)) {
  1084. action = R->canPrintPretty() ? "captured by block as " :
  1085. "Captured by block as ";
  1086. if (VR) {
  1087. // See if we can get the BlockVarRegion.
  1088. ProgramStateRef State = StoreSite->getState();
  1089. SVal V = StoreSite->getSVal(S);
  1090. if (const auto *BDR =
  1091. dyn_cast_or_null<BlockDataRegion>(V.getAsRegion())) {
  1092. if (const VarRegion *OriginalR = BDR->getOriginalRegion(VR)) {
  1093. if (auto KV = State->getSVal(OriginalR).getAs<KnownSVal>())
  1094. BR.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
  1095. *KV, OriginalR, EnableNullFPSuppression));
  1096. }
  1097. }
  1098. }
  1099. }
  1100. if (action)
  1101. showBRDiagnostics(action, os, R, V, DS);
  1102. } else if (StoreSite->getLocation().getAs<CallEnter>()) {
  1103. if (const auto *VR = dyn_cast<VarRegion>(R))
  1104. showBRParamDiagnostics(os, VR, V);
  1105. }
  1106. if (os.str().empty())
  1107. showBRDefaultDiagnostics(os, R, V);
  1108. // Construct a new PathDiagnosticPiece.
  1109. ProgramPoint P = StoreSite->getLocation();
  1110. PathDiagnosticLocation L;
  1111. if (P.getAs<CallEnter>() && InitE)
  1112. L = PathDiagnosticLocation(InitE, BRC.getSourceManager(),
  1113. P.getLocationContext());
  1114. if (!L.isValid() || !L.asLocation().isValid())
  1115. L = PathDiagnosticLocation::create(P, BRC.getSourceManager());
  1116. if (!L.isValid() || !L.asLocation().isValid())
  1117. return nullptr;
  1118. return std::make_shared<PathDiagnosticEventPiece>(L, os.str());
  1119. }
  1120. void TrackConstraintBRVisitor::Profile(llvm::FoldingSetNodeID &ID) const {
  1121. static int tag = 0;
  1122. ID.AddPointer(&tag);
  1123. ID.AddBoolean(Assumption);
  1124. ID.Add(Constraint);
  1125. }
  1126. /// Return the tag associated with this visitor. This tag will be used
  1127. /// to make all PathDiagnosticPieces created by this visitor.
  1128. const char *TrackConstraintBRVisitor::getTag() {
  1129. return "TrackConstraintBRVisitor";
  1130. }
  1131. bool TrackConstraintBRVisitor::isUnderconstrained(const ExplodedNode *N) const {
  1132. if (IsZeroCheck)
  1133. return N->getState()->isNull(Constraint).isUnderconstrained();
  1134. return (bool)N->getState()->assume(Constraint, !Assumption);
  1135. }
  1136. std::shared_ptr<PathDiagnosticPiece>
  1137. TrackConstraintBRVisitor::VisitNode(const ExplodedNode *N,
  1138. BugReporterContext &BRC, BugReport &) {
  1139. const ExplodedNode *PrevN = N->getFirstPred();
  1140. if (IsSatisfied)
  1141. return nullptr;
  1142. // Start tracking after we see the first state in which the value is
  1143. // constrained.
  1144. if (!IsTrackingTurnedOn)
  1145. if (!isUnderconstrained(N))
  1146. IsTrackingTurnedOn = true;
  1147. if (!IsTrackingTurnedOn)
  1148. return nullptr;
  1149. // Check if in the previous state it was feasible for this constraint
  1150. // to *not* be true.
  1151. if (isUnderconstrained(PrevN)) {
  1152. IsSatisfied = true;
  1153. // As a sanity check, make sure that the negation of the constraint
  1154. // was infeasible in the current state. If it is feasible, we somehow
  1155. // missed the transition point.
  1156. assert(!isUnderconstrained(N));
  1157. // We found the transition point for the constraint. We now need to
  1158. // pretty-print the constraint. (work-in-progress)
  1159. SmallString<64> sbuf;
  1160. llvm::raw_svector_ostream os(sbuf);
  1161. if (Constraint.getAs<Loc>()) {
  1162. os << "Assuming pointer value is ";
  1163. os << (Assumption ? "non-null" : "null");
  1164. }
  1165. if (os.str().empty())
  1166. return nullptr;
  1167. // Construct a new PathDiagnosticPiece.
  1168. ProgramPoint P = N->getLocation();
  1169. PathDiagnosticLocation L =
  1170. PathDiagnosticLocation::create(P, BRC.getSourceManager());
  1171. if (!L.isValid())
  1172. return nullptr;
  1173. auto X = std::make_shared<PathDiagnosticEventPiece>(L, os.str());
  1174. X->setTag(getTag());
  1175. return std::move(X);
  1176. }
  1177. return nullptr;
  1178. }
  1179. SuppressInlineDefensiveChecksVisitor::
  1180. SuppressInlineDefensiveChecksVisitor(DefinedSVal Value, const ExplodedNode *N)
  1181. : V(Value) {
  1182. // Check if the visitor is disabled.
  1183. AnalyzerOptions &Options = N->getState()->getAnalysisManager().options;
  1184. if (!Options.ShouldSuppressInlinedDefensiveChecks)
  1185. IsSatisfied = true;
  1186. assert(N->getState()->isNull(V).isConstrainedTrue() &&
  1187. "The visitor only tracks the cases where V is constrained to 0");
  1188. }
  1189. void SuppressInlineDefensiveChecksVisitor::Profile(
  1190. llvm::FoldingSetNodeID &ID) const {
  1191. static int id = 0;
  1192. ID.AddPointer(&id);
  1193. ID.Add(V);
  1194. }
  1195. const char *SuppressInlineDefensiveChecksVisitor::getTag() {
  1196. return "IDCVisitor";
  1197. }
  1198. std::shared_ptr<PathDiagnosticPiece>
  1199. SuppressInlineDefensiveChecksVisitor::VisitNode(const ExplodedNode *Succ,
  1200. BugReporterContext &BRC,
  1201. BugReport &BR) {
  1202. const ExplodedNode *Pred = Succ->getFirstPred();
  1203. if (IsSatisfied)
  1204. return nullptr;
  1205. // Start tracking after we see the first state in which the value is null.
  1206. if (!IsTrackingTurnedOn)
  1207. if (Succ->getState()->isNull(V).isConstrainedTrue())
  1208. IsTrackingTurnedOn = true;
  1209. if (!IsTrackingTurnedOn)
  1210. return nullptr;
  1211. // Check if in the previous state it was feasible for this value
  1212. // to *not* be null.
  1213. if (!Pred->getState()->isNull(V).isConstrainedTrue()) {
  1214. IsSatisfied = true;
  1215. assert(Succ->getState()->isNull(V).isConstrainedTrue());
  1216. // Check if this is inlined defensive checks.
  1217. const LocationContext *CurLC =Succ->getLocationContext();
  1218. const LocationContext *ReportLC = BR.getErrorNode()->getLocationContext();
  1219. if (CurLC != ReportLC && !CurLC->isParentOf(ReportLC)) {
  1220. BR.markInvalid("Suppress IDC", CurLC);
  1221. return nullptr;
  1222. }
  1223. // Treat defensive checks in function-like macros as if they were an inlined
  1224. // defensive check. If the bug location is not in a macro and the
  1225. // terminator for the current location is in a macro then suppress the
  1226. // warning.
  1227. auto BugPoint = BR.getErrorNode()->getLocation().getAs<StmtPoint>();
  1228. if (!BugPoint)
  1229. return nullptr;
  1230. ProgramPoint CurPoint = Succ->getLocation();
  1231. const Stmt *CurTerminatorStmt = nullptr;
  1232. if (auto BE = CurPoint.getAs<BlockEdge>()) {
  1233. CurTerminatorStmt = BE->getSrc()->getTerminator().getStmt();
  1234. } else if (auto SP = CurPoint.getAs<StmtPoint>()) {
  1235. const Stmt *CurStmt = SP->getStmt();
  1236. if (!CurStmt->getBeginLoc().isMacroID())
  1237. return nullptr;
  1238. CFGStmtMap *Map = CurLC->getAnalysisDeclContext()->getCFGStmtMap();
  1239. CurTerminatorStmt = Map->getBlock(CurStmt)->getTerminator();
  1240. } else {
  1241. return nullptr;
  1242. }
  1243. if (!CurTerminatorStmt)
  1244. return nullptr;
  1245. SourceLocation TerminatorLoc = CurTerminatorStmt->getBeginLoc();
  1246. if (TerminatorLoc.isMacroID()) {
  1247. SourceLocation BugLoc = BugPoint->getStmt()->getBeginLoc();
  1248. // Suppress reports unless we are in that same macro.
  1249. if (!BugLoc.isMacroID() ||
  1250. getMacroName(BugLoc, BRC) != getMacroName(TerminatorLoc, BRC)) {
  1251. BR.markInvalid("Suppress Macro IDC", CurLC);
  1252. }
  1253. return nullptr;
  1254. }
  1255. }
  1256. return nullptr;
  1257. }
  1258. static const MemRegion *getLocationRegionIfReference(const Expr *E,
  1259. const ExplodedNode *N) {
  1260. if (const auto *DR = dyn_cast<DeclRefExpr>(E)) {
  1261. if (const auto *VD = dyn_cast<VarDecl>(DR->getDecl())) {
  1262. if (!VD->getType()->isReferenceType())
  1263. return nullptr;
  1264. ProgramStateManager &StateMgr = N->getState()->getStateManager();
  1265. MemRegionManager &MRMgr = StateMgr.getRegionManager();
  1266. return MRMgr.getVarRegion(VD, N->getLocationContext());
  1267. }
  1268. }
  1269. // FIXME: This does not handle other kinds of null references,
  1270. // for example, references from FieldRegions:
  1271. // struct Wrapper { int &ref; };
  1272. // Wrapper w = { *(int *)0 };
  1273. // w.ref = 1;
  1274. return nullptr;
  1275. }
  1276. /// \return A subexpression of {@code Ex} which represents the
  1277. /// expression-of-interest.
  1278. static const Expr *peelOffOuterExpr(const Expr *Ex,
  1279. const ExplodedNode *N) {
  1280. Ex = Ex->IgnoreParenCasts();
  1281. if (const auto *FE = dyn_cast<FullExpr>(Ex))
  1282. return peelOffOuterExpr(FE->getSubExpr(), N);
  1283. if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ex))
  1284. return peelOffOuterExpr(OVE->getSourceExpr(), N);
  1285. if (const auto *POE = dyn_cast<PseudoObjectExpr>(Ex)) {
  1286. const auto *PropRef = dyn_cast<ObjCPropertyRefExpr>(POE->getSyntacticForm());
  1287. if (PropRef && PropRef->isMessagingGetter()) {
  1288. const Expr *GetterMessageSend =
  1289. POE->getSemanticExpr(POE->getNumSemanticExprs() - 1);
  1290. assert(isa<ObjCMessageExpr>(GetterMessageSend->IgnoreParenCasts()));
  1291. return peelOffOuterExpr(GetterMessageSend, N);
  1292. }
  1293. }
  1294. // Peel off the ternary operator.
  1295. if (const auto *CO = dyn_cast<ConditionalOperator>(Ex)) {
  1296. // Find a node where the branching occurred and find out which branch
  1297. // we took (true/false) by looking at the ExplodedGraph.
  1298. const ExplodedNode *NI = N;
  1299. do {
  1300. ProgramPoint ProgPoint = NI->getLocation();
  1301. if (Optional<BlockEdge> BE = ProgPoint.getAs<BlockEdge>()) {
  1302. const CFGBlock *srcBlk = BE->getSrc();
  1303. if (const Stmt *term = srcBlk->getTerminator()) {
  1304. if (term == CO) {
  1305. bool TookTrueBranch = (*(srcBlk->succ_begin()) == BE->getDst());
  1306. if (TookTrueBranch)
  1307. return peelOffOuterExpr(CO->getTrueExpr(), N);
  1308. else
  1309. return peelOffOuterExpr(CO->getFalseExpr(), N);
  1310. }
  1311. }
  1312. }
  1313. NI = NI->getFirstPred();
  1314. } while (NI);
  1315. }
  1316. if (auto *BO = dyn_cast<BinaryOperator>(Ex))
  1317. if (const Expr *SubEx = peelOffPointerArithmetic(BO))
  1318. return peelOffOuterExpr(SubEx, N);
  1319. if (auto *UO = dyn_cast<UnaryOperator>(Ex)) {
  1320. if (UO->getOpcode() == UO_LNot)
  1321. return peelOffOuterExpr(UO->getSubExpr(), N);
  1322. // FIXME: There's a hack in our Store implementation that always computes
  1323. // field offsets around null pointers as if they are always equal to 0.
  1324. // The idea here is to report accesses to fields as null dereferences
  1325. // even though the pointer value that's being dereferenced is actually
  1326. // the offset of the field rather than exactly 0.
  1327. // See the FIXME in StoreManager's getLValueFieldOrIvar() method.
  1328. // This code interacts heavily with this hack; otherwise the value
  1329. // would not be null at all for most fields, so we'd be unable to track it.
  1330. if (UO->getOpcode() == UO_AddrOf && UO->getSubExpr()->isLValue())
  1331. if (const Expr *DerefEx = bugreporter::getDerefExpr(UO->getSubExpr()))
  1332. return peelOffOuterExpr(DerefEx, N);
  1333. }
  1334. return Ex;
  1335. }
  1336. /// Find the ExplodedNode where the lvalue (the value of 'Ex')
  1337. /// was computed.
  1338. static const ExplodedNode* findNodeForExpression(const ExplodedNode *N,
  1339. const Expr *Inner) {
  1340. while (N) {
  1341. if (PathDiagnosticLocation::getStmt(N) == Inner)
  1342. return N;
  1343. N = N->getFirstPred();
  1344. }
  1345. return N;
  1346. }
  1347. bool bugreporter::trackExpressionValue(const ExplodedNode *InputNode,
  1348. const Expr *E, BugReport &report,
  1349. bool EnableNullFPSuppression) {
  1350. if (!E || !InputNode)
  1351. return false;
  1352. const Expr *Inner = peelOffOuterExpr(E, InputNode);
  1353. const ExplodedNode *LVNode = findNodeForExpression(InputNode, Inner);
  1354. if (!LVNode)
  1355. return false;
  1356. ProgramStateRef LVState = LVNode->getState();
  1357. // The message send could be nil due to the receiver being nil.
  1358. // At this point in the path, the receiver should be live since we are at the
  1359. // message send expr. If it is nil, start tracking it.
  1360. if (const Expr *Receiver = NilReceiverBRVisitor::getNilReceiver(Inner, LVNode))
  1361. trackExpressionValue(LVNode, Receiver, report, EnableNullFPSuppression);
  1362. // See if the expression we're interested refers to a variable.
  1363. // If so, we can track both its contents and constraints on its value.
  1364. if (ExplodedGraph::isInterestingLValueExpr(Inner)) {
  1365. SVal LVal = LVNode->getSVal(Inner);
  1366. const MemRegion *RR = getLocationRegionIfReference(Inner, LVNode);
  1367. bool LVIsNull = LVState->isNull(LVal).isConstrainedTrue();
  1368. // If this is a C++ reference to a null pointer, we are tracking the
  1369. // pointer. In addition, we should find the store at which the reference
  1370. // got initialized.
  1371. if (RR && !LVIsNull)
  1372. if (auto KV = LVal.getAs<KnownSVal>())
  1373. report.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
  1374. *KV, RR, EnableNullFPSuppression));
  1375. // In case of C++ references, we want to differentiate between a null
  1376. // reference and reference to null pointer.
  1377. // If the LVal is null, check if we are dealing with null reference.
  1378. // For those, we want to track the location of the reference.
  1379. const MemRegion *R = (RR && LVIsNull) ? RR :
  1380. LVNode->getSVal(Inner).getAsRegion();
  1381. if (R) {
  1382. // Mark both the variable region and its contents as interesting.
  1383. SVal V = LVState->getRawSVal(loc::MemRegionVal(R));
  1384. report.addVisitor(
  1385. llvm::make_unique<NoStoreFuncVisitor>(cast<SubRegion>(R)));
  1386. MacroNullReturnSuppressionVisitor::addMacroVisitorIfNecessary(
  1387. LVNode, R, EnableNullFPSuppression, report, V);
  1388. report.markInteresting(V);
  1389. report.addVisitor(llvm::make_unique<UndefOrNullArgVisitor>(R));
  1390. // If the contents are symbolic, find out when they became null.
  1391. if (V.getAsLocSymbol(/*IncludeBaseRegions*/ true))
  1392. report.addVisitor(llvm::make_unique<TrackConstraintBRVisitor>(
  1393. V.castAs<DefinedSVal>(), false));
  1394. // Add visitor, which will suppress inline defensive checks.
  1395. if (auto DV = V.getAs<DefinedSVal>())
  1396. if (!DV->isZeroConstant() && LVState->isNull(*DV).isConstrainedTrue() &&
  1397. EnableNullFPSuppression)
  1398. report.addVisitor(
  1399. llvm::make_unique<SuppressInlineDefensiveChecksVisitor>(*DV,
  1400. LVNode));
  1401. if (auto KV = V.getAs<KnownSVal>())
  1402. report.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
  1403. *KV, R, EnableNullFPSuppression));
  1404. return true;
  1405. }
  1406. }
  1407. // If the expression is not an "lvalue expression", we can still
  1408. // track the constraints on its contents.
  1409. SVal V = LVState->getSValAsScalarOrLoc(Inner, LVNode->getLocationContext());
  1410. ReturnVisitor::addVisitorIfNecessary(
  1411. LVNode, Inner, report, EnableNullFPSuppression);
  1412. // Is it a symbolic value?
  1413. if (auto L = V.getAs<loc::MemRegionVal>()) {
  1414. report.addVisitor(llvm::make_unique<UndefOrNullArgVisitor>(L->getRegion()));
  1415. // FIXME: this is a hack for fixing a later crash when attempting to
  1416. // dereference a void* pointer.
  1417. // We should not try to dereference pointers at all when we don't care
  1418. // what is written inside the pointer.
  1419. bool CanDereference = true;
  1420. if (const auto *SR = dyn_cast<SymbolicRegion>(L->getRegion()))
  1421. if (SR->getSymbol()->getType()->getPointeeType()->isVoidType())
  1422. CanDereference = false;
  1423. // At this point we are dealing with the region's LValue.
  1424. // However, if the rvalue is a symbolic region, we should track it as well.
  1425. // Try to use the correct type when looking up the value.
  1426. SVal RVal;
  1427. if (ExplodedGraph::isInterestingLValueExpr(Inner)) {
  1428. RVal = LVState->getRawSVal(L.getValue(), Inner->getType());
  1429. } else if (CanDereference) {
  1430. RVal = LVState->getSVal(L->getRegion());
  1431. }
  1432. if (CanDereference)
  1433. if (auto KV = RVal.getAs<KnownSVal>())
  1434. report.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
  1435. *KV, L->getRegion(), EnableNullFPSuppression));
  1436. const MemRegion *RegionRVal = RVal.getAsRegion();
  1437. if (RegionRVal && isa<SymbolicRegion>(RegionRVal)) {
  1438. report.markInteresting(RegionRVal);
  1439. report.addVisitor(llvm::make_unique<TrackConstraintBRVisitor>(
  1440. loc::MemRegionVal(RegionRVal), /*assumption=*/false));
  1441. }
  1442. }
  1443. return true;
  1444. }
  1445. const Expr *NilReceiverBRVisitor::getNilReceiver(const Stmt *S,
  1446. const ExplodedNode *N) {
  1447. const auto *ME = dyn_cast<ObjCMessageExpr>(S);
  1448. if (!ME)
  1449. return nullptr;
  1450. if (const Expr *Receiver = ME->getInstanceReceiver()) {
  1451. ProgramStateRef state = N->getState();
  1452. SVal V = N->getSVal(Receiver);
  1453. if (state->isNull(V).isConstrainedTrue())
  1454. return Receiver;
  1455. }
  1456. return nullptr;
  1457. }
  1458. std::shared_ptr<PathDiagnosticPiece>
  1459. NilReceiverBRVisitor::VisitNode(const ExplodedNode *N,
  1460. BugReporterContext &BRC, BugReport &BR) {
  1461. Optional<PreStmt> P = N->getLocationAs<PreStmt>();
  1462. if (!P)
  1463. return nullptr;
  1464. const Stmt *S = P->getStmt();
  1465. const Expr *Receiver = getNilReceiver(S, N);
  1466. if (!Receiver)
  1467. return nullptr;
  1468. llvm::SmallString<256> Buf;
  1469. llvm::raw_svector_ostream OS(Buf);
  1470. if (const auto *ME = dyn_cast<ObjCMessageExpr>(S)) {
  1471. OS << "'";
  1472. ME->getSelector().print(OS);
  1473. OS << "' not called";
  1474. }
  1475. else {
  1476. OS << "No method is called";
  1477. }
  1478. OS << " because the receiver is nil";
  1479. // The receiver was nil, and hence the method was skipped.
  1480. // Register a BugReporterVisitor to issue a message telling us how
  1481. // the receiver was null.
  1482. bugreporter::trackExpressionValue(N, Receiver, BR,
  1483. /*EnableNullFPSuppression*/ false);
  1484. // Issue a message saying that the method was skipped.
  1485. PathDiagnosticLocation L(Receiver, BRC.getSourceManager(),
  1486. N->getLocationContext());
  1487. return std::make_shared<PathDiagnosticEventPiece>(L, OS.str());
  1488. }
  1489. // Registers every VarDecl inside a Stmt with a last store visitor.
  1490. void FindLastStoreBRVisitor::registerStatementVarDecls(BugReport &BR,
  1491. const Stmt *S,
  1492. bool EnableNullFPSuppression) {
  1493. const ExplodedNode *N = BR.getErrorNode();
  1494. std::deque<const Stmt *> WorkList;
  1495. WorkList.push_back(S);
  1496. while (!WorkList.empty()) {
  1497. const Stmt *Head = WorkList.front();
  1498. WorkList.pop_front();
  1499. ProgramStateManager &StateMgr = N->getState()->getStateManager();
  1500. if (const auto *DR = dyn_cast<DeclRefExpr>(Head)) {
  1501. if (const auto *VD = dyn_cast<VarDecl>(DR->getDecl())) {
  1502. const VarRegion *R =
  1503. StateMgr.getRegionManager().getVarRegion(VD, N->getLocationContext());
  1504. // What did we load?
  1505. SVal V = N->getSVal(S);
  1506. if (V.getAs<loc::ConcreteInt>() || V.getAs<nonloc::ConcreteInt>()) {
  1507. // Register a new visitor with the BugReport.
  1508. BR.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
  1509. V.castAs<KnownSVal>(), R, EnableNullFPSuppression));
  1510. }
  1511. }
  1512. }
  1513. for (const Stmt *SubStmt : Head->children())
  1514. WorkList.push_back(SubStmt);
  1515. }
  1516. }
  1517. //===----------------------------------------------------------------------===//
  1518. // Visitor that tries to report interesting diagnostics from conditions.
  1519. //===----------------------------------------------------------------------===//
  1520. /// Return the tag associated with this visitor. This tag will be used
  1521. /// to make all PathDiagnosticPieces created by this visitor.
  1522. const char *ConditionBRVisitor::getTag() {
  1523. return "ConditionBRVisitor";
  1524. }
  1525. std::shared_ptr<PathDiagnosticPiece>
  1526. ConditionBRVisitor::VisitNode(const ExplodedNode *N,
  1527. BugReporterContext &BRC, BugReport &BR) {
  1528. auto piece = VisitNodeImpl(N, BRC, BR);
  1529. if (piece) {
  1530. piece->setTag(getTag());
  1531. if (auto *ev = dyn_cast<PathDiagnosticEventPiece>(piece.get()))
  1532. ev->setPrunable(true, /* override */ false);
  1533. }
  1534. return piece;
  1535. }
  1536. std::shared_ptr<PathDiagnosticPiece>
  1537. ConditionBRVisitor::VisitNodeImpl(const ExplodedNode *N,
  1538. BugReporterContext &BRC, BugReport &BR) {
  1539. ProgramPoint progPoint = N->getLocation();
  1540. // If an assumption was made on a branch, it should be caught
  1541. // here by looking at the state transition.
  1542. if (Optional<BlockEdge> BE = progPoint.getAs<BlockEdge>()) {
  1543. const CFGBlock *srcBlk = BE->getSrc();
  1544. if (const Stmt *term = srcBlk->getTerminator())
  1545. return VisitTerminator(term, N, srcBlk, BE->getDst(), BR, BRC);
  1546. return nullptr;
  1547. }
  1548. if (Optional<PostStmt> PS = progPoint.getAs<PostStmt>()) {
  1549. const std::pair<const ProgramPointTag *, const ProgramPointTag *> &tags =
  1550. ExprEngine::geteagerlyAssumeBinOpBifurcationTags();
  1551. const ProgramPointTag *tag = PS->getTag();
  1552. if (tag == tags.first)
  1553. return VisitTrueTest(cast<Expr>(PS->getStmt()), true,
  1554. BRC, BR, N);
  1555. if (tag == tags.second)
  1556. return VisitTrueTest(cast<Expr>(PS->getStmt()), false,
  1557. BRC, BR, N);
  1558. return nullptr;
  1559. }
  1560. return nullptr;
  1561. }
  1562. std::shared_ptr<PathDiagnosticPiece> ConditionBRVisitor::VisitTerminator(
  1563. const Stmt *Term, const ExplodedNode *N, const CFGBlock *srcBlk,
  1564. const CFGBlock *dstBlk, BugReport &R, BugReporterContext &BRC) {
  1565. const Expr *Cond = nullptr;
  1566. // In the code below, Term is a CFG terminator and Cond is a branch condition
  1567. // expression upon which the decision is made on this terminator.
  1568. //
  1569. // For example, in "if (x == 0)", the "if (x == 0)" statement is a terminator,
  1570. // and "x == 0" is the respective condition.
  1571. //
  1572. // Another example: in "if (x && y)", we've got two terminators and two
  1573. // conditions due to short-circuit nature of operator "&&":
  1574. // 1. The "if (x && y)" statement is a terminator,
  1575. // and "y" is the respective condition.
  1576. // 2. Also "x && ..." is another terminator,
  1577. // and "x" is its condition.
  1578. switch (Term->getStmtClass()) {
  1579. // FIXME: Stmt::SwitchStmtClass is worth handling, however it is a bit
  1580. // more tricky because there are more than two branches to account for.
  1581. default:
  1582. return nullptr;
  1583. case Stmt::IfStmtClass:
  1584. Cond = cast<IfStmt>(Term)->getCond();
  1585. break;
  1586. case Stmt::ConditionalOperatorClass:
  1587. Cond = cast<ConditionalOperator>(Term)->getCond();
  1588. break;
  1589. case Stmt::BinaryOperatorClass:
  1590. // When we encounter a logical operator (&& or ||) as a CFG terminator,
  1591. // then the condition is actually its LHS; otherwise, we'd encounter
  1592. // the parent, such as if-statement, as a terminator.
  1593. const auto *BO = cast<BinaryOperator>(Term);
  1594. assert(BO->isLogicalOp() &&
  1595. "CFG terminator is not a short-circuit operator!");
  1596. Cond = BO->getLHS();
  1597. break;
  1598. }
  1599. Cond = Cond->IgnoreParens();
  1600. // However, when we encounter a logical operator as a branch condition,
  1601. // then the condition is actually its RHS, because LHS would be
  1602. // the condition for the logical operator terminator.
  1603. while (const auto *InnerBO = dyn_cast<BinaryOperator>(Cond)) {
  1604. if (!InnerBO->isLogicalOp())
  1605. break;
  1606. Cond = InnerBO->getRHS()->IgnoreParens();
  1607. }
  1608. assert(Cond);
  1609. assert(srcBlk->succ_size() == 2);
  1610. const bool tookTrue = *(srcBlk->succ_begin()) == dstBlk;
  1611. return VisitTrueTest(Cond, tookTrue, BRC, R, N);
  1612. }
  1613. std::shared_ptr<PathDiagnosticPiece>
  1614. ConditionBRVisitor::VisitTrueTest(const Expr *Cond, bool tookTrue,
  1615. BugReporterContext &BRC, BugReport &R,
  1616. const ExplodedNode *N) {
  1617. ProgramStateRef CurrentState = N->getState();
  1618. ProgramStateRef PreviousState = N->getFirstPred()->getState();
  1619. const LocationContext *LCtx = N->getLocationContext();
  1620. // If the constraint information is changed between the current and the
  1621. // previous program state we assuming the newly seen constraint information.
  1622. // If we cannot evaluate the condition (and the constraints are the same)
  1623. // the analyzer has no information about the value and just assuming it.
  1624. if (BRC.getStateManager().haveEqualConstraints(CurrentState, PreviousState) &&
  1625. CurrentState->getSVal(Cond, LCtx).isValid())
  1626. return nullptr;
  1627. // These will be modified in code below, but we need to preserve the original
  1628. // values in case we want to throw the generic message.
  1629. const Expr *CondTmp = Cond;
  1630. bool tookTrueTmp = tookTrue;
  1631. while (true) {
  1632. CondTmp = CondTmp->IgnoreParenCasts();
  1633. switch (CondTmp->getStmtClass()) {
  1634. default:
  1635. break;
  1636. case Stmt::BinaryOperatorClass:
  1637. if (auto P = VisitTrueTest(Cond, cast<BinaryOperator>(CondTmp),
  1638. tookTrueTmp, BRC, R, N))
  1639. return P;
  1640. break;
  1641. case Stmt::DeclRefExprClass:
  1642. if (auto P = VisitTrueTest(Cond, cast<DeclRefExpr>(CondTmp),
  1643. tookTrueTmp, BRC, R, N))
  1644. return P;
  1645. break;
  1646. case Stmt::UnaryOperatorClass: {
  1647. const auto *UO = cast<UnaryOperator>(CondTmp);
  1648. if (UO->getOpcode() == UO_LNot) {
  1649. tookTrueTmp = !tookTrueTmp;
  1650. CondTmp = UO->getSubExpr();
  1651. continue;
  1652. }
  1653. break;
  1654. }
  1655. }
  1656. break;
  1657. }
  1658. // Condition too complex to explain? Just say something so that the user
  1659. // knew we've made some path decision at this point.
  1660. PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
  1661. if (!Loc.isValid() || !Loc.asLocation().isValid())
  1662. return nullptr;
  1663. return std::make_shared<PathDiagnosticEventPiece>(
  1664. Loc, tookTrue ? GenericTrueMessage : GenericFalseMessage);
  1665. }
  1666. bool ConditionBRVisitor::patternMatch(const Expr *Ex,
  1667. const Expr *ParentEx,
  1668. raw_ostream &Out,
  1669. BugReporterContext &BRC,
  1670. BugReport &report,
  1671. const ExplodedNode *N,
  1672. Optional<bool> &prunable) {
  1673. const Expr *OriginalExpr = Ex;
  1674. Ex = Ex->IgnoreParenCasts();
  1675. // Use heuristics to determine if Ex is a macro expending to a literal and
  1676. // if so, use the macro's name.
  1677. SourceLocation LocStart = Ex->getBeginLoc();
  1678. SourceLocation LocEnd = Ex->getEndLoc();
  1679. if (LocStart.isMacroID() && LocEnd.isMacroID() &&
  1680. (isa<GNUNullExpr>(Ex) ||
  1681. isa<ObjCBoolLiteralExpr>(Ex) ||
  1682. isa<CXXBoolLiteralExpr>(Ex) ||
  1683. isa<IntegerLiteral>(Ex) ||
  1684. isa<FloatingLiteral>(Ex))) {
  1685. StringRef StartName = Lexer::getImmediateMacroNameForDiagnostics(LocStart,
  1686. BRC.getSourceManager(), BRC.getASTContext().getLangOpts());
  1687. StringRef EndName = Lexer::getImmediateMacroNameForDiagnostics(LocEnd,
  1688. BRC.getSourceManager(), BRC.getASTContext().getLangOpts());
  1689. bool beginAndEndAreTheSameMacro = StartName.equals(EndName);
  1690. bool partOfParentMacro = false;
  1691. if (ParentEx->getBeginLoc().isMacroID()) {
  1692. StringRef PName = Lexer::getImmediateMacroNameForDiagnostics(
  1693. ParentEx->getBeginLoc(), BRC.getSourceManager(),
  1694. BRC.getASTContext().getLangOpts());
  1695. partOfParentMacro = PName.equals(StartName);
  1696. }
  1697. if (beginAndEndAreTheSameMacro && !partOfParentMacro ) {
  1698. // Get the location of the macro name as written by the caller.
  1699. SourceLocation Loc = LocStart;
  1700. while (LocStart.isMacroID()) {
  1701. Loc = LocStart;
  1702. LocStart = BRC.getSourceManager().getImmediateMacroCallerLoc(LocStart);
  1703. }
  1704. StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
  1705. Loc, BRC.getSourceManager(), BRC.getASTContext().getLangOpts());
  1706. // Return the macro name.
  1707. Out << MacroName;
  1708. return false;
  1709. }
  1710. }
  1711. if (const auto *DR = dyn_cast<DeclRefExpr>(Ex)) {
  1712. const bool quotes = isa<VarDecl>(DR->getDecl());
  1713. if (quotes) {
  1714. Out << '\'';
  1715. const LocationContext *LCtx = N->getLocationContext();
  1716. const ProgramState *state = N->getState().get();
  1717. if (const MemRegion *R = state->getLValue(cast<VarDecl>(DR->getDecl()),
  1718. LCtx).getAsRegion()) {
  1719. if (report.isInteresting(R))
  1720. prunable = false;
  1721. else {
  1722. const ProgramState *state = N->getState().get();
  1723. SVal V = state->getSVal(R);
  1724. if (report.isInteresting(V))
  1725. prunable = false;
  1726. }
  1727. }
  1728. }
  1729. Out << DR->getDecl()->getDeclName().getAsString();
  1730. if (quotes)
  1731. Out << '\'';
  1732. return quotes;
  1733. }
  1734. if (const auto *IL = dyn_cast<IntegerLiteral>(Ex)) {
  1735. QualType OriginalTy = OriginalExpr->getType();
  1736. if (OriginalTy->isPointerType()) {
  1737. if (IL->getValue() == 0) {
  1738. Out << "null";
  1739. return false;
  1740. }
  1741. }
  1742. else if (OriginalTy->isObjCObjectPointerType()) {
  1743. if (IL->getValue() == 0) {
  1744. Out << "nil";
  1745. return false;
  1746. }
  1747. }
  1748. Out << IL->getValue();
  1749. return false;
  1750. }
  1751. return false;
  1752. }
  1753. std::shared_ptr<PathDiagnosticPiece>
  1754. ConditionBRVisitor::VisitTrueTest(const Expr *Cond, const BinaryOperator *BExpr,
  1755. const bool tookTrue, BugReporterContext &BRC,
  1756. BugReport &R, const ExplodedNode *N) {
  1757. bool shouldInvert = false;
  1758. Optional<bool> shouldPrune;
  1759. SmallString<128> LhsString, RhsString;
  1760. {
  1761. llvm::raw_svector_ostream OutLHS(LhsString), OutRHS(RhsString);
  1762. const bool isVarLHS = patternMatch(BExpr->getLHS(), BExpr, OutLHS,
  1763. BRC, R, N, shouldPrune);
  1764. const bool isVarRHS = patternMatch(BExpr->getRHS(), BExpr, OutRHS,
  1765. BRC, R, N, shouldPrune);
  1766. shouldInvert = !isVarLHS && isVarRHS;
  1767. }
  1768. BinaryOperator::Opcode Op = BExpr->getOpcode();
  1769. if (BinaryOperator::isAssignmentOp(Op)) {
  1770. // For assignment operators, all that we care about is that the LHS
  1771. // evaluates to "true" or "false".
  1772. return VisitConditionVariable(LhsString, BExpr->getLHS(), tookTrue,
  1773. BRC, R, N);
  1774. }
  1775. // For non-assignment operations, we require that we can understand
  1776. // both the LHS and RHS.
  1777. if (LhsString.empty() || RhsString.empty() ||
  1778. !BinaryOperator::isComparisonOp(Op) || Op == BO_Cmp)
  1779. return nullptr;
  1780. // Should we invert the strings if the LHS is not a variable name?
  1781. SmallString<256> buf;
  1782. llvm::raw_svector_ostream Out(buf);
  1783. Out << "Assuming " << (shouldInvert ? RhsString : LhsString) << " is ";
  1784. // Do we need to invert the opcode?
  1785. if (shouldInvert)
  1786. switch (Op) {
  1787. default: break;
  1788. case BO_LT: Op = BO_GT; break;
  1789. case BO_GT: Op = BO_LT; break;
  1790. case BO_LE: Op = BO_GE; break;
  1791. case BO_GE: Op = BO_LE; break;
  1792. }
  1793. if (!tookTrue)
  1794. switch (Op) {
  1795. case BO_EQ: Op = BO_NE; break;
  1796. case BO_NE: Op = BO_EQ; break;
  1797. case BO_LT: Op = BO_GE; break;
  1798. case BO_GT: Op = BO_LE; break;
  1799. case BO_LE: Op = BO_GT; break;
  1800. case BO_GE: Op = BO_LT; break;
  1801. default:
  1802. return nullptr;
  1803. }
  1804. switch (Op) {
  1805. case BO_EQ:
  1806. Out << "equal to ";
  1807. break;
  1808. case BO_NE:
  1809. Out << "not equal to ";
  1810. break;
  1811. default:
  1812. Out << BinaryOperator::getOpcodeStr(Op) << ' ';
  1813. break;
  1814. }
  1815. Out << (shouldInvert ? LhsString : RhsString);
  1816. const LocationContext *LCtx = N->getLocationContext();
  1817. PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
  1818. auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str());
  1819. if (shouldPrune.hasValue())
  1820. event->setPrunable(shouldPrune.getValue());
  1821. return event;
  1822. }
  1823. std::shared_ptr<PathDiagnosticPiece> ConditionBRVisitor::VisitConditionVariable(
  1824. StringRef LhsString, const Expr *CondVarExpr, const bool tookTrue,
  1825. BugReporterContext &BRC, BugReport &report, const ExplodedNode *N) {
  1826. // FIXME: If there's already a constraint tracker for this variable,
  1827. // we shouldn't emit anything here (c.f. the double note in
  1828. // test/Analysis/inlining/path-notes.c)
  1829. SmallString<256> buf;
  1830. llvm::raw_svector_ostream Out(buf);
  1831. Out << "Assuming " << LhsString << " is ";
  1832. QualType Ty = CondVarExpr->getType();
  1833. if (Ty->isPointerType())
  1834. Out << (tookTrue ? "not null" : "null");
  1835. else if (Ty->isObjCObjectPointerType())
  1836. Out << (tookTrue ? "not nil" : "nil");
  1837. else if (Ty->isBooleanType())
  1838. Out << (tookTrue ? "true" : "false");
  1839. else if (Ty->isIntegralOrEnumerationType())
  1840. Out << (tookTrue ? "non-zero" : "zero");
  1841. else
  1842. return nullptr;
  1843. const LocationContext *LCtx = N->getLocationContext();
  1844. PathDiagnosticLocation Loc(CondVarExpr, BRC.getSourceManager(), LCtx);
  1845. auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str());
  1846. if (const auto *DR = dyn_cast<DeclRefExpr>(CondVarExpr)) {
  1847. if (const auto *VD = dyn_cast<VarDecl>(DR->getDecl())) {
  1848. const ProgramState *state = N->getState().get();
  1849. if (const MemRegion *R = state->getLValue(VD, LCtx).getAsRegion()) {
  1850. if (report.isInteresting(R))
  1851. event->setPrunable(false);
  1852. }
  1853. }
  1854. }
  1855. return event;
  1856. }
  1857. std::shared_ptr<PathDiagnosticPiece>
  1858. ConditionBRVisitor::VisitTrueTest(const Expr *Cond, const DeclRefExpr *DR,
  1859. const bool tookTrue, BugReporterContext &BRC,
  1860. BugReport &report, const ExplodedNode *N) {
  1861. const auto *VD = dyn_cast<VarDecl>(DR->getDecl());
  1862. if (!VD)
  1863. return nullptr;
  1864. SmallString<256> Buf;
  1865. llvm::raw_svector_ostream Out(Buf);
  1866. Out << "Assuming '" << VD->getDeclName() << "' is ";
  1867. QualType VDTy = VD->getType();
  1868. if (VDTy->isPointerType())
  1869. Out << (tookTrue ? "non-null" : "null");
  1870. else if (VDTy->isObjCObjectPointerType())
  1871. Out << (tookTrue ? "non-nil" : "nil");
  1872. else if (VDTy->isScalarType())
  1873. Out << (tookTrue ? "not equal to 0" : "0");
  1874. else
  1875. return nullptr;
  1876. const LocationContext *LCtx = N->getLocationContext();
  1877. PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
  1878. auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str());
  1879. const ProgramState *state = N->getState().get();
  1880. if (const MemRegion *R = state->getLValue(VD, LCtx).getAsRegion()) {
  1881. if (report.isInteresting(R))
  1882. event->setPrunable(false);
  1883. else {
  1884. SVal V = state->getSVal(R);
  1885. if (report.isInteresting(V))
  1886. event->setPrunable(false);
  1887. }
  1888. }
  1889. return std::move(event);
  1890. }
  1891. const char *const ConditionBRVisitor::GenericTrueMessage =
  1892. "Assuming the condition is true";
  1893. const char *const ConditionBRVisitor::GenericFalseMessage =
  1894. "Assuming the condition is false";
  1895. bool ConditionBRVisitor::isPieceMessageGeneric(
  1896. const PathDiagnosticPiece *Piece) {
  1897. return Piece->getString() == GenericTrueMessage ||
  1898. Piece->getString() == GenericFalseMessage;
  1899. }
  1900. void LikelyFalsePositiveSuppressionBRVisitor::finalizeVisitor(
  1901. BugReporterContext &BRC, const ExplodedNode *N, BugReport &BR) {
  1902. // Here we suppress false positives coming from system headers. This list is
  1903. // based on known issues.
  1904. AnalyzerOptions &Options = BRC.getAnalyzerOptions();
  1905. const Decl *D = N->getLocationContext()->getDecl();
  1906. if (AnalysisDeclContext::isInStdNamespace(D)) {
  1907. // Skip reports within the 'std' namespace. Although these can sometimes be
  1908. // the user's fault, we currently don't report them very well, and
  1909. // Note that this will not help for any other data structure libraries, like
  1910. // TR1, Boost, or llvm/ADT.
  1911. if (Options.ShouldSuppressFromCXXStandardLibrary) {
  1912. BR.markInvalid(getTag(), nullptr);
  1913. return;
  1914. } else {
  1915. // If the complete 'std' suppression is not enabled, suppress reports
  1916. // from the 'std' namespace that are known to produce false positives.
  1917. // The analyzer issues a false use-after-free when std::list::pop_front
  1918. // or std::list::pop_back are called multiple times because we cannot
  1919. // reason about the internal invariants of the data structure.
  1920. if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
  1921. const CXXRecordDecl *CD = MD->getParent();
  1922. if (CD->getName() == "list") {
  1923. BR.markInvalid(getTag(), nullptr);
  1924. return;
  1925. }
  1926. }
  1927. // The analyzer issues a false positive when the constructor of
  1928. // std::__independent_bits_engine from algorithms is used.
  1929. if (const auto *MD = dyn_cast<CXXConstructorDecl>(D)) {
  1930. const CXXRecordDecl *CD = MD->getParent();
  1931. if (CD->getName() == "__independent_bits_engine") {
  1932. BR.markInvalid(getTag(), nullptr);
  1933. return;
  1934. }
  1935. }
  1936. for (const LocationContext *LCtx = N->getLocationContext(); LCtx;
  1937. LCtx = LCtx->getParent()) {
  1938. const auto *MD = dyn_cast<CXXMethodDecl>(LCtx->getDecl());
  1939. if (!MD)
  1940. continue;
  1941. const CXXRecordDecl *CD = MD->getParent();
  1942. // The analyzer issues a false positive on
  1943. // std::basic_string<uint8_t> v; v.push_back(1);
  1944. // and
  1945. // std::u16string s; s += u'a';
  1946. // because we cannot reason about the internal invariants of the
  1947. // data structure.
  1948. if (CD->getName() == "basic_string") {
  1949. BR.markInvalid(getTag(), nullptr);
  1950. return;
  1951. }
  1952. // The analyzer issues a false positive on
  1953. // std::shared_ptr<int> p(new int(1)); p = nullptr;
  1954. // because it does not reason properly about temporary destructors.
  1955. if (CD->getName() == "shared_ptr") {
  1956. BR.markInvalid(getTag(), nullptr);
  1957. return;
  1958. }
  1959. }
  1960. }
  1961. }
  1962. // Skip reports within the sys/queue.h macros as we do not have the ability to
  1963. // reason about data structure shapes.
  1964. SourceManager &SM = BRC.getSourceManager();
  1965. FullSourceLoc Loc = BR.getLocation(SM).asLocation();
  1966. while (Loc.isMacroID()) {
  1967. Loc = Loc.getSpellingLoc();
  1968. if (SM.getFilename(Loc).endswith("sys/queue.h")) {
  1969. BR.markInvalid(getTag(), nullptr);
  1970. return;
  1971. }
  1972. }
  1973. }
  1974. std::shared_ptr<PathDiagnosticPiece>
  1975. UndefOrNullArgVisitor::VisitNode(const ExplodedNode *N,
  1976. BugReporterContext &BRC, BugReport &BR) {
  1977. ProgramStateRef State = N->getState();
  1978. ProgramPoint ProgLoc = N->getLocation();
  1979. // We are only interested in visiting CallEnter nodes.
  1980. Optional<CallEnter> CEnter = ProgLoc.getAs<CallEnter>();
  1981. if (!CEnter)
  1982. return nullptr;
  1983. // Check if one of the arguments is the region the visitor is tracking.
  1984. CallEventManager &CEMgr = BRC.getStateManager().getCallEventManager();
  1985. CallEventRef<> Call = CEMgr.getCaller(CEnter->getCalleeContext(), State);
  1986. unsigned Idx = 0;
  1987. ArrayRef<ParmVarDecl *> parms = Call->parameters();
  1988. for (const auto ParamDecl : parms) {
  1989. const MemRegion *ArgReg = Call->getArgSVal(Idx).getAsRegion();
  1990. ++Idx;
  1991. // Are we tracking the argument or its subregion?
  1992. if ( !ArgReg || !R->isSubRegionOf(ArgReg->StripCasts()))
  1993. continue;
  1994. // Check the function parameter type.
  1995. assert(ParamDecl && "Formal parameter has no decl?");
  1996. QualType T = ParamDecl->getType();
  1997. if (!(T->isAnyPointerType() || T->isReferenceType())) {
  1998. // Function can only change the value passed in by address.
  1999. continue;
  2000. }
  2001. // If it is a const pointer value, the function does not intend to
  2002. // change the value.
  2003. if (T->getPointeeType().isConstQualified())
  2004. continue;
  2005. // Mark the call site (LocationContext) as interesting if the value of the
  2006. // argument is undefined or '0'/'NULL'.
  2007. SVal BoundVal = State->getSVal(R);
  2008. if (BoundVal.isUndef() || BoundVal.isZeroConstant()) {
  2009. BR.markInteresting(CEnter->getCalleeContext());
  2010. return nullptr;
  2011. }
  2012. }
  2013. return nullptr;
  2014. }
  2015. std::shared_ptr<PathDiagnosticPiece>
  2016. CXXSelfAssignmentBRVisitor::VisitNode(const ExplodedNode *Succ,
  2017. BugReporterContext &BRC, BugReport &) {
  2018. if (Satisfied)
  2019. return nullptr;
  2020. const auto Edge = Succ->getLocation().getAs<BlockEdge>();
  2021. if (!Edge.hasValue())
  2022. return nullptr;
  2023. auto Tag = Edge->getTag();
  2024. if (!Tag)
  2025. return nullptr;
  2026. if (Tag->getTagDescription() != "cplusplus.SelfAssignment")
  2027. return nullptr;
  2028. Satisfied = true;
  2029. const auto *Met =
  2030. dyn_cast<CXXMethodDecl>(Succ->getCodeDecl().getAsFunction());
  2031. assert(Met && "Not a C++ method.");
  2032. assert((Met->isCopyAssignmentOperator() || Met->isMoveAssignmentOperator()) &&
  2033. "Not a copy/move assignment operator.");
  2034. const auto *LCtx = Edge->getLocationContext();
  2035. const auto &State = Succ->getState();
  2036. auto &SVB = State->getStateManager().getSValBuilder();
  2037. const auto Param =
  2038. State->getSVal(State->getRegion(Met->getParamDecl(0), LCtx));
  2039. const auto This =
  2040. State->getSVal(SVB.getCXXThis(Met, LCtx->getStackFrame()));
  2041. auto L = PathDiagnosticLocation::create(Met, BRC.getSourceManager());
  2042. if (!L.isValid() || !L.asLocation().isValid())
  2043. return nullptr;
  2044. SmallString<256> Buf;
  2045. llvm::raw_svector_ostream Out(Buf);
  2046. Out << "Assuming " << Met->getParamDecl(0)->getName() <<
  2047. ((Param == This) ? " == " : " != ") << "*this";
  2048. auto Piece = std::make_shared<PathDiagnosticEventPiece>(L, Out.str());
  2049. Piece->addRange(Met->getSourceRange());
  2050. return std::move(Piece);
  2051. }
  2052. std::shared_ptr<PathDiagnosticPiece>
  2053. TaintBugVisitor::VisitNode(const ExplodedNode *N,
  2054. BugReporterContext &BRC, BugReport &) {
  2055. // Find the ExplodedNode where the taint was first introduced
  2056. if (!N->getState()->isTainted(V) || N->getFirstPred()->getState()->isTainted(V))
  2057. return nullptr;
  2058. const Stmt *S = PathDiagnosticLocation::getStmt(N);
  2059. if (!S)
  2060. return nullptr;
  2061. const LocationContext *NCtx = N->getLocationContext();
  2062. PathDiagnosticLocation L =
  2063. PathDiagnosticLocation::createBegin(S, BRC.getSourceManager(), NCtx);
  2064. if (!L.isValid() || !L.asLocation().isValid())
  2065. return nullptr;
  2066. return std::make_shared<PathDiagnosticEventPiece>(L, "Taint originated here");
  2067. }
  2068. FalsePositiveRefutationBRVisitor::FalsePositiveRefutationBRVisitor()
  2069. : Constraints(ConstraintRangeTy::Factory().getEmptyMap()) {}
  2070. void FalsePositiveRefutationBRVisitor::finalizeVisitor(
  2071. BugReporterContext &BRC, const ExplodedNode *EndPathNode, BugReport &BR) {
  2072. // Collect new constraints
  2073. VisitNode(EndPathNode, BRC, BR);
  2074. // Create a refutation manager
  2075. llvm::SMTSolverRef RefutationSolver = llvm::CreateZ3Solver();
  2076. ASTContext &Ctx = BRC.getASTContext();
  2077. // Add constraints to the solver
  2078. for (const auto &I : Constraints) {
  2079. const SymbolRef Sym = I.first;
  2080. auto RangeIt = I.second.begin();
  2081. llvm::SMTExprRef Constraints = SMTConv::getRangeExpr(
  2082. RefutationSolver, Ctx, Sym, RangeIt->From(), RangeIt->To(),
  2083. /*InRange=*/true);
  2084. while ((++RangeIt) != I.second.end()) {
  2085. Constraints = RefutationSolver->mkOr(
  2086. Constraints, SMTConv::getRangeExpr(RefutationSolver, Ctx, Sym,
  2087. RangeIt->From(), RangeIt->To(),
  2088. /*InRange=*/true));
  2089. }
  2090. RefutationSolver->addConstraint(Constraints);
  2091. }
  2092. // And check for satisfiability
  2093. Optional<bool> isSat = RefutationSolver->check();
  2094. if (!isSat.hasValue())
  2095. return;
  2096. if (!isSat.getValue())
  2097. BR.markInvalid("Infeasible constraints", EndPathNode->getLocationContext());
  2098. }
  2099. std::shared_ptr<PathDiagnosticPiece>
  2100. FalsePositiveRefutationBRVisitor::VisitNode(const ExplodedNode *N,
  2101. BugReporterContext &,
  2102. BugReport &) {
  2103. // Collect new constraints
  2104. const ConstraintRangeTy &NewCs = N->getState()->get<ConstraintRange>();
  2105. ConstraintRangeTy::Factory &CF =
  2106. N->getState()->get_context<ConstraintRange>();
  2107. // Add constraints if we don't have them yet
  2108. for (auto const &C : NewCs) {
  2109. const SymbolRef &Sym = C.first;
  2110. if (!Constraints.contains(Sym)) {
  2111. Constraints = CF.add(Constraints, Sym, C.second);
  2112. }
  2113. }
  2114. return nullptr;
  2115. }
  2116. int NoteTag::Kind = 0;
  2117. void TagVisitor::Profile(llvm::FoldingSetNodeID &ID) const {
  2118. static int Tag = 0;
  2119. ID.AddPointer(&Tag);
  2120. }
  2121. std::shared_ptr<PathDiagnosticPiece>
  2122. TagVisitor::VisitNode(const ExplodedNode *N, BugReporterContext &BRC,
  2123. BugReport &R) {
  2124. ProgramPoint PP = N->getLocation();
  2125. const NoteTag *T = dyn_cast_or_null<NoteTag>(PP.getTag());
  2126. if (!T)
  2127. return nullptr;
  2128. if (Optional<std::string> Msg = T->generateMessage(BRC, R)) {
  2129. PathDiagnosticLocation Loc =
  2130. PathDiagnosticLocation::create(PP, BRC.getSourceManager());
  2131. return std::make_shared<PathDiagnosticEventPiece>(Loc, *Msg);
  2132. }
  2133. return nullptr;
  2134. }
  2135. void FalsePositiveRefutationBRVisitor::Profile(
  2136. llvm::FoldingSetNodeID &ID) const {
  2137. static int Tag = 0;
  2138. ID.AddPointer(&Tag);
  2139. }