BugReporterVisitors.cpp 86 KB

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