BugReporterVisitors.cpp 86 KB

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