BugReporterVisitors.cpp 101 KB

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