BugReporterVisitors.cpp 83 KB

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