ExprEngine.cpp 112 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037
  1. //=-- ExprEngine.cpp - Path-Sensitive Expression-Level Dataflow ---*- C++ -*-=
  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 meta-engine for path-sensitive dataflow analysis that
  11. // is built on GREngine, but provides the boilerplate to execute transfer
  12. // functions and build the ExplodedGraph at the expression level.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
  16. #include "PrettyStackTraceLocationContext.h"
  17. #include "clang/AST/CharUnits.h"
  18. #include "clang/AST/ParentMap.h"
  19. #include "clang/Analysis/CFGStmtMap.h"
  20. #include "clang/AST/StmtCXX.h"
  21. #include "clang/AST/StmtObjC.h"
  22. #include "clang/Basic/Builtins.h"
  23. #include "clang/Basic/PrettyStackTrace.h"
  24. #include "clang/Basic/SourceManager.h"
  25. #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
  26. #include "clang/StaticAnalyzer/Core/CheckerManager.h"
  27. #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
  28. #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
  29. #include "clang/StaticAnalyzer/Core/PathSensitive/LoopWidening.h"
  30. #include "clang/StaticAnalyzer/Core/PathSensitive/LoopUnrolling.h"
  31. #include "llvm/ADT/Statistic.h"
  32. #include "llvm/Support/SaveAndRestore.h"
  33. #include "llvm/Support/raw_ostream.h"
  34. #ifndef NDEBUG
  35. #include "llvm/Support/GraphWriter.h"
  36. #endif
  37. using namespace clang;
  38. using namespace ento;
  39. using llvm::APSInt;
  40. #define DEBUG_TYPE "ExprEngine"
  41. STATISTIC(NumRemoveDeadBindings,
  42. "The # of times RemoveDeadBindings is called");
  43. STATISTIC(NumMaxBlockCountReached,
  44. "The # of aborted paths due to reaching the maximum block count in "
  45. "a top level function");
  46. STATISTIC(NumMaxBlockCountReachedInInlined,
  47. "The # of aborted paths due to reaching the maximum block count in "
  48. "an inlined function");
  49. STATISTIC(NumTimesRetriedWithoutInlining,
  50. "The # of times we re-evaluated a call without inlining");
  51. typedef std::pair<const CXXBindTemporaryExpr *, const StackFrameContext *>
  52. CXXBindTemporaryContext;
  53. // Keeps track of whether CXXBindTemporaryExpr nodes have been evaluated.
  54. // The StackFrameContext assures that nested calls due to inlined recursive
  55. // functions do not interfere.
  56. REGISTER_TRAIT_WITH_PROGRAMSTATE(InitializedTemporariesSet,
  57. llvm::ImmutableSet<CXXBindTemporaryContext>)
  58. typedef llvm::ImmutableMap<std::pair<const CXXNewExpr *,
  59. const LocationContext *>, SVal>
  60. CXXNewAllocatorValuesMap;
  61. // Keeps track of return values of various operator new() calls between
  62. // evaluation of the inlined operator new(), through the constructor call,
  63. // to the actual evaluation of the CXXNewExpr.
  64. // TODO: Refactor the key for this trait into a LocationContext sub-class,
  65. // which would be put on the stack of location contexts before operator new()
  66. // is evaluated, and removed from the stack when the whole CXXNewExpr
  67. // is fully evaluated.
  68. // Probably do something similar to the previous trait as well.
  69. REGISTER_TRAIT_WITH_PROGRAMSTATE(CXXNewAllocatorValues,
  70. CXXNewAllocatorValuesMap)
  71. //===----------------------------------------------------------------------===//
  72. // Engine construction and deletion.
  73. //===----------------------------------------------------------------------===//
  74. static const char* TagProviderName = "ExprEngine";
  75. ExprEngine::ExprEngine(AnalysisManager &mgr, bool gcEnabled,
  76. SetOfConstDecls *VisitedCalleesIn,
  77. FunctionSummariesTy *FS,
  78. InliningModes HowToInlineIn)
  79. : AMgr(mgr),
  80. AnalysisDeclContexts(mgr.getAnalysisDeclContextManager()),
  81. Engine(*this, FS),
  82. G(Engine.getGraph()),
  83. StateMgr(getContext(), mgr.getStoreManagerCreator(),
  84. mgr.getConstraintManagerCreator(), G.getAllocator(),
  85. this),
  86. SymMgr(StateMgr.getSymbolManager()),
  87. svalBuilder(StateMgr.getSValBuilder()),
  88. currStmtIdx(0), currBldrCtx(nullptr),
  89. ObjCNoRet(mgr.getASTContext()),
  90. ObjCGCEnabled(gcEnabled), BR(mgr, *this),
  91. VisitedCallees(VisitedCalleesIn),
  92. HowToInline(HowToInlineIn)
  93. {
  94. unsigned TrimInterval = mgr.options.getGraphTrimInterval();
  95. if (TrimInterval != 0) {
  96. // Enable eager node reclaimation when constructing the ExplodedGraph.
  97. G.enableNodeReclamation(TrimInterval);
  98. }
  99. }
  100. ExprEngine::~ExprEngine() {
  101. BR.FlushReports();
  102. }
  103. //===----------------------------------------------------------------------===//
  104. // Utility methods.
  105. //===----------------------------------------------------------------------===//
  106. ProgramStateRef ExprEngine::getInitialState(const LocationContext *InitLoc) {
  107. ProgramStateRef state = StateMgr.getInitialState(InitLoc);
  108. const Decl *D = InitLoc->getDecl();
  109. // Preconditions.
  110. // FIXME: It would be nice if we had a more general mechanism to add
  111. // such preconditions. Some day.
  112. do {
  113. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  114. // Precondition: the first argument of 'main' is an integer guaranteed
  115. // to be > 0.
  116. const IdentifierInfo *II = FD->getIdentifier();
  117. if (!II || !(II->getName() == "main" && FD->getNumParams() > 0))
  118. break;
  119. const ParmVarDecl *PD = FD->getParamDecl(0);
  120. QualType T = PD->getType();
  121. const BuiltinType *BT = dyn_cast<BuiltinType>(T);
  122. if (!BT || !BT->isInteger())
  123. break;
  124. const MemRegion *R = state->getRegion(PD, InitLoc);
  125. if (!R)
  126. break;
  127. SVal V = state->getSVal(loc::MemRegionVal(R));
  128. SVal Constraint_untested = evalBinOp(state, BO_GT, V,
  129. svalBuilder.makeZeroVal(T),
  130. svalBuilder.getConditionType());
  131. Optional<DefinedOrUnknownSVal> Constraint =
  132. Constraint_untested.getAs<DefinedOrUnknownSVal>();
  133. if (!Constraint)
  134. break;
  135. if (ProgramStateRef newState = state->assume(*Constraint, true))
  136. state = newState;
  137. }
  138. break;
  139. }
  140. while (0);
  141. if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
  142. // Precondition: 'self' is always non-null upon entry to an Objective-C
  143. // method.
  144. const ImplicitParamDecl *SelfD = MD->getSelfDecl();
  145. const MemRegion *R = state->getRegion(SelfD, InitLoc);
  146. SVal V = state->getSVal(loc::MemRegionVal(R));
  147. if (Optional<Loc> LV = V.getAs<Loc>()) {
  148. // Assume that the pointer value in 'self' is non-null.
  149. state = state->assume(*LV, true);
  150. assert(state && "'self' cannot be null");
  151. }
  152. }
  153. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
  154. if (!MD->isStatic()) {
  155. // Precondition: 'this' is always non-null upon entry to the
  156. // top-level function. This is our starting assumption for
  157. // analyzing an "open" program.
  158. const StackFrameContext *SFC = InitLoc->getCurrentStackFrame();
  159. if (SFC->getParent() == nullptr) {
  160. loc::MemRegionVal L = svalBuilder.getCXXThis(MD, SFC);
  161. SVal V = state->getSVal(L);
  162. if (Optional<Loc> LV = V.getAs<Loc>()) {
  163. state = state->assume(*LV, true);
  164. assert(state && "'this' cannot be null");
  165. }
  166. }
  167. }
  168. }
  169. return state;
  170. }
  171. ProgramStateRef
  172. ExprEngine::createTemporaryRegionIfNeeded(ProgramStateRef State,
  173. const LocationContext *LC,
  174. const Expr *InitWithAdjustments,
  175. const Expr *Result) {
  176. // FIXME: This function is a hack that works around the quirky AST
  177. // we're often having with respect to C++ temporaries. If only we modelled
  178. // the actual execution order of statements properly in the CFG,
  179. // all the hassle with adjustments would not be necessary,
  180. // and perhaps the whole function would be removed.
  181. SVal InitValWithAdjustments = State->getSVal(InitWithAdjustments, LC);
  182. if (!Result) {
  183. // If we don't have an explicit result expression, we're in "if needed"
  184. // mode. Only create a region if the current value is a NonLoc.
  185. if (!InitValWithAdjustments.getAs<NonLoc>())
  186. return State;
  187. Result = InitWithAdjustments;
  188. } else {
  189. // We need to create a region no matter what. For sanity, make sure we don't
  190. // try to stuff a Loc into a non-pointer temporary region.
  191. assert(!InitValWithAdjustments.getAs<Loc>() ||
  192. Loc::isLocType(Result->getType()) ||
  193. Result->getType()->isMemberPointerType());
  194. }
  195. ProgramStateManager &StateMgr = State->getStateManager();
  196. MemRegionManager &MRMgr = StateMgr.getRegionManager();
  197. StoreManager &StoreMgr = StateMgr.getStoreManager();
  198. // MaterializeTemporaryExpr may appear out of place, after a few field and
  199. // base-class accesses have been made to the object, even though semantically
  200. // it is the whole object that gets materialized and lifetime-extended.
  201. //
  202. // For example:
  203. //
  204. // `-MaterializeTemporaryExpr
  205. // `-MemberExpr
  206. // `-CXXTemporaryObjectExpr
  207. //
  208. // instead of the more natural
  209. //
  210. // `-MemberExpr
  211. // `-MaterializeTemporaryExpr
  212. // `-CXXTemporaryObjectExpr
  213. //
  214. // Use the usual methods for obtaining the expression of the base object,
  215. // and record the adjustments that we need to make to obtain the sub-object
  216. // that the whole expression 'Ex' refers to. This trick is usual,
  217. // in the sense that CodeGen takes a similar route.
  218. SmallVector<const Expr *, 2> CommaLHSs;
  219. SmallVector<SubobjectAdjustment, 2> Adjustments;
  220. const Expr *Init = InitWithAdjustments->skipRValueSubobjectAdjustments(
  221. CommaLHSs, Adjustments);
  222. const TypedValueRegion *TR = nullptr;
  223. if (const MaterializeTemporaryExpr *MT =
  224. dyn_cast<MaterializeTemporaryExpr>(Result)) {
  225. StorageDuration SD = MT->getStorageDuration();
  226. // If this object is bound to a reference with static storage duration, we
  227. // put it in a different region to prevent "address leakage" warnings.
  228. if (SD == SD_Static || SD == SD_Thread)
  229. TR = MRMgr.getCXXStaticTempObjectRegion(Init);
  230. }
  231. if (!TR)
  232. TR = MRMgr.getCXXTempObjectRegion(Init, LC);
  233. SVal Reg = loc::MemRegionVal(TR);
  234. SVal BaseReg = Reg;
  235. // Make the necessary adjustments to obtain the sub-object.
  236. for (auto I = Adjustments.rbegin(), E = Adjustments.rend(); I != E; ++I) {
  237. const SubobjectAdjustment &Adj = *I;
  238. switch (Adj.Kind) {
  239. case SubobjectAdjustment::DerivedToBaseAdjustment:
  240. Reg = StoreMgr.evalDerivedToBase(Reg, Adj.DerivedToBase.BasePath);
  241. break;
  242. case SubobjectAdjustment::FieldAdjustment:
  243. Reg = StoreMgr.getLValueField(Adj.Field, Reg);
  244. break;
  245. case SubobjectAdjustment::MemberPointerAdjustment:
  246. // FIXME: Unimplemented.
  247. State = State->bindDefault(Reg, UnknownVal(), LC);
  248. return State;
  249. }
  250. }
  251. // What remains is to copy the value of the object to the new region.
  252. // FIXME: In other words, what we should always do is copy value of the
  253. // Init expression (which corresponds to the bigger object) to the whole
  254. // temporary region TR. However, this value is often no longer present
  255. // in the Environment. If it has disappeared, we instead invalidate TR.
  256. // Still, what we can do is assign the value of expression Ex (which
  257. // corresponds to the sub-object) to the TR's sub-region Reg. At least,
  258. // values inside Reg would be correct.
  259. SVal InitVal = State->getSVal(Init, LC);
  260. if (InitVal.isUnknown()) {
  261. InitVal = getSValBuilder().conjureSymbolVal(Result, LC, Init->getType(),
  262. currBldrCtx->blockCount());
  263. State = State->bindLoc(BaseReg.castAs<Loc>(), InitVal, LC, false);
  264. // Then we'd need to take the value that certainly exists and bind it over.
  265. if (InitValWithAdjustments.isUnknown()) {
  266. // Try to recover some path sensitivity in case we couldn't
  267. // compute the value.
  268. InitValWithAdjustments = getSValBuilder().conjureSymbolVal(
  269. Result, LC, InitWithAdjustments->getType(),
  270. currBldrCtx->blockCount());
  271. }
  272. State =
  273. State->bindLoc(Reg.castAs<Loc>(), InitValWithAdjustments, LC, false);
  274. } else {
  275. State = State->bindLoc(BaseReg.castAs<Loc>(), InitVal, LC, false);
  276. }
  277. // The result expression would now point to the correct sub-region of the
  278. // newly created temporary region. Do this last in order to getSVal of Init
  279. // correctly in case (Result == Init).
  280. State = State->BindExpr(Result, LC, Reg);
  281. // Notify checkers once for two bindLoc()s.
  282. State = processRegionChange(State, TR, LC);
  283. return State;
  284. }
  285. ProgramStateRef
  286. ExprEngine::setCXXNewAllocatorValue(ProgramStateRef State,
  287. const CXXNewExpr *CNE,
  288. const LocationContext *CallerLC, SVal V) {
  289. assert(!State->get<CXXNewAllocatorValues>(std::make_pair(CNE, CallerLC)) &&
  290. "Allocator value already set!");
  291. return State->set<CXXNewAllocatorValues>(std::make_pair(CNE, CallerLC), V);
  292. }
  293. SVal ExprEngine::getCXXNewAllocatorValue(ProgramStateRef State,
  294. const CXXNewExpr *CNE,
  295. const LocationContext *CallerLC) {
  296. return *State->get<CXXNewAllocatorValues>(std::make_pair(CNE, CallerLC));
  297. }
  298. ProgramStateRef
  299. ExprEngine::clearCXXNewAllocatorValue(ProgramStateRef State,
  300. const CXXNewExpr *CNE,
  301. const LocationContext *CallerLC) {
  302. return State->remove<CXXNewAllocatorValues>(std::make_pair(CNE, CallerLC));
  303. }
  304. bool ExprEngine::areCXXNewAllocatorValuesClear(ProgramStateRef State,
  305. const LocationContext *FromLC,
  306. const LocationContext *ToLC) {
  307. const LocationContext *LC = FromLC;
  308. do {
  309. for (auto I : State->get<CXXNewAllocatorValues>())
  310. if (I.first.second == LC)
  311. return false;
  312. LC = LC->getParent();
  313. assert(LC && "ToLC must be a parent of FromLC!");
  314. } while (LC != ToLC);
  315. return true;
  316. }
  317. //===----------------------------------------------------------------------===//
  318. // Top-level transfer function logic (Dispatcher).
  319. //===----------------------------------------------------------------------===//
  320. /// evalAssume - Called by ConstraintManager. Used to call checker-specific
  321. /// logic for handling assumptions on symbolic values.
  322. ProgramStateRef ExprEngine::processAssume(ProgramStateRef state,
  323. SVal cond, bool assumption) {
  324. return getCheckerManager().runCheckersForEvalAssume(state, cond, assumption);
  325. }
  326. ProgramStateRef
  327. ExprEngine::processRegionChanges(ProgramStateRef state,
  328. const InvalidatedSymbols *invalidated,
  329. ArrayRef<const MemRegion *> Explicits,
  330. ArrayRef<const MemRegion *> Regions,
  331. const LocationContext *LCtx,
  332. const CallEvent *Call) {
  333. return getCheckerManager().runCheckersForRegionChanges(state, invalidated,
  334. Explicits, Regions,
  335. LCtx, Call);
  336. }
  337. void ExprEngine::printState(raw_ostream &Out, ProgramStateRef State,
  338. const char *NL, const char *Sep) {
  339. getCheckerManager().runCheckersForPrintState(Out, State, NL, Sep);
  340. }
  341. void ExprEngine::processEndWorklist(bool hasWorkRemaining) {
  342. getCheckerManager().runCheckersForEndAnalysis(G, BR, *this);
  343. }
  344. void ExprEngine::processCFGElement(const CFGElement E, ExplodedNode *Pred,
  345. unsigned StmtIdx, NodeBuilderContext *Ctx) {
  346. PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
  347. currStmtIdx = StmtIdx;
  348. currBldrCtx = Ctx;
  349. switch (E.getKind()) {
  350. case CFGElement::Statement:
  351. ProcessStmt(const_cast<Stmt*>(E.castAs<CFGStmt>().getStmt()), Pred);
  352. return;
  353. case CFGElement::Initializer:
  354. ProcessInitializer(E.castAs<CFGInitializer>().getInitializer(), Pred);
  355. return;
  356. case CFGElement::NewAllocator:
  357. ProcessNewAllocator(E.castAs<CFGNewAllocator>().getAllocatorExpr(),
  358. Pred);
  359. return;
  360. case CFGElement::AutomaticObjectDtor:
  361. case CFGElement::DeleteDtor:
  362. case CFGElement::BaseDtor:
  363. case CFGElement::MemberDtor:
  364. case CFGElement::TemporaryDtor:
  365. ProcessImplicitDtor(E.castAs<CFGImplicitDtor>(), Pred);
  366. return;
  367. case CFGElement::LoopExit:
  368. ProcessLoopExit(E.castAs<CFGLoopExit>().getLoopStmt(), Pred);
  369. return;
  370. case CFGElement::LifetimeEnds:
  371. return;
  372. }
  373. }
  374. static bool shouldRemoveDeadBindings(AnalysisManager &AMgr,
  375. const CFGStmt S,
  376. const ExplodedNode *Pred,
  377. const LocationContext *LC) {
  378. // Are we never purging state values?
  379. if (AMgr.options.AnalysisPurgeOpt == PurgeNone)
  380. return false;
  381. // Is this the beginning of a basic block?
  382. if (Pred->getLocation().getAs<BlockEntrance>())
  383. return true;
  384. // Is this on a non-expression?
  385. if (!isa<Expr>(S.getStmt()))
  386. return true;
  387. // Run before processing a call.
  388. if (CallEvent::isCallStmt(S.getStmt()))
  389. return true;
  390. // Is this an expression that is consumed by another expression? If so,
  391. // postpone cleaning out the state.
  392. ParentMap &PM = LC->getAnalysisDeclContext()->getParentMap();
  393. return !PM.isConsumedExpr(cast<Expr>(S.getStmt()));
  394. }
  395. void ExprEngine::removeDead(ExplodedNode *Pred, ExplodedNodeSet &Out,
  396. const Stmt *ReferenceStmt,
  397. const LocationContext *LC,
  398. const Stmt *DiagnosticStmt,
  399. ProgramPoint::Kind K) {
  400. assert((K == ProgramPoint::PreStmtPurgeDeadSymbolsKind ||
  401. ReferenceStmt == nullptr || isa<ReturnStmt>(ReferenceStmt))
  402. && "PostStmt is not generally supported by the SymbolReaper yet");
  403. assert(LC && "Must pass the current (or expiring) LocationContext");
  404. if (!DiagnosticStmt) {
  405. DiagnosticStmt = ReferenceStmt;
  406. assert(DiagnosticStmt && "Required for clearing a LocationContext");
  407. }
  408. NumRemoveDeadBindings++;
  409. ProgramStateRef CleanedState = Pred->getState();
  410. // LC is the location context being destroyed, but SymbolReaper wants a
  411. // location context that is still live. (If this is the top-level stack
  412. // frame, this will be null.)
  413. if (!ReferenceStmt) {
  414. assert(K == ProgramPoint::PostStmtPurgeDeadSymbolsKind &&
  415. "Use PostStmtPurgeDeadSymbolsKind for clearing a LocationContext");
  416. LC = LC->getParent();
  417. }
  418. const StackFrameContext *SFC = LC ? LC->getCurrentStackFrame() : nullptr;
  419. SymbolReaper SymReaper(SFC, ReferenceStmt, SymMgr, getStoreManager());
  420. for (auto I : CleanedState->get<CXXNewAllocatorValues>()) {
  421. if (SymbolRef Sym = I.second.getAsSymbol())
  422. SymReaper.markLive(Sym);
  423. if (const MemRegion *MR = I.second.getAsRegion())
  424. SymReaper.markElementIndicesLive(MR);
  425. }
  426. getCheckerManager().runCheckersForLiveSymbols(CleanedState, SymReaper);
  427. // Create a state in which dead bindings are removed from the environment
  428. // and the store. TODO: The function should just return new env and store,
  429. // not a new state.
  430. CleanedState = StateMgr.removeDeadBindings(CleanedState, SFC, SymReaper);
  431. // Process any special transfer function for dead symbols.
  432. // A tag to track convenience transitions, which can be removed at cleanup.
  433. static SimpleProgramPointTag cleanupTag(TagProviderName, "Clean Node");
  434. if (!SymReaper.hasDeadSymbols()) {
  435. // Generate a CleanedNode that has the environment and store cleaned
  436. // up. Since no symbols are dead, we can optimize and not clean out
  437. // the constraint manager.
  438. StmtNodeBuilder Bldr(Pred, Out, *currBldrCtx);
  439. Bldr.generateNode(DiagnosticStmt, Pred, CleanedState, &cleanupTag, K);
  440. } else {
  441. // Call checkers with the non-cleaned state so that they could query the
  442. // values of the soon to be dead symbols.
  443. ExplodedNodeSet CheckedSet;
  444. getCheckerManager().runCheckersForDeadSymbols(CheckedSet, Pred, SymReaper,
  445. DiagnosticStmt, *this, K);
  446. // For each node in CheckedSet, generate CleanedNodes that have the
  447. // environment, the store, and the constraints cleaned up but have the
  448. // user-supplied states as the predecessors.
  449. StmtNodeBuilder Bldr(CheckedSet, Out, *currBldrCtx);
  450. for (ExplodedNodeSet::const_iterator
  451. I = CheckedSet.begin(), E = CheckedSet.end(); I != E; ++I) {
  452. ProgramStateRef CheckerState = (*I)->getState();
  453. // The constraint manager has not been cleaned up yet, so clean up now.
  454. CheckerState = getConstraintManager().removeDeadBindings(CheckerState,
  455. SymReaper);
  456. assert(StateMgr.haveEqualEnvironments(CheckerState, Pred->getState()) &&
  457. "Checkers are not allowed to modify the Environment as a part of "
  458. "checkDeadSymbols processing.");
  459. assert(StateMgr.haveEqualStores(CheckerState, Pred->getState()) &&
  460. "Checkers are not allowed to modify the Store as a part of "
  461. "checkDeadSymbols processing.");
  462. // Create a state based on CleanedState with CheckerState GDM and
  463. // generate a transition to that state.
  464. ProgramStateRef CleanedCheckerSt =
  465. StateMgr.getPersistentStateWithGDM(CleanedState, CheckerState);
  466. Bldr.generateNode(DiagnosticStmt, *I, CleanedCheckerSt, &cleanupTag, K);
  467. }
  468. }
  469. }
  470. void ExprEngine::ProcessStmt(const CFGStmt S,
  471. ExplodedNode *Pred) {
  472. // Reclaim any unnecessary nodes in the ExplodedGraph.
  473. G.reclaimRecentlyAllocatedNodes();
  474. const Stmt *currStmt = S.getStmt();
  475. PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
  476. currStmt->getLocStart(),
  477. "Error evaluating statement");
  478. // Remove dead bindings and symbols.
  479. ExplodedNodeSet CleanedStates;
  480. if (shouldRemoveDeadBindings(AMgr, S, Pred, Pred->getLocationContext())){
  481. removeDead(Pred, CleanedStates, currStmt, Pred->getLocationContext());
  482. } else
  483. CleanedStates.Add(Pred);
  484. // Visit the statement.
  485. ExplodedNodeSet Dst;
  486. for (ExplodedNodeSet::iterator I = CleanedStates.begin(),
  487. E = CleanedStates.end(); I != E; ++I) {
  488. ExplodedNodeSet DstI;
  489. // Visit the statement.
  490. Visit(currStmt, *I, DstI);
  491. Dst.insert(DstI);
  492. }
  493. // Enqueue the new nodes onto the work list.
  494. Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
  495. }
  496. void ExprEngine::ProcessLoopExit(const Stmt* S, ExplodedNode *Pred) {
  497. PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
  498. S->getLocStart(),
  499. "Error evaluating end of the loop");
  500. ExplodedNodeSet Dst;
  501. Dst.Add(Pred);
  502. NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
  503. ProgramStateRef NewState = Pred->getState();
  504. if(AMgr.options.shouldUnrollLoops())
  505. NewState = processLoopEnd(S, NewState);
  506. LoopExit PP(S, Pred->getLocationContext());
  507. Bldr.generateNode(PP, NewState, Pred);
  508. // Enqueue the new nodes onto the work list.
  509. Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
  510. }
  511. void ExprEngine::ProcessInitializer(const CFGInitializer Init,
  512. ExplodedNode *Pred) {
  513. const CXXCtorInitializer *BMI = Init.getInitializer();
  514. PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
  515. BMI->getSourceLocation(),
  516. "Error evaluating initializer");
  517. // We don't clean up dead bindings here.
  518. const StackFrameContext *stackFrame =
  519. cast<StackFrameContext>(Pred->getLocationContext());
  520. const CXXConstructorDecl *decl =
  521. cast<CXXConstructorDecl>(stackFrame->getDecl());
  522. ProgramStateRef State = Pred->getState();
  523. SVal thisVal = State->getSVal(svalBuilder.getCXXThis(decl, stackFrame));
  524. ExplodedNodeSet Tmp(Pred);
  525. SVal FieldLoc;
  526. // Evaluate the initializer, if necessary
  527. if (BMI->isAnyMemberInitializer()) {
  528. // Constructors build the object directly in the field,
  529. // but non-objects must be copied in from the initializer.
  530. if (auto *CtorExpr = findDirectConstructorForCurrentCFGElement()) {
  531. assert(BMI->getInit()->IgnoreImplicit() == CtorExpr);
  532. (void)CtorExpr;
  533. // The field was directly constructed, so there is no need to bind.
  534. } else {
  535. const Expr *Init = BMI->getInit()->IgnoreImplicit();
  536. const ValueDecl *Field;
  537. if (BMI->isIndirectMemberInitializer()) {
  538. Field = BMI->getIndirectMember();
  539. FieldLoc = State->getLValue(BMI->getIndirectMember(), thisVal);
  540. } else {
  541. Field = BMI->getMember();
  542. FieldLoc = State->getLValue(BMI->getMember(), thisVal);
  543. }
  544. SVal InitVal;
  545. if (Init->getType()->isArrayType()) {
  546. // Handle arrays of trivial type. We can represent this with a
  547. // primitive load/copy from the base array region.
  548. const ArraySubscriptExpr *ASE;
  549. while ((ASE = dyn_cast<ArraySubscriptExpr>(Init)))
  550. Init = ASE->getBase()->IgnoreImplicit();
  551. SVal LValue = State->getSVal(Init, stackFrame);
  552. if (!Field->getType()->isReferenceType())
  553. if (Optional<Loc> LValueLoc = LValue.getAs<Loc>())
  554. InitVal = State->getSVal(*LValueLoc);
  555. // If we fail to get the value for some reason, use a symbolic value.
  556. if (InitVal.isUnknownOrUndef()) {
  557. SValBuilder &SVB = getSValBuilder();
  558. InitVal = SVB.conjureSymbolVal(BMI->getInit(), stackFrame,
  559. Field->getType(),
  560. currBldrCtx->blockCount());
  561. }
  562. } else {
  563. InitVal = State->getSVal(BMI->getInit(), stackFrame);
  564. }
  565. assert(Tmp.size() == 1 && "have not generated any new nodes yet");
  566. assert(*Tmp.begin() == Pred && "have not generated any new nodes yet");
  567. Tmp.clear();
  568. PostInitializer PP(BMI, FieldLoc.getAsRegion(), stackFrame);
  569. evalBind(Tmp, Init, Pred, FieldLoc, InitVal, /*isInit=*/true, &PP);
  570. }
  571. } else {
  572. assert(BMI->isBaseInitializer() || BMI->isDelegatingInitializer());
  573. // We already did all the work when visiting the CXXConstructExpr.
  574. }
  575. // Construct PostInitializer nodes whether the state changed or not,
  576. // so that the diagnostics don't get confused.
  577. PostInitializer PP(BMI, FieldLoc.getAsRegion(), stackFrame);
  578. ExplodedNodeSet Dst;
  579. NodeBuilder Bldr(Tmp, Dst, *currBldrCtx);
  580. for (ExplodedNodeSet::iterator I = Tmp.begin(), E = Tmp.end(); I != E; ++I) {
  581. ExplodedNode *N = *I;
  582. Bldr.generateNode(PP, N->getState(), N);
  583. }
  584. // Enqueue the new nodes onto the work list.
  585. Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
  586. }
  587. void ExprEngine::ProcessImplicitDtor(const CFGImplicitDtor D,
  588. ExplodedNode *Pred) {
  589. ExplodedNodeSet Dst;
  590. switch (D.getKind()) {
  591. case CFGElement::AutomaticObjectDtor:
  592. ProcessAutomaticObjDtor(D.castAs<CFGAutomaticObjDtor>(), Pred, Dst);
  593. break;
  594. case CFGElement::BaseDtor:
  595. ProcessBaseDtor(D.castAs<CFGBaseDtor>(), Pred, Dst);
  596. break;
  597. case CFGElement::MemberDtor:
  598. ProcessMemberDtor(D.castAs<CFGMemberDtor>(), Pred, Dst);
  599. break;
  600. case CFGElement::TemporaryDtor:
  601. ProcessTemporaryDtor(D.castAs<CFGTemporaryDtor>(), Pred, Dst);
  602. break;
  603. case CFGElement::DeleteDtor:
  604. ProcessDeleteDtor(D.castAs<CFGDeleteDtor>(), Pred, Dst);
  605. break;
  606. default:
  607. llvm_unreachable("Unexpected dtor kind.");
  608. }
  609. // Enqueue the new nodes onto the work list.
  610. Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
  611. }
  612. void ExprEngine::ProcessNewAllocator(const CXXNewExpr *NE,
  613. ExplodedNode *Pred) {
  614. ExplodedNodeSet Dst;
  615. AnalysisManager &AMgr = getAnalysisManager();
  616. AnalyzerOptions &Opts = AMgr.options;
  617. // TODO: We're not evaluating allocators for all cases just yet as
  618. // we're not handling the return value correctly, which causes false
  619. // positives when the alpha.cplusplus.NewDeleteLeaks check is on.
  620. if (Opts.mayInlineCXXAllocator())
  621. VisitCXXNewAllocatorCall(NE, Pred, Dst);
  622. else {
  623. NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
  624. const LocationContext *LCtx = Pred->getLocationContext();
  625. PostImplicitCall PP(NE->getOperatorNew(), NE->getLocStart(), LCtx);
  626. Bldr.generateNode(PP, Pred->getState(), Pred);
  627. }
  628. Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
  629. }
  630. void ExprEngine::ProcessAutomaticObjDtor(const CFGAutomaticObjDtor Dtor,
  631. ExplodedNode *Pred,
  632. ExplodedNodeSet &Dst) {
  633. const VarDecl *varDecl = Dtor.getVarDecl();
  634. QualType varType = varDecl->getType();
  635. ProgramStateRef state = Pred->getState();
  636. SVal dest = state->getLValue(varDecl, Pred->getLocationContext());
  637. const MemRegion *Region = dest.castAs<loc::MemRegionVal>().getRegion();
  638. if (varType->isReferenceType()) {
  639. const MemRegion *ValueRegion = state->getSVal(Region).getAsRegion();
  640. if (!ValueRegion) {
  641. // FIXME: This should not happen. The language guarantees a presence
  642. // of a valid initializer here, so the reference shall not be undefined.
  643. // It seems that we're calling destructors over variables that
  644. // were not initialized yet.
  645. return;
  646. }
  647. Region = ValueRegion->getBaseRegion();
  648. varType = cast<TypedValueRegion>(Region)->getValueType();
  649. }
  650. VisitCXXDestructor(varType, Region, Dtor.getTriggerStmt(), /*IsBase=*/ false,
  651. Pred, Dst);
  652. }
  653. void ExprEngine::ProcessDeleteDtor(const CFGDeleteDtor Dtor,
  654. ExplodedNode *Pred,
  655. ExplodedNodeSet &Dst) {
  656. ProgramStateRef State = Pred->getState();
  657. const LocationContext *LCtx = Pred->getLocationContext();
  658. const CXXDeleteExpr *DE = Dtor.getDeleteExpr();
  659. const Stmt *Arg = DE->getArgument();
  660. SVal ArgVal = State->getSVal(Arg, LCtx);
  661. // If the argument to delete is known to be a null value,
  662. // don't run destructor.
  663. if (State->isNull(ArgVal).isConstrainedTrue()) {
  664. QualType DTy = DE->getDestroyedType();
  665. QualType BTy = getContext().getBaseElementType(DTy);
  666. const CXXRecordDecl *RD = BTy->getAsCXXRecordDecl();
  667. const CXXDestructorDecl *Dtor = RD->getDestructor();
  668. PostImplicitCall PP(Dtor, DE->getLocStart(), LCtx);
  669. NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
  670. Bldr.generateNode(PP, Pred->getState(), Pred);
  671. return;
  672. }
  673. VisitCXXDestructor(DE->getDestroyedType(),
  674. ArgVal.getAsRegion(),
  675. DE, /*IsBase=*/ false,
  676. Pred, Dst);
  677. }
  678. void ExprEngine::ProcessBaseDtor(const CFGBaseDtor D,
  679. ExplodedNode *Pred, ExplodedNodeSet &Dst) {
  680. const LocationContext *LCtx = Pred->getLocationContext();
  681. const CXXDestructorDecl *CurDtor = cast<CXXDestructorDecl>(LCtx->getDecl());
  682. Loc ThisPtr = getSValBuilder().getCXXThis(CurDtor,
  683. LCtx->getCurrentStackFrame());
  684. SVal ThisVal = Pred->getState()->getSVal(ThisPtr);
  685. // Create the base object region.
  686. const CXXBaseSpecifier *Base = D.getBaseSpecifier();
  687. QualType BaseTy = Base->getType();
  688. SVal BaseVal = getStoreManager().evalDerivedToBase(ThisVal, BaseTy,
  689. Base->isVirtual());
  690. VisitCXXDestructor(BaseTy, BaseVal.castAs<loc::MemRegionVal>().getRegion(),
  691. CurDtor->getBody(), /*IsBase=*/ true, Pred, Dst);
  692. }
  693. void ExprEngine::ProcessMemberDtor(const CFGMemberDtor D,
  694. ExplodedNode *Pred, ExplodedNodeSet &Dst) {
  695. const FieldDecl *Member = D.getFieldDecl();
  696. ProgramStateRef State = Pred->getState();
  697. const LocationContext *LCtx = Pred->getLocationContext();
  698. const CXXDestructorDecl *CurDtor = cast<CXXDestructorDecl>(LCtx->getDecl());
  699. Loc ThisVal = getSValBuilder().getCXXThis(CurDtor,
  700. LCtx->getCurrentStackFrame());
  701. SVal FieldVal =
  702. State->getLValue(Member, State->getSVal(ThisVal).castAs<Loc>());
  703. VisitCXXDestructor(Member->getType(),
  704. FieldVal.castAs<loc::MemRegionVal>().getRegion(),
  705. CurDtor->getBody(), /*IsBase=*/false, Pred, Dst);
  706. }
  707. void ExprEngine::ProcessTemporaryDtor(const CFGTemporaryDtor D,
  708. ExplodedNode *Pred,
  709. ExplodedNodeSet &Dst) {
  710. ExplodedNodeSet CleanDtorState;
  711. StmtNodeBuilder StmtBldr(Pred, CleanDtorState, *currBldrCtx);
  712. ProgramStateRef State = Pred->getState();
  713. if (State->contains<InitializedTemporariesSet>(
  714. std::make_pair(D.getBindTemporaryExpr(), Pred->getStackFrame()))) {
  715. // FIXME: Currently we insert temporary destructors for default parameters,
  716. // but we don't insert the constructors.
  717. State = State->remove<InitializedTemporariesSet>(
  718. std::make_pair(D.getBindTemporaryExpr(), Pred->getStackFrame()));
  719. }
  720. StmtBldr.generateNode(D.getBindTemporaryExpr(), Pred, State);
  721. QualType varType = D.getBindTemporaryExpr()->getSubExpr()->getType();
  722. // FIXME: Currently CleanDtorState can be empty here due to temporaries being
  723. // bound to default parameters.
  724. assert(CleanDtorState.size() <= 1);
  725. ExplodedNode *CleanPred =
  726. CleanDtorState.empty() ? Pred : *CleanDtorState.begin();
  727. // FIXME: Inlining of temporary destructors is not supported yet anyway, so
  728. // we just put a NULL region for now. This will need to be changed later.
  729. VisitCXXDestructor(varType, nullptr, D.getBindTemporaryExpr(),
  730. /*IsBase=*/false, CleanPred, Dst);
  731. }
  732. void ExprEngine::processCleanupTemporaryBranch(const CXXBindTemporaryExpr *BTE,
  733. NodeBuilderContext &BldCtx,
  734. ExplodedNode *Pred,
  735. ExplodedNodeSet &Dst,
  736. const CFGBlock *DstT,
  737. const CFGBlock *DstF) {
  738. BranchNodeBuilder TempDtorBuilder(Pred, Dst, BldCtx, DstT, DstF);
  739. if (Pred->getState()->contains<InitializedTemporariesSet>(
  740. std::make_pair(BTE, Pred->getStackFrame()))) {
  741. TempDtorBuilder.markInfeasible(false);
  742. TempDtorBuilder.generateNode(Pred->getState(), true, Pred);
  743. } else {
  744. TempDtorBuilder.markInfeasible(true);
  745. TempDtorBuilder.generateNode(Pred->getState(), false, Pred);
  746. }
  747. }
  748. void ExprEngine::VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *BTE,
  749. ExplodedNodeSet &PreVisit,
  750. ExplodedNodeSet &Dst) {
  751. if (!getAnalysisManager().options.includeTemporaryDtorsInCFG()) {
  752. // In case we don't have temporary destructors in the CFG, do not mark
  753. // the initialization - we would otherwise never clean it up.
  754. Dst = PreVisit;
  755. return;
  756. }
  757. StmtNodeBuilder StmtBldr(PreVisit, Dst, *currBldrCtx);
  758. for (ExplodedNode *Node : PreVisit) {
  759. ProgramStateRef State = Node->getState();
  760. if (!State->contains<InitializedTemporariesSet>(
  761. std::make_pair(BTE, Node->getStackFrame()))) {
  762. // FIXME: Currently the state might already contain the marker due to
  763. // incorrect handling of temporaries bound to default parameters; for
  764. // those, we currently skip the CXXBindTemporaryExpr but rely on adding
  765. // temporary destructor nodes.
  766. State = State->add<InitializedTemporariesSet>(
  767. std::make_pair(BTE, Node->getStackFrame()));
  768. }
  769. StmtBldr.generateNode(BTE, Node, State);
  770. }
  771. }
  772. namespace {
  773. class CollectReachableSymbolsCallback final : public SymbolVisitor {
  774. InvalidatedSymbols Symbols;
  775. public:
  776. explicit CollectReachableSymbolsCallback(ProgramStateRef State) {}
  777. const InvalidatedSymbols &getSymbols() const { return Symbols; }
  778. bool VisitSymbol(SymbolRef Sym) override {
  779. Symbols.insert(Sym);
  780. return true;
  781. }
  782. };
  783. } // end anonymous namespace
  784. void ExprEngine::Visit(const Stmt *S, ExplodedNode *Pred,
  785. ExplodedNodeSet &DstTop) {
  786. PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
  787. S->getLocStart(),
  788. "Error evaluating statement");
  789. ExplodedNodeSet Dst;
  790. StmtNodeBuilder Bldr(Pred, DstTop, *currBldrCtx);
  791. assert(!isa<Expr>(S) || S == cast<Expr>(S)->IgnoreParens());
  792. switch (S->getStmtClass()) {
  793. // C++, OpenMP and ARC stuff we don't support yet.
  794. case Expr::ObjCIndirectCopyRestoreExprClass:
  795. case Stmt::CXXDependentScopeMemberExprClass:
  796. case Stmt::CXXInheritedCtorInitExprClass:
  797. case Stmt::CXXTryStmtClass:
  798. case Stmt::CXXTypeidExprClass:
  799. case Stmt::CXXUuidofExprClass:
  800. case Stmt::CXXFoldExprClass:
  801. case Stmt::MSPropertyRefExprClass:
  802. case Stmt::MSPropertySubscriptExprClass:
  803. case Stmt::CXXUnresolvedConstructExprClass:
  804. case Stmt::DependentScopeDeclRefExprClass:
  805. case Stmt::ArrayTypeTraitExprClass:
  806. case Stmt::ExpressionTraitExprClass:
  807. case Stmt::UnresolvedLookupExprClass:
  808. case Stmt::UnresolvedMemberExprClass:
  809. case Stmt::TypoExprClass:
  810. case Stmt::CXXNoexceptExprClass:
  811. case Stmt::PackExpansionExprClass:
  812. case Stmt::SubstNonTypeTemplateParmPackExprClass:
  813. case Stmt::FunctionParmPackExprClass:
  814. case Stmt::CoroutineBodyStmtClass:
  815. case Stmt::CoawaitExprClass:
  816. case Stmt::DependentCoawaitExprClass:
  817. case Stmt::CoreturnStmtClass:
  818. case Stmt::CoyieldExprClass:
  819. case Stmt::SEHTryStmtClass:
  820. case Stmt::SEHExceptStmtClass:
  821. case Stmt::SEHLeaveStmtClass:
  822. case Stmt::SEHFinallyStmtClass:
  823. case Stmt::OMPParallelDirectiveClass:
  824. case Stmt::OMPSimdDirectiveClass:
  825. case Stmt::OMPForDirectiveClass:
  826. case Stmt::OMPForSimdDirectiveClass:
  827. case Stmt::OMPSectionsDirectiveClass:
  828. case Stmt::OMPSectionDirectiveClass:
  829. case Stmt::OMPSingleDirectiveClass:
  830. case Stmt::OMPMasterDirectiveClass:
  831. case Stmt::OMPCriticalDirectiveClass:
  832. case Stmt::OMPParallelForDirectiveClass:
  833. case Stmt::OMPParallelForSimdDirectiveClass:
  834. case Stmt::OMPParallelSectionsDirectiveClass:
  835. case Stmt::OMPTaskDirectiveClass:
  836. case Stmt::OMPTaskyieldDirectiveClass:
  837. case Stmt::OMPBarrierDirectiveClass:
  838. case Stmt::OMPTaskwaitDirectiveClass:
  839. case Stmt::OMPTaskgroupDirectiveClass:
  840. case Stmt::OMPFlushDirectiveClass:
  841. case Stmt::OMPOrderedDirectiveClass:
  842. case Stmt::OMPAtomicDirectiveClass:
  843. case Stmt::OMPTargetDirectiveClass:
  844. case Stmt::OMPTargetDataDirectiveClass:
  845. case Stmt::OMPTargetEnterDataDirectiveClass:
  846. case Stmt::OMPTargetExitDataDirectiveClass:
  847. case Stmt::OMPTargetParallelDirectiveClass:
  848. case Stmt::OMPTargetParallelForDirectiveClass:
  849. case Stmt::OMPTargetUpdateDirectiveClass:
  850. case Stmt::OMPTeamsDirectiveClass:
  851. case Stmt::OMPCancellationPointDirectiveClass:
  852. case Stmt::OMPCancelDirectiveClass:
  853. case Stmt::OMPTaskLoopDirectiveClass:
  854. case Stmt::OMPTaskLoopSimdDirectiveClass:
  855. case Stmt::OMPDistributeDirectiveClass:
  856. case Stmt::OMPDistributeParallelForDirectiveClass:
  857. case Stmt::OMPDistributeParallelForSimdDirectiveClass:
  858. case Stmt::OMPDistributeSimdDirectiveClass:
  859. case Stmt::OMPTargetParallelForSimdDirectiveClass:
  860. case Stmt::OMPTargetSimdDirectiveClass:
  861. case Stmt::OMPTeamsDistributeDirectiveClass:
  862. case Stmt::OMPTeamsDistributeSimdDirectiveClass:
  863. case Stmt::OMPTeamsDistributeParallelForSimdDirectiveClass:
  864. case Stmt::OMPTeamsDistributeParallelForDirectiveClass:
  865. case Stmt::OMPTargetTeamsDirectiveClass:
  866. case Stmt::OMPTargetTeamsDistributeDirectiveClass:
  867. case Stmt::OMPTargetTeamsDistributeParallelForDirectiveClass:
  868. case Stmt::OMPTargetTeamsDistributeParallelForSimdDirectiveClass:
  869. case Stmt::OMPTargetTeamsDistributeSimdDirectiveClass:
  870. case Stmt::CapturedStmtClass:
  871. {
  872. const ExplodedNode *node = Bldr.generateSink(S, Pred, Pred->getState());
  873. Engine.addAbortedBlock(node, currBldrCtx->getBlock());
  874. break;
  875. }
  876. case Stmt::ParenExprClass:
  877. llvm_unreachable("ParenExprs already handled.");
  878. case Stmt::GenericSelectionExprClass:
  879. llvm_unreachable("GenericSelectionExprs already handled.");
  880. // Cases that should never be evaluated simply because they shouldn't
  881. // appear in the CFG.
  882. case Stmt::BreakStmtClass:
  883. case Stmt::CaseStmtClass:
  884. case Stmt::CompoundStmtClass:
  885. case Stmt::ContinueStmtClass:
  886. case Stmt::CXXForRangeStmtClass:
  887. case Stmt::DefaultStmtClass:
  888. case Stmt::DoStmtClass:
  889. case Stmt::ForStmtClass:
  890. case Stmt::GotoStmtClass:
  891. case Stmt::IfStmtClass:
  892. case Stmt::IndirectGotoStmtClass:
  893. case Stmt::LabelStmtClass:
  894. case Stmt::NoStmtClass:
  895. case Stmt::NullStmtClass:
  896. case Stmt::SwitchStmtClass:
  897. case Stmt::WhileStmtClass:
  898. case Expr::MSDependentExistsStmtClass:
  899. llvm_unreachable("Stmt should not be in analyzer evaluation loop");
  900. case Stmt::ObjCSubscriptRefExprClass:
  901. case Stmt::ObjCPropertyRefExprClass:
  902. llvm_unreachable("These are handled by PseudoObjectExpr");
  903. case Stmt::GNUNullExprClass: {
  904. // GNU __null is a pointer-width integer, not an actual pointer.
  905. ProgramStateRef state = Pred->getState();
  906. state = state->BindExpr(S, Pred->getLocationContext(),
  907. svalBuilder.makeIntValWithPtrWidth(0, false));
  908. Bldr.generateNode(S, Pred, state);
  909. break;
  910. }
  911. case Stmt::ObjCAtSynchronizedStmtClass:
  912. Bldr.takeNodes(Pred);
  913. VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S), Pred, Dst);
  914. Bldr.addNodes(Dst);
  915. break;
  916. case Stmt::ExprWithCleanupsClass:
  917. // Handled due to fully linearised CFG.
  918. break;
  919. case Stmt::CXXBindTemporaryExprClass: {
  920. Bldr.takeNodes(Pred);
  921. ExplodedNodeSet PreVisit;
  922. getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
  923. ExplodedNodeSet Next;
  924. VisitCXXBindTemporaryExpr(cast<CXXBindTemporaryExpr>(S), PreVisit, Next);
  925. getCheckerManager().runCheckersForPostStmt(Dst, Next, S, *this);
  926. Bldr.addNodes(Dst);
  927. break;
  928. }
  929. // Cases not handled yet; but will handle some day.
  930. case Stmt::DesignatedInitExprClass:
  931. case Stmt::DesignatedInitUpdateExprClass:
  932. case Stmt::ArrayInitLoopExprClass:
  933. case Stmt::ArrayInitIndexExprClass:
  934. case Stmt::ExtVectorElementExprClass:
  935. case Stmt::ImaginaryLiteralClass:
  936. case Stmt::ObjCAtCatchStmtClass:
  937. case Stmt::ObjCAtFinallyStmtClass:
  938. case Stmt::ObjCAtTryStmtClass:
  939. case Stmt::ObjCAutoreleasePoolStmtClass:
  940. case Stmt::ObjCEncodeExprClass:
  941. case Stmt::ObjCIsaExprClass:
  942. case Stmt::ObjCProtocolExprClass:
  943. case Stmt::ObjCSelectorExprClass:
  944. case Stmt::ParenListExprClass:
  945. case Stmt::ShuffleVectorExprClass:
  946. case Stmt::ConvertVectorExprClass:
  947. case Stmt::VAArgExprClass:
  948. case Stmt::CUDAKernelCallExprClass:
  949. case Stmt::OpaqueValueExprClass:
  950. case Stmt::AsTypeExprClass:
  951. // Fall through.
  952. // Cases we intentionally don't evaluate, since they don't need
  953. // to be explicitly evaluated.
  954. case Stmt::PredefinedExprClass:
  955. case Stmt::AddrLabelExprClass:
  956. case Stmt::AttributedStmtClass:
  957. case Stmt::IntegerLiteralClass:
  958. case Stmt::CharacterLiteralClass:
  959. case Stmt::ImplicitValueInitExprClass:
  960. case Stmt::CXXScalarValueInitExprClass:
  961. case Stmt::CXXBoolLiteralExprClass:
  962. case Stmt::ObjCBoolLiteralExprClass:
  963. case Stmt::ObjCAvailabilityCheckExprClass:
  964. case Stmt::FloatingLiteralClass:
  965. case Stmt::NoInitExprClass:
  966. case Stmt::SizeOfPackExprClass:
  967. case Stmt::StringLiteralClass:
  968. case Stmt::ObjCStringLiteralClass:
  969. case Stmt::CXXPseudoDestructorExprClass:
  970. case Stmt::SubstNonTypeTemplateParmExprClass:
  971. case Stmt::CXXNullPtrLiteralExprClass:
  972. case Stmt::OMPArraySectionExprClass:
  973. case Stmt::TypeTraitExprClass: {
  974. Bldr.takeNodes(Pred);
  975. ExplodedNodeSet preVisit;
  976. getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this);
  977. getCheckerManager().runCheckersForPostStmt(Dst, preVisit, S, *this);
  978. Bldr.addNodes(Dst);
  979. break;
  980. }
  981. case Stmt::CXXDefaultArgExprClass:
  982. case Stmt::CXXDefaultInitExprClass: {
  983. Bldr.takeNodes(Pred);
  984. ExplodedNodeSet PreVisit;
  985. getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
  986. ExplodedNodeSet Tmp;
  987. StmtNodeBuilder Bldr2(PreVisit, Tmp, *currBldrCtx);
  988. const Expr *ArgE;
  989. if (const CXXDefaultArgExpr *DefE = dyn_cast<CXXDefaultArgExpr>(S))
  990. ArgE = DefE->getExpr();
  991. else if (const CXXDefaultInitExpr *DefE = dyn_cast<CXXDefaultInitExpr>(S))
  992. ArgE = DefE->getExpr();
  993. else
  994. llvm_unreachable("unknown constant wrapper kind");
  995. bool IsTemporary = false;
  996. if (const MaterializeTemporaryExpr *MTE =
  997. dyn_cast<MaterializeTemporaryExpr>(ArgE)) {
  998. ArgE = MTE->GetTemporaryExpr();
  999. IsTemporary = true;
  1000. }
  1001. Optional<SVal> ConstantVal = svalBuilder.getConstantVal(ArgE);
  1002. if (!ConstantVal)
  1003. ConstantVal = UnknownVal();
  1004. const LocationContext *LCtx = Pred->getLocationContext();
  1005. for (ExplodedNodeSet::iterator I = PreVisit.begin(), E = PreVisit.end();
  1006. I != E; ++I) {
  1007. ProgramStateRef State = (*I)->getState();
  1008. State = State->BindExpr(S, LCtx, *ConstantVal);
  1009. if (IsTemporary)
  1010. State = createTemporaryRegionIfNeeded(State, LCtx,
  1011. cast<Expr>(S),
  1012. cast<Expr>(S));
  1013. Bldr2.generateNode(S, *I, State);
  1014. }
  1015. getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this);
  1016. Bldr.addNodes(Dst);
  1017. break;
  1018. }
  1019. // Cases we evaluate as opaque expressions, conjuring a symbol.
  1020. case Stmt::CXXStdInitializerListExprClass:
  1021. case Expr::ObjCArrayLiteralClass:
  1022. case Expr::ObjCDictionaryLiteralClass:
  1023. case Expr::ObjCBoxedExprClass: {
  1024. Bldr.takeNodes(Pred);
  1025. ExplodedNodeSet preVisit;
  1026. getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this);
  1027. ExplodedNodeSet Tmp;
  1028. StmtNodeBuilder Bldr2(preVisit, Tmp, *currBldrCtx);
  1029. const Expr *Ex = cast<Expr>(S);
  1030. QualType resultType = Ex->getType();
  1031. for (ExplodedNodeSet::iterator it = preVisit.begin(), et = preVisit.end();
  1032. it != et; ++it) {
  1033. ExplodedNode *N = *it;
  1034. const LocationContext *LCtx = N->getLocationContext();
  1035. SVal result = svalBuilder.conjureSymbolVal(nullptr, Ex, LCtx,
  1036. resultType,
  1037. currBldrCtx->blockCount());
  1038. ProgramStateRef State = N->getState()->BindExpr(Ex, LCtx, result);
  1039. // Escape pointers passed into the list, unless it's an ObjC boxed
  1040. // expression which is not a boxable C structure.
  1041. if (!(isa<ObjCBoxedExpr>(Ex) &&
  1042. !cast<ObjCBoxedExpr>(Ex)->getSubExpr()
  1043. ->getType()->isRecordType()))
  1044. for (auto Child : Ex->children()) {
  1045. assert(Child);
  1046. SVal Val = State->getSVal(Child, LCtx);
  1047. CollectReachableSymbolsCallback Scanner =
  1048. State->scanReachableSymbols<CollectReachableSymbolsCallback>(
  1049. Val);
  1050. const InvalidatedSymbols &EscapedSymbols = Scanner.getSymbols();
  1051. State = getCheckerManager().runCheckersForPointerEscape(
  1052. State, EscapedSymbols,
  1053. /*CallEvent*/ nullptr, PSK_EscapeOther, nullptr);
  1054. }
  1055. Bldr2.generateNode(S, N, State);
  1056. }
  1057. getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this);
  1058. Bldr.addNodes(Dst);
  1059. break;
  1060. }
  1061. case Stmt::ArraySubscriptExprClass:
  1062. Bldr.takeNodes(Pred);
  1063. VisitArraySubscriptExpr(cast<ArraySubscriptExpr>(S), Pred, Dst);
  1064. Bldr.addNodes(Dst);
  1065. break;
  1066. case Stmt::GCCAsmStmtClass:
  1067. Bldr.takeNodes(Pred);
  1068. VisitGCCAsmStmt(cast<GCCAsmStmt>(S), Pred, Dst);
  1069. Bldr.addNodes(Dst);
  1070. break;
  1071. case Stmt::MSAsmStmtClass:
  1072. Bldr.takeNodes(Pred);
  1073. VisitMSAsmStmt(cast<MSAsmStmt>(S), Pred, Dst);
  1074. Bldr.addNodes(Dst);
  1075. break;
  1076. case Stmt::BlockExprClass:
  1077. Bldr.takeNodes(Pred);
  1078. VisitBlockExpr(cast<BlockExpr>(S), Pred, Dst);
  1079. Bldr.addNodes(Dst);
  1080. break;
  1081. case Stmt::LambdaExprClass:
  1082. if (AMgr.options.shouldInlineLambdas()) {
  1083. Bldr.takeNodes(Pred);
  1084. VisitLambdaExpr(cast<LambdaExpr>(S), Pred, Dst);
  1085. Bldr.addNodes(Dst);
  1086. } else {
  1087. const ExplodedNode *node = Bldr.generateSink(S, Pred, Pred->getState());
  1088. Engine.addAbortedBlock(node, currBldrCtx->getBlock());
  1089. }
  1090. break;
  1091. case Stmt::BinaryOperatorClass: {
  1092. const BinaryOperator* B = cast<BinaryOperator>(S);
  1093. if (B->isLogicalOp()) {
  1094. Bldr.takeNodes(Pred);
  1095. VisitLogicalExpr(B, Pred, Dst);
  1096. Bldr.addNodes(Dst);
  1097. break;
  1098. }
  1099. else if (B->getOpcode() == BO_Comma) {
  1100. ProgramStateRef state = Pred->getState();
  1101. Bldr.generateNode(B, Pred,
  1102. state->BindExpr(B, Pred->getLocationContext(),
  1103. state->getSVal(B->getRHS(),
  1104. Pred->getLocationContext())));
  1105. break;
  1106. }
  1107. Bldr.takeNodes(Pred);
  1108. if (AMgr.options.eagerlyAssumeBinOpBifurcation &&
  1109. (B->isRelationalOp() || B->isEqualityOp())) {
  1110. ExplodedNodeSet Tmp;
  1111. VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Tmp);
  1112. evalEagerlyAssumeBinOpBifurcation(Dst, Tmp, cast<Expr>(S));
  1113. }
  1114. else
  1115. VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst);
  1116. Bldr.addNodes(Dst);
  1117. break;
  1118. }
  1119. case Stmt::CXXOperatorCallExprClass: {
  1120. const CXXOperatorCallExpr *OCE = cast<CXXOperatorCallExpr>(S);
  1121. // For instance method operators, make sure the 'this' argument has a
  1122. // valid region.
  1123. const Decl *Callee = OCE->getCalleeDecl();
  1124. if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Callee)) {
  1125. if (MD->isInstance()) {
  1126. ProgramStateRef State = Pred->getState();
  1127. const LocationContext *LCtx = Pred->getLocationContext();
  1128. ProgramStateRef NewState =
  1129. createTemporaryRegionIfNeeded(State, LCtx, OCE->getArg(0));
  1130. if (NewState != State) {
  1131. Pred = Bldr.generateNode(OCE, Pred, NewState, /*Tag=*/nullptr,
  1132. ProgramPoint::PreStmtKind);
  1133. // Did we cache out?
  1134. if (!Pred)
  1135. break;
  1136. }
  1137. }
  1138. }
  1139. // FALLTHROUGH
  1140. LLVM_FALLTHROUGH;
  1141. }
  1142. case Stmt::CallExprClass:
  1143. case Stmt::CXXMemberCallExprClass:
  1144. case Stmt::UserDefinedLiteralClass: {
  1145. Bldr.takeNodes(Pred);
  1146. VisitCallExpr(cast<CallExpr>(S), Pred, Dst);
  1147. Bldr.addNodes(Dst);
  1148. break;
  1149. }
  1150. case Stmt::CXXCatchStmtClass: {
  1151. Bldr.takeNodes(Pred);
  1152. VisitCXXCatchStmt(cast<CXXCatchStmt>(S), Pred, Dst);
  1153. Bldr.addNodes(Dst);
  1154. break;
  1155. }
  1156. case Stmt::CXXTemporaryObjectExprClass:
  1157. case Stmt::CXXConstructExprClass: {
  1158. Bldr.takeNodes(Pred);
  1159. VisitCXXConstructExpr(cast<CXXConstructExpr>(S), Pred, Dst);
  1160. Bldr.addNodes(Dst);
  1161. break;
  1162. }
  1163. case Stmt::CXXNewExprClass: {
  1164. Bldr.takeNodes(Pred);
  1165. ExplodedNodeSet PostVisit;
  1166. VisitCXXNewExpr(cast<CXXNewExpr>(S), Pred, PostVisit);
  1167. getCheckerManager().runCheckersForPostStmt(Dst, PostVisit, S, *this);
  1168. Bldr.addNodes(Dst);
  1169. break;
  1170. }
  1171. case Stmt::CXXDeleteExprClass: {
  1172. Bldr.takeNodes(Pred);
  1173. ExplodedNodeSet PreVisit;
  1174. const CXXDeleteExpr *CDE = cast<CXXDeleteExpr>(S);
  1175. getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
  1176. for (ExplodedNodeSet::iterator i = PreVisit.begin(),
  1177. e = PreVisit.end(); i != e ; ++i)
  1178. VisitCXXDeleteExpr(CDE, *i, Dst);
  1179. Bldr.addNodes(Dst);
  1180. break;
  1181. }
  1182. // FIXME: ChooseExpr is really a constant. We need to fix
  1183. // the CFG do not model them as explicit control-flow.
  1184. case Stmt::ChooseExprClass: { // __builtin_choose_expr
  1185. Bldr.takeNodes(Pred);
  1186. const ChooseExpr *C = cast<ChooseExpr>(S);
  1187. VisitGuardedExpr(C, C->getLHS(), C->getRHS(), Pred, Dst);
  1188. Bldr.addNodes(Dst);
  1189. break;
  1190. }
  1191. case Stmt::CompoundAssignOperatorClass:
  1192. Bldr.takeNodes(Pred);
  1193. VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst);
  1194. Bldr.addNodes(Dst);
  1195. break;
  1196. case Stmt::CompoundLiteralExprClass:
  1197. Bldr.takeNodes(Pred);
  1198. VisitCompoundLiteralExpr(cast<CompoundLiteralExpr>(S), Pred, Dst);
  1199. Bldr.addNodes(Dst);
  1200. break;
  1201. case Stmt::BinaryConditionalOperatorClass:
  1202. case Stmt::ConditionalOperatorClass: { // '?' operator
  1203. Bldr.takeNodes(Pred);
  1204. const AbstractConditionalOperator *C
  1205. = cast<AbstractConditionalOperator>(S);
  1206. VisitGuardedExpr(C, C->getTrueExpr(), C->getFalseExpr(), Pred, Dst);
  1207. Bldr.addNodes(Dst);
  1208. break;
  1209. }
  1210. case Stmt::CXXThisExprClass:
  1211. Bldr.takeNodes(Pred);
  1212. VisitCXXThisExpr(cast<CXXThisExpr>(S), Pred, Dst);
  1213. Bldr.addNodes(Dst);
  1214. break;
  1215. case Stmt::DeclRefExprClass: {
  1216. Bldr.takeNodes(Pred);
  1217. const DeclRefExpr *DE = cast<DeclRefExpr>(S);
  1218. VisitCommonDeclRefExpr(DE, DE->getDecl(), Pred, Dst);
  1219. Bldr.addNodes(Dst);
  1220. break;
  1221. }
  1222. case Stmt::DeclStmtClass:
  1223. Bldr.takeNodes(Pred);
  1224. VisitDeclStmt(cast<DeclStmt>(S), Pred, Dst);
  1225. Bldr.addNodes(Dst);
  1226. break;
  1227. case Stmt::ImplicitCastExprClass:
  1228. case Stmt::CStyleCastExprClass:
  1229. case Stmt::CXXStaticCastExprClass:
  1230. case Stmt::CXXDynamicCastExprClass:
  1231. case Stmt::CXXReinterpretCastExprClass:
  1232. case Stmt::CXXConstCastExprClass:
  1233. case Stmt::CXXFunctionalCastExprClass:
  1234. case Stmt::ObjCBridgedCastExprClass: {
  1235. Bldr.takeNodes(Pred);
  1236. const CastExpr *C = cast<CastExpr>(S);
  1237. ExplodedNodeSet dstExpr;
  1238. VisitCast(C, C->getSubExpr(), Pred, dstExpr);
  1239. // Handle the postvisit checks.
  1240. getCheckerManager().runCheckersForPostStmt(Dst, dstExpr, C, *this);
  1241. Bldr.addNodes(Dst);
  1242. break;
  1243. }
  1244. case Expr::MaterializeTemporaryExprClass: {
  1245. Bldr.takeNodes(Pred);
  1246. const MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(S);
  1247. ExplodedNodeSet dstPrevisit;
  1248. getCheckerManager().runCheckersForPreStmt(dstPrevisit, Pred, MTE, *this);
  1249. ExplodedNodeSet dstExpr;
  1250. for (ExplodedNodeSet::iterator i = dstPrevisit.begin(),
  1251. e = dstPrevisit.end(); i != e ; ++i) {
  1252. CreateCXXTemporaryObject(MTE, *i, dstExpr);
  1253. }
  1254. getCheckerManager().runCheckersForPostStmt(Dst, dstExpr, MTE, *this);
  1255. Bldr.addNodes(Dst);
  1256. break;
  1257. }
  1258. case Stmt::InitListExprClass:
  1259. Bldr.takeNodes(Pred);
  1260. VisitInitListExpr(cast<InitListExpr>(S), Pred, Dst);
  1261. Bldr.addNodes(Dst);
  1262. break;
  1263. case Stmt::MemberExprClass:
  1264. Bldr.takeNodes(Pred);
  1265. VisitMemberExpr(cast<MemberExpr>(S), Pred, Dst);
  1266. Bldr.addNodes(Dst);
  1267. break;
  1268. case Stmt::AtomicExprClass:
  1269. Bldr.takeNodes(Pred);
  1270. VisitAtomicExpr(cast<AtomicExpr>(S), Pred, Dst);
  1271. Bldr.addNodes(Dst);
  1272. break;
  1273. case Stmt::ObjCIvarRefExprClass:
  1274. Bldr.takeNodes(Pred);
  1275. VisitLvalObjCIvarRefExpr(cast<ObjCIvarRefExpr>(S), Pred, Dst);
  1276. Bldr.addNodes(Dst);
  1277. break;
  1278. case Stmt::ObjCForCollectionStmtClass:
  1279. Bldr.takeNodes(Pred);
  1280. VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S), Pred, Dst);
  1281. Bldr.addNodes(Dst);
  1282. break;
  1283. case Stmt::ObjCMessageExprClass:
  1284. Bldr.takeNodes(Pred);
  1285. VisitObjCMessage(cast<ObjCMessageExpr>(S), Pred, Dst);
  1286. Bldr.addNodes(Dst);
  1287. break;
  1288. case Stmt::ObjCAtThrowStmtClass:
  1289. case Stmt::CXXThrowExprClass:
  1290. // FIXME: This is not complete. We basically treat @throw as
  1291. // an abort.
  1292. Bldr.generateSink(S, Pred, Pred->getState());
  1293. break;
  1294. case Stmt::ReturnStmtClass:
  1295. Bldr.takeNodes(Pred);
  1296. VisitReturnStmt(cast<ReturnStmt>(S), Pred, Dst);
  1297. Bldr.addNodes(Dst);
  1298. break;
  1299. case Stmt::OffsetOfExprClass:
  1300. Bldr.takeNodes(Pred);
  1301. VisitOffsetOfExpr(cast<OffsetOfExpr>(S), Pred, Dst);
  1302. Bldr.addNodes(Dst);
  1303. break;
  1304. case Stmt::UnaryExprOrTypeTraitExprClass:
  1305. Bldr.takeNodes(Pred);
  1306. VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S),
  1307. Pred, Dst);
  1308. Bldr.addNodes(Dst);
  1309. break;
  1310. case Stmt::StmtExprClass: {
  1311. const StmtExpr *SE = cast<StmtExpr>(S);
  1312. if (SE->getSubStmt()->body_empty()) {
  1313. // Empty statement expression.
  1314. assert(SE->getType() == getContext().VoidTy
  1315. && "Empty statement expression must have void type.");
  1316. break;
  1317. }
  1318. if (Expr *LastExpr = dyn_cast<Expr>(*SE->getSubStmt()->body_rbegin())) {
  1319. ProgramStateRef state = Pred->getState();
  1320. Bldr.generateNode(SE, Pred,
  1321. state->BindExpr(SE, Pred->getLocationContext(),
  1322. state->getSVal(LastExpr,
  1323. Pred->getLocationContext())));
  1324. }
  1325. break;
  1326. }
  1327. case Stmt::UnaryOperatorClass: {
  1328. Bldr.takeNodes(Pred);
  1329. const UnaryOperator *U = cast<UnaryOperator>(S);
  1330. if (AMgr.options.eagerlyAssumeBinOpBifurcation && (U->getOpcode() == UO_LNot)) {
  1331. ExplodedNodeSet Tmp;
  1332. VisitUnaryOperator(U, Pred, Tmp);
  1333. evalEagerlyAssumeBinOpBifurcation(Dst, Tmp, U);
  1334. }
  1335. else
  1336. VisitUnaryOperator(U, Pred, Dst);
  1337. Bldr.addNodes(Dst);
  1338. break;
  1339. }
  1340. case Stmt::PseudoObjectExprClass: {
  1341. Bldr.takeNodes(Pred);
  1342. ProgramStateRef state = Pred->getState();
  1343. const PseudoObjectExpr *PE = cast<PseudoObjectExpr>(S);
  1344. if (const Expr *Result = PE->getResultExpr()) {
  1345. SVal V = state->getSVal(Result, Pred->getLocationContext());
  1346. Bldr.generateNode(S, Pred,
  1347. state->BindExpr(S, Pred->getLocationContext(), V));
  1348. }
  1349. else
  1350. Bldr.generateNode(S, Pred,
  1351. state->BindExpr(S, Pred->getLocationContext(),
  1352. UnknownVal()));
  1353. Bldr.addNodes(Dst);
  1354. break;
  1355. }
  1356. }
  1357. }
  1358. bool ExprEngine::replayWithoutInlining(ExplodedNode *N,
  1359. const LocationContext *CalleeLC) {
  1360. const StackFrameContext *CalleeSF = CalleeLC->getCurrentStackFrame();
  1361. const StackFrameContext *CallerSF = CalleeSF->getParent()->getCurrentStackFrame();
  1362. assert(CalleeSF && CallerSF);
  1363. ExplodedNode *BeforeProcessingCall = nullptr;
  1364. const Stmt *CE = CalleeSF->getCallSite();
  1365. // Find the first node before we started processing the call expression.
  1366. while (N) {
  1367. ProgramPoint L = N->getLocation();
  1368. BeforeProcessingCall = N;
  1369. N = N->pred_empty() ? nullptr : *(N->pred_begin());
  1370. // Skip the nodes corresponding to the inlined code.
  1371. if (L.getLocationContext()->getCurrentStackFrame() != CallerSF)
  1372. continue;
  1373. // We reached the caller. Find the node right before we started
  1374. // processing the call.
  1375. if (L.isPurgeKind())
  1376. continue;
  1377. if (L.getAs<PreImplicitCall>())
  1378. continue;
  1379. if (L.getAs<CallEnter>())
  1380. continue;
  1381. if (Optional<StmtPoint> SP = L.getAs<StmtPoint>())
  1382. if (SP->getStmt() == CE)
  1383. continue;
  1384. break;
  1385. }
  1386. if (!BeforeProcessingCall)
  1387. return false;
  1388. // TODO: Clean up the unneeded nodes.
  1389. // Build an Epsilon node from which we will restart the analyzes.
  1390. // Note that CE is permitted to be NULL!
  1391. ProgramPoint NewNodeLoc =
  1392. EpsilonPoint(BeforeProcessingCall->getLocationContext(), CE);
  1393. // Add the special flag to GDM to signal retrying with no inlining.
  1394. // Note, changing the state ensures that we are not going to cache out.
  1395. ProgramStateRef NewNodeState = BeforeProcessingCall->getState();
  1396. NewNodeState =
  1397. NewNodeState->set<ReplayWithoutInlining>(const_cast<Stmt *>(CE));
  1398. // Make the new node a successor of BeforeProcessingCall.
  1399. bool IsNew = false;
  1400. ExplodedNode *NewNode = G.getNode(NewNodeLoc, NewNodeState, false, &IsNew);
  1401. // We cached out at this point. Caching out is common due to us backtracking
  1402. // from the inlined function, which might spawn several paths.
  1403. if (!IsNew)
  1404. return true;
  1405. NewNode->addPredecessor(BeforeProcessingCall, G);
  1406. // Add the new node to the work list.
  1407. Engine.enqueueStmtNode(NewNode, CalleeSF->getCallSiteBlock(),
  1408. CalleeSF->getIndex());
  1409. NumTimesRetriedWithoutInlining++;
  1410. return true;
  1411. }
  1412. /// Block entrance. (Update counters).
  1413. void ExprEngine::processCFGBlockEntrance(const BlockEdge &L,
  1414. NodeBuilderWithSinks &nodeBuilder,
  1415. ExplodedNode *Pred) {
  1416. PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
  1417. // If we reach a loop which has a known bound (and meets
  1418. // other constraints) then consider completely unrolling it.
  1419. if(AMgr.options.shouldUnrollLoops()) {
  1420. unsigned maxBlockVisitOnPath = AMgr.options.maxBlockVisitOnPath;
  1421. const Stmt *Term = nodeBuilder.getContext().getBlock()->getTerminator();
  1422. if (Term) {
  1423. ProgramStateRef NewState = updateLoopStack(Term, AMgr.getASTContext(),
  1424. Pred, maxBlockVisitOnPath);
  1425. if (NewState != Pred->getState()) {
  1426. ExplodedNode *UpdatedNode = nodeBuilder.generateNode(NewState, Pred);
  1427. if (!UpdatedNode)
  1428. return;
  1429. Pred = UpdatedNode;
  1430. }
  1431. }
  1432. // Is we are inside an unrolled loop then no need the check the counters.
  1433. if(isUnrolledState(Pred->getState()))
  1434. return;
  1435. }
  1436. // If this block is terminated by a loop and it has already been visited the
  1437. // maximum number of times, widen the loop.
  1438. unsigned int BlockCount = nodeBuilder.getContext().blockCount();
  1439. if (BlockCount == AMgr.options.maxBlockVisitOnPath - 1 &&
  1440. AMgr.options.shouldWidenLoops()) {
  1441. const Stmt *Term = nodeBuilder.getContext().getBlock()->getTerminator();
  1442. if (!(Term &&
  1443. (isa<ForStmt>(Term) || isa<WhileStmt>(Term) || isa<DoStmt>(Term))))
  1444. return;
  1445. // Widen.
  1446. const LocationContext *LCtx = Pred->getLocationContext();
  1447. ProgramStateRef WidenedState =
  1448. getWidenedLoopState(Pred->getState(), LCtx, BlockCount, Term);
  1449. nodeBuilder.generateNode(WidenedState, Pred);
  1450. return;
  1451. }
  1452. // FIXME: Refactor this into a checker.
  1453. if (BlockCount >= AMgr.options.maxBlockVisitOnPath) {
  1454. static SimpleProgramPointTag tag(TagProviderName, "Block count exceeded");
  1455. const ExplodedNode *Sink =
  1456. nodeBuilder.generateSink(Pred->getState(), Pred, &tag);
  1457. // Check if we stopped at the top level function or not.
  1458. // Root node should have the location context of the top most function.
  1459. const LocationContext *CalleeLC = Pred->getLocation().getLocationContext();
  1460. const LocationContext *CalleeSF = CalleeLC->getCurrentStackFrame();
  1461. const LocationContext *RootLC =
  1462. (*G.roots_begin())->getLocation().getLocationContext();
  1463. if (RootLC->getCurrentStackFrame() != CalleeSF) {
  1464. Engine.FunctionSummaries->markReachedMaxBlockCount(CalleeSF->getDecl());
  1465. // Re-run the call evaluation without inlining it, by storing the
  1466. // no-inlining policy in the state and enqueuing the new work item on
  1467. // the list. Replay should almost never fail. Use the stats to catch it
  1468. // if it does.
  1469. if ((!AMgr.options.NoRetryExhausted &&
  1470. replayWithoutInlining(Pred, CalleeLC)))
  1471. return;
  1472. NumMaxBlockCountReachedInInlined++;
  1473. } else
  1474. NumMaxBlockCountReached++;
  1475. // Make sink nodes as exhausted(for stats) only if retry failed.
  1476. Engine.blocksExhausted.push_back(std::make_pair(L, Sink));
  1477. }
  1478. }
  1479. //===----------------------------------------------------------------------===//
  1480. // Branch processing.
  1481. //===----------------------------------------------------------------------===//
  1482. /// RecoverCastedSymbol - A helper function for ProcessBranch that is used
  1483. /// to try to recover some path-sensitivity for casts of symbolic
  1484. /// integers that promote their values (which are currently not tracked well).
  1485. /// This function returns the SVal bound to Condition->IgnoreCasts if all the
  1486. // cast(s) did was sign-extend the original value.
  1487. static SVal RecoverCastedSymbol(ProgramStateManager& StateMgr,
  1488. ProgramStateRef state,
  1489. const Stmt *Condition,
  1490. const LocationContext *LCtx,
  1491. ASTContext &Ctx) {
  1492. const Expr *Ex = dyn_cast<Expr>(Condition);
  1493. if (!Ex)
  1494. return UnknownVal();
  1495. uint64_t bits = 0;
  1496. bool bitsInit = false;
  1497. while (const CastExpr *CE = dyn_cast<CastExpr>(Ex)) {
  1498. QualType T = CE->getType();
  1499. if (!T->isIntegralOrEnumerationType())
  1500. return UnknownVal();
  1501. uint64_t newBits = Ctx.getTypeSize(T);
  1502. if (!bitsInit || newBits < bits) {
  1503. bitsInit = true;
  1504. bits = newBits;
  1505. }
  1506. Ex = CE->getSubExpr();
  1507. }
  1508. // We reached a non-cast. Is it a symbolic value?
  1509. QualType T = Ex->getType();
  1510. if (!bitsInit || !T->isIntegralOrEnumerationType() ||
  1511. Ctx.getTypeSize(T) > bits)
  1512. return UnknownVal();
  1513. return state->getSVal(Ex, LCtx);
  1514. }
  1515. #ifndef NDEBUG
  1516. static const Stmt *getRightmostLeaf(const Stmt *Condition) {
  1517. while (Condition) {
  1518. const BinaryOperator *BO = dyn_cast<BinaryOperator>(Condition);
  1519. if (!BO || !BO->isLogicalOp()) {
  1520. return Condition;
  1521. }
  1522. Condition = BO->getRHS()->IgnoreParens();
  1523. }
  1524. return nullptr;
  1525. }
  1526. #endif
  1527. // Returns the condition the branch at the end of 'B' depends on and whose value
  1528. // has been evaluated within 'B'.
  1529. // In most cases, the terminator condition of 'B' will be evaluated fully in
  1530. // the last statement of 'B'; in those cases, the resolved condition is the
  1531. // given 'Condition'.
  1532. // If the condition of the branch is a logical binary operator tree, the CFG is
  1533. // optimized: in that case, we know that the expression formed by all but the
  1534. // rightmost leaf of the logical binary operator tree must be true, and thus
  1535. // the branch condition is at this point equivalent to the truth value of that
  1536. // rightmost leaf; the CFG block thus only evaluates this rightmost leaf
  1537. // expression in its final statement. As the full condition in that case was
  1538. // not evaluated, and is thus not in the SVal cache, we need to use that leaf
  1539. // expression to evaluate the truth value of the condition in the current state
  1540. // space.
  1541. static const Stmt *ResolveCondition(const Stmt *Condition,
  1542. const CFGBlock *B) {
  1543. if (const Expr *Ex = dyn_cast<Expr>(Condition))
  1544. Condition = Ex->IgnoreParens();
  1545. const BinaryOperator *BO = dyn_cast<BinaryOperator>(Condition);
  1546. if (!BO || !BO->isLogicalOp())
  1547. return Condition;
  1548. assert(!B->getTerminator().isTemporaryDtorsBranch() &&
  1549. "Temporary destructor branches handled by processBindTemporary.");
  1550. // For logical operations, we still have the case where some branches
  1551. // use the traditional "merge" approach and others sink the branch
  1552. // directly into the basic blocks representing the logical operation.
  1553. // We need to distinguish between those two cases here.
  1554. // The invariants are still shifting, but it is possible that the
  1555. // last element in a CFGBlock is not a CFGStmt. Look for the last
  1556. // CFGStmt as the value of the condition.
  1557. CFGBlock::const_reverse_iterator I = B->rbegin(), E = B->rend();
  1558. for (; I != E; ++I) {
  1559. CFGElement Elem = *I;
  1560. Optional<CFGStmt> CS = Elem.getAs<CFGStmt>();
  1561. if (!CS)
  1562. continue;
  1563. const Stmt *LastStmt = CS->getStmt();
  1564. assert(LastStmt == Condition || LastStmt == getRightmostLeaf(Condition));
  1565. return LastStmt;
  1566. }
  1567. llvm_unreachable("could not resolve condition");
  1568. }
  1569. void ExprEngine::processBranch(const Stmt *Condition, const Stmt *Term,
  1570. NodeBuilderContext& BldCtx,
  1571. ExplodedNode *Pred,
  1572. ExplodedNodeSet &Dst,
  1573. const CFGBlock *DstT,
  1574. const CFGBlock *DstF) {
  1575. assert((!Condition || !isa<CXXBindTemporaryExpr>(Condition)) &&
  1576. "CXXBindTemporaryExprs are handled by processBindTemporary.");
  1577. const LocationContext *LCtx = Pred->getLocationContext();
  1578. PrettyStackTraceLocationContext StackCrashInfo(LCtx);
  1579. currBldrCtx = &BldCtx;
  1580. // Check for NULL conditions; e.g. "for(;;)"
  1581. if (!Condition) {
  1582. BranchNodeBuilder NullCondBldr(Pred, Dst, BldCtx, DstT, DstF);
  1583. NullCondBldr.markInfeasible(false);
  1584. NullCondBldr.generateNode(Pred->getState(), true, Pred);
  1585. return;
  1586. }
  1587. if (const Expr *Ex = dyn_cast<Expr>(Condition))
  1588. Condition = Ex->IgnoreParens();
  1589. Condition = ResolveCondition(Condition, BldCtx.getBlock());
  1590. PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
  1591. Condition->getLocStart(),
  1592. "Error evaluating branch");
  1593. ExplodedNodeSet CheckersOutSet;
  1594. getCheckerManager().runCheckersForBranchCondition(Condition, CheckersOutSet,
  1595. Pred, *this);
  1596. // We generated only sinks.
  1597. if (CheckersOutSet.empty())
  1598. return;
  1599. BranchNodeBuilder builder(CheckersOutSet, Dst, BldCtx, DstT, DstF);
  1600. for (NodeBuilder::iterator I = CheckersOutSet.begin(),
  1601. E = CheckersOutSet.end(); E != I; ++I) {
  1602. ExplodedNode *PredI = *I;
  1603. if (PredI->isSink())
  1604. continue;
  1605. ProgramStateRef PrevState = PredI->getState();
  1606. SVal X = PrevState->getSVal(Condition, PredI->getLocationContext());
  1607. if (X.isUnknownOrUndef()) {
  1608. // Give it a chance to recover from unknown.
  1609. if (const Expr *Ex = dyn_cast<Expr>(Condition)) {
  1610. if (Ex->getType()->isIntegralOrEnumerationType()) {
  1611. // Try to recover some path-sensitivity. Right now casts of symbolic
  1612. // integers that promote their values are currently not tracked well.
  1613. // If 'Condition' is such an expression, try and recover the
  1614. // underlying value and use that instead.
  1615. SVal recovered = RecoverCastedSymbol(getStateManager(),
  1616. PrevState, Condition,
  1617. PredI->getLocationContext(),
  1618. getContext());
  1619. if (!recovered.isUnknown()) {
  1620. X = recovered;
  1621. }
  1622. }
  1623. }
  1624. }
  1625. // If the condition is still unknown, give up.
  1626. if (X.isUnknownOrUndef()) {
  1627. builder.generateNode(PrevState, true, PredI);
  1628. builder.generateNode(PrevState, false, PredI);
  1629. continue;
  1630. }
  1631. DefinedSVal V = X.castAs<DefinedSVal>();
  1632. ProgramStateRef StTrue, StFalse;
  1633. std::tie(StTrue, StFalse) = PrevState->assume(V);
  1634. // Process the true branch.
  1635. if (builder.isFeasible(true)) {
  1636. if (StTrue)
  1637. builder.generateNode(StTrue, true, PredI);
  1638. else
  1639. builder.markInfeasible(true);
  1640. }
  1641. // Process the false branch.
  1642. if (builder.isFeasible(false)) {
  1643. if (StFalse)
  1644. builder.generateNode(StFalse, false, PredI);
  1645. else
  1646. builder.markInfeasible(false);
  1647. }
  1648. }
  1649. currBldrCtx = nullptr;
  1650. }
  1651. /// The GDM component containing the set of global variables which have been
  1652. /// previously initialized with explicit initializers.
  1653. REGISTER_TRAIT_WITH_PROGRAMSTATE(InitializedGlobalsSet,
  1654. llvm::ImmutableSet<const VarDecl *>)
  1655. void ExprEngine::processStaticInitializer(const DeclStmt *DS,
  1656. NodeBuilderContext &BuilderCtx,
  1657. ExplodedNode *Pred,
  1658. clang::ento::ExplodedNodeSet &Dst,
  1659. const CFGBlock *DstT,
  1660. const CFGBlock *DstF) {
  1661. PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
  1662. currBldrCtx = &BuilderCtx;
  1663. const VarDecl *VD = cast<VarDecl>(DS->getSingleDecl());
  1664. ProgramStateRef state = Pred->getState();
  1665. bool initHasRun = state->contains<InitializedGlobalsSet>(VD);
  1666. BranchNodeBuilder builder(Pred, Dst, BuilderCtx, DstT, DstF);
  1667. if (!initHasRun) {
  1668. state = state->add<InitializedGlobalsSet>(VD);
  1669. }
  1670. builder.generateNode(state, initHasRun, Pred);
  1671. builder.markInfeasible(!initHasRun);
  1672. currBldrCtx = nullptr;
  1673. }
  1674. /// processIndirectGoto - Called by CoreEngine. Used to generate successor
  1675. /// nodes by processing the 'effects' of a computed goto jump.
  1676. void ExprEngine::processIndirectGoto(IndirectGotoNodeBuilder &builder) {
  1677. ProgramStateRef state = builder.getState();
  1678. SVal V = state->getSVal(builder.getTarget(), builder.getLocationContext());
  1679. // Three possibilities:
  1680. //
  1681. // (1) We know the computed label.
  1682. // (2) The label is NULL (or some other constant), or Undefined.
  1683. // (3) We have no clue about the label. Dispatch to all targets.
  1684. //
  1685. typedef IndirectGotoNodeBuilder::iterator iterator;
  1686. if (Optional<loc::GotoLabel> LV = V.getAs<loc::GotoLabel>()) {
  1687. const LabelDecl *L = LV->getLabel();
  1688. for (iterator I = builder.begin(), E = builder.end(); I != E; ++I) {
  1689. if (I.getLabel() == L) {
  1690. builder.generateNode(I, state);
  1691. return;
  1692. }
  1693. }
  1694. llvm_unreachable("No block with label.");
  1695. }
  1696. if (V.getAs<loc::ConcreteInt>() || V.getAs<UndefinedVal>()) {
  1697. // Dispatch to the first target and mark it as a sink.
  1698. //ExplodedNode* N = builder.generateNode(builder.begin(), state, true);
  1699. // FIXME: add checker visit.
  1700. // UndefBranches.insert(N);
  1701. return;
  1702. }
  1703. // This is really a catch-all. We don't support symbolics yet.
  1704. // FIXME: Implement dispatch for symbolic pointers.
  1705. for (iterator I=builder.begin(), E=builder.end(); I != E; ++I)
  1706. builder.generateNode(I, state);
  1707. }
  1708. #if 0
  1709. static bool stackFrameDoesNotContainInitializedTemporaries(ExplodedNode &Pred) {
  1710. const StackFrameContext* Frame = Pred.getStackFrame();
  1711. const llvm::ImmutableSet<CXXBindTemporaryContext> &Set =
  1712. Pred.getState()->get<InitializedTemporariesSet>();
  1713. return std::find_if(Set.begin(), Set.end(),
  1714. [&](const CXXBindTemporaryContext &Ctx) {
  1715. if (Ctx.second == Frame) {
  1716. Ctx.first->dump();
  1717. llvm::errs() << "\n";
  1718. }
  1719. return Ctx.second == Frame;
  1720. }) == Set.end();
  1721. }
  1722. #endif
  1723. void ExprEngine::processBeginOfFunction(NodeBuilderContext &BC,
  1724. ExplodedNode *Pred,
  1725. ExplodedNodeSet &Dst,
  1726. const BlockEdge &L) {
  1727. SaveAndRestore<const NodeBuilderContext *> NodeContextRAII(currBldrCtx, &BC);
  1728. getCheckerManager().runCheckersForBeginFunction(Dst, L, Pred, *this);
  1729. }
  1730. /// ProcessEndPath - Called by CoreEngine. Used to generate end-of-path
  1731. /// nodes when the control reaches the end of a function.
  1732. void ExprEngine::processEndOfFunction(NodeBuilderContext& BC,
  1733. ExplodedNode *Pred,
  1734. const ReturnStmt *RS) {
  1735. // FIXME: Assert that stackFrameDoesNotContainInitializedTemporaries(*Pred)).
  1736. // We currently cannot enable this assert, as lifetime extended temporaries
  1737. // are not modelled correctly.
  1738. PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
  1739. StateMgr.EndPath(Pred->getState());
  1740. ExplodedNodeSet Dst;
  1741. if (Pred->getLocationContext()->inTopFrame()) {
  1742. // Remove dead symbols.
  1743. ExplodedNodeSet AfterRemovedDead;
  1744. removeDeadOnEndOfFunction(BC, Pred, AfterRemovedDead);
  1745. // Notify checkers.
  1746. for (ExplodedNodeSet::iterator I = AfterRemovedDead.begin(),
  1747. E = AfterRemovedDead.end(); I != E; ++I) {
  1748. getCheckerManager().runCheckersForEndFunction(BC, Dst, *I, *this);
  1749. }
  1750. } else {
  1751. getCheckerManager().runCheckersForEndFunction(BC, Dst, Pred, *this);
  1752. }
  1753. Engine.enqueueEndOfFunction(Dst, RS);
  1754. }
  1755. /// ProcessSwitch - Called by CoreEngine. Used to generate successor
  1756. /// nodes by processing the 'effects' of a switch statement.
  1757. void ExprEngine::processSwitch(SwitchNodeBuilder& builder) {
  1758. typedef SwitchNodeBuilder::iterator iterator;
  1759. ProgramStateRef state = builder.getState();
  1760. const Expr *CondE = builder.getCondition();
  1761. SVal CondV_untested = state->getSVal(CondE, builder.getLocationContext());
  1762. if (CondV_untested.isUndef()) {
  1763. //ExplodedNode* N = builder.generateDefaultCaseNode(state, true);
  1764. // FIXME: add checker
  1765. //UndefBranches.insert(N);
  1766. return;
  1767. }
  1768. DefinedOrUnknownSVal CondV = CondV_untested.castAs<DefinedOrUnknownSVal>();
  1769. ProgramStateRef DefaultSt = state;
  1770. iterator I = builder.begin(), EI = builder.end();
  1771. bool defaultIsFeasible = I == EI;
  1772. for ( ; I != EI; ++I) {
  1773. // Successor may be pruned out during CFG construction.
  1774. if (!I.getBlock())
  1775. continue;
  1776. const CaseStmt *Case = I.getCase();
  1777. // Evaluate the LHS of the case value.
  1778. llvm::APSInt V1 = Case->getLHS()->EvaluateKnownConstInt(getContext());
  1779. assert(V1.getBitWidth() == getContext().getIntWidth(CondE->getType()));
  1780. // Get the RHS of the case, if it exists.
  1781. llvm::APSInt V2;
  1782. if (const Expr *E = Case->getRHS())
  1783. V2 = E->EvaluateKnownConstInt(getContext());
  1784. else
  1785. V2 = V1;
  1786. ProgramStateRef StateCase;
  1787. if (Optional<NonLoc> NL = CondV.getAs<NonLoc>())
  1788. std::tie(StateCase, DefaultSt) =
  1789. DefaultSt->assumeInclusiveRange(*NL, V1, V2);
  1790. else // UnknownVal
  1791. StateCase = DefaultSt;
  1792. if (StateCase)
  1793. builder.generateCaseStmtNode(I, StateCase);
  1794. // Now "assume" that the case doesn't match. Add this state
  1795. // to the default state (if it is feasible).
  1796. if (DefaultSt)
  1797. defaultIsFeasible = true;
  1798. else {
  1799. defaultIsFeasible = false;
  1800. break;
  1801. }
  1802. }
  1803. if (!defaultIsFeasible)
  1804. return;
  1805. // If we have switch(enum value), the default branch is not
  1806. // feasible if all of the enum constants not covered by 'case:' statements
  1807. // are not feasible values for the switch condition.
  1808. //
  1809. // Note that this isn't as accurate as it could be. Even if there isn't
  1810. // a case for a particular enum value as long as that enum value isn't
  1811. // feasible then it shouldn't be considered for making 'default:' reachable.
  1812. const SwitchStmt *SS = builder.getSwitch();
  1813. const Expr *CondExpr = SS->getCond()->IgnoreParenImpCasts();
  1814. if (CondExpr->getType()->getAs<EnumType>()) {
  1815. if (SS->isAllEnumCasesCovered())
  1816. return;
  1817. }
  1818. builder.generateDefaultCaseNode(DefaultSt);
  1819. }
  1820. //===----------------------------------------------------------------------===//
  1821. // Transfer functions: Loads and stores.
  1822. //===----------------------------------------------------------------------===//
  1823. void ExprEngine::VisitCommonDeclRefExpr(const Expr *Ex, const NamedDecl *D,
  1824. ExplodedNode *Pred,
  1825. ExplodedNodeSet &Dst) {
  1826. StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
  1827. ProgramStateRef state = Pred->getState();
  1828. const LocationContext *LCtx = Pred->getLocationContext();
  1829. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1830. // C permits "extern void v", and if you cast the address to a valid type,
  1831. // you can even do things with it. We simply pretend
  1832. assert(Ex->isGLValue() || VD->getType()->isVoidType());
  1833. const LocationContext *LocCtxt = Pred->getLocationContext();
  1834. const Decl *D = LocCtxt->getDecl();
  1835. const auto *MD = D ? dyn_cast<CXXMethodDecl>(D) : nullptr;
  1836. const auto *DeclRefEx = dyn_cast<DeclRefExpr>(Ex);
  1837. SVal V;
  1838. bool IsReference;
  1839. if (AMgr.options.shouldInlineLambdas() && DeclRefEx &&
  1840. DeclRefEx->refersToEnclosingVariableOrCapture() && MD &&
  1841. MD->getParent()->isLambda()) {
  1842. // Lookup the field of the lambda.
  1843. const CXXRecordDecl *CXXRec = MD->getParent();
  1844. llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
  1845. FieldDecl *LambdaThisCaptureField;
  1846. CXXRec->getCaptureFields(LambdaCaptureFields, LambdaThisCaptureField);
  1847. const FieldDecl *FD = LambdaCaptureFields[VD];
  1848. if (!FD) {
  1849. // When a constant is captured, sometimes no corresponding field is
  1850. // created in the lambda object.
  1851. assert(VD->getType().isConstQualified());
  1852. V = state->getLValue(VD, LocCtxt);
  1853. IsReference = false;
  1854. } else {
  1855. Loc CXXThis =
  1856. svalBuilder.getCXXThis(MD, LocCtxt->getCurrentStackFrame());
  1857. SVal CXXThisVal = state->getSVal(CXXThis);
  1858. V = state->getLValue(FD, CXXThisVal);
  1859. IsReference = FD->getType()->isReferenceType();
  1860. }
  1861. } else {
  1862. V = state->getLValue(VD, LocCtxt);
  1863. IsReference = VD->getType()->isReferenceType();
  1864. }
  1865. // For references, the 'lvalue' is the pointer address stored in the
  1866. // reference region.
  1867. if (IsReference) {
  1868. if (const MemRegion *R = V.getAsRegion())
  1869. V = state->getSVal(R);
  1870. else
  1871. V = UnknownVal();
  1872. }
  1873. Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
  1874. ProgramPoint::PostLValueKind);
  1875. return;
  1876. }
  1877. if (const EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
  1878. assert(!Ex->isGLValue());
  1879. SVal V = svalBuilder.makeIntVal(ED->getInitVal());
  1880. Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V));
  1881. return;
  1882. }
  1883. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  1884. SVal V = svalBuilder.getFunctionPointer(FD);
  1885. Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
  1886. ProgramPoint::PostLValueKind);
  1887. return;
  1888. }
  1889. if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) {
  1890. // FIXME: Compute lvalue of field pointers-to-member.
  1891. // Right now we just use a non-null void pointer, so that it gives proper
  1892. // results in boolean contexts.
  1893. // FIXME: Maybe delegate this to the surrounding operator&.
  1894. // Note how this expression is lvalue, however pointer-to-member is NonLoc.
  1895. SVal V = svalBuilder.conjureSymbolVal(Ex, LCtx, getContext().VoidPtrTy,
  1896. currBldrCtx->blockCount());
  1897. state = state->assume(V.castAs<DefinedOrUnknownSVal>(), true);
  1898. Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
  1899. ProgramPoint::PostLValueKind);
  1900. return;
  1901. }
  1902. llvm_unreachable("Support for this Decl not implemented.");
  1903. }
  1904. /// VisitArraySubscriptExpr - Transfer function for array accesses
  1905. void ExprEngine::VisitArraySubscriptExpr(const ArraySubscriptExpr *A,
  1906. ExplodedNode *Pred,
  1907. ExplodedNodeSet &Dst){
  1908. const Expr *Base = A->getBase()->IgnoreParens();
  1909. const Expr *Idx = A->getIdx()->IgnoreParens();
  1910. ExplodedNodeSet CheckerPreStmt;
  1911. getCheckerManager().runCheckersForPreStmt(CheckerPreStmt, Pred, A, *this);
  1912. ExplodedNodeSet EvalSet;
  1913. StmtNodeBuilder Bldr(CheckerPreStmt, EvalSet, *currBldrCtx);
  1914. bool IsVectorType = A->getBase()->getType()->isVectorType();
  1915. // The "like" case is for situations where C standard prohibits the type to
  1916. // be an lvalue, e.g. taking the address of a subscript of an expression of
  1917. // type "void *".
  1918. bool IsGLValueLike = A->isGLValue() ||
  1919. (A->getType().isCForbiddenLValueType() && !AMgr.getLangOpts().CPlusPlus);
  1920. for (auto *Node : CheckerPreStmt) {
  1921. const LocationContext *LCtx = Node->getLocationContext();
  1922. ProgramStateRef state = Node->getState();
  1923. if (IsGLValueLike) {
  1924. QualType T = A->getType();
  1925. // One of the forbidden LValue types! We still need to have sensible
  1926. // symbolic locations to represent this stuff. Note that arithmetic on
  1927. // void pointers is a GCC extension.
  1928. if (T->isVoidType())
  1929. T = getContext().CharTy;
  1930. SVal V = state->getLValue(T,
  1931. state->getSVal(Idx, LCtx),
  1932. state->getSVal(Base, LCtx));
  1933. Bldr.generateNode(A, Node, state->BindExpr(A, LCtx, V), nullptr,
  1934. ProgramPoint::PostLValueKind);
  1935. } else if (IsVectorType) {
  1936. // FIXME: non-glvalue vector reads are not modelled.
  1937. Bldr.generateNode(A, Node, state, nullptr);
  1938. } else {
  1939. llvm_unreachable("Array subscript should be an lValue when not \
  1940. a vector and not a forbidden lvalue type");
  1941. }
  1942. }
  1943. getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, A, *this);
  1944. }
  1945. /// VisitMemberExpr - Transfer function for member expressions.
  1946. void ExprEngine::VisitMemberExpr(const MemberExpr *M, ExplodedNode *Pred,
  1947. ExplodedNodeSet &Dst) {
  1948. // FIXME: Prechecks eventually go in ::Visit().
  1949. ExplodedNodeSet CheckedSet;
  1950. getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, M, *this);
  1951. ExplodedNodeSet EvalSet;
  1952. ValueDecl *Member = M->getMemberDecl();
  1953. // Handle static member variables and enum constants accessed via
  1954. // member syntax.
  1955. if (isa<VarDecl>(Member) || isa<EnumConstantDecl>(Member)) {
  1956. ExplodedNodeSet Dst;
  1957. for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
  1958. I != E; ++I) {
  1959. VisitCommonDeclRefExpr(M, Member, Pred, EvalSet);
  1960. }
  1961. } else {
  1962. StmtNodeBuilder Bldr(CheckedSet, EvalSet, *currBldrCtx);
  1963. ExplodedNodeSet Tmp;
  1964. for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
  1965. I != E; ++I) {
  1966. ProgramStateRef state = (*I)->getState();
  1967. const LocationContext *LCtx = (*I)->getLocationContext();
  1968. Expr *BaseExpr = M->getBase();
  1969. // Handle C++ method calls.
  1970. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member)) {
  1971. if (MD->isInstance())
  1972. state = createTemporaryRegionIfNeeded(state, LCtx, BaseExpr);
  1973. SVal MDVal = svalBuilder.getFunctionPointer(MD);
  1974. state = state->BindExpr(M, LCtx, MDVal);
  1975. Bldr.generateNode(M, *I, state);
  1976. continue;
  1977. }
  1978. // Handle regular struct fields / member variables.
  1979. state = createTemporaryRegionIfNeeded(state, LCtx, BaseExpr);
  1980. SVal baseExprVal = state->getSVal(BaseExpr, LCtx);
  1981. FieldDecl *field = cast<FieldDecl>(Member);
  1982. SVal L = state->getLValue(field, baseExprVal);
  1983. if (M->isGLValue() || M->getType()->isArrayType()) {
  1984. // We special-case rvalues of array type because the analyzer cannot
  1985. // reason about them, since we expect all regions to be wrapped in Locs.
  1986. // We instead treat these as lvalues and assume that they will decay to
  1987. // pointers as soon as they are used.
  1988. if (!M->isGLValue()) {
  1989. assert(M->getType()->isArrayType());
  1990. const ImplicitCastExpr *PE =
  1991. dyn_cast<ImplicitCastExpr>((*I)->getParentMap().getParentIgnoreParens(M));
  1992. if (!PE || PE->getCastKind() != CK_ArrayToPointerDecay) {
  1993. llvm_unreachable("should always be wrapped in ArrayToPointerDecay");
  1994. }
  1995. }
  1996. if (field->getType()->isReferenceType()) {
  1997. if (const MemRegion *R = L.getAsRegion())
  1998. L = state->getSVal(R);
  1999. else
  2000. L = UnknownVal();
  2001. }
  2002. Bldr.generateNode(M, *I, state->BindExpr(M, LCtx, L), nullptr,
  2003. ProgramPoint::PostLValueKind);
  2004. } else {
  2005. Bldr.takeNodes(*I);
  2006. evalLoad(Tmp, M, M, *I, state, L);
  2007. Bldr.addNodes(Tmp);
  2008. }
  2009. }
  2010. }
  2011. getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, M, *this);
  2012. }
  2013. void ExprEngine::VisitAtomicExpr(const AtomicExpr *AE, ExplodedNode *Pred,
  2014. ExplodedNodeSet &Dst) {
  2015. ExplodedNodeSet AfterPreSet;
  2016. getCheckerManager().runCheckersForPreStmt(AfterPreSet, Pred, AE, *this);
  2017. // For now, treat all the arguments to C11 atomics as escaping.
  2018. // FIXME: Ideally we should model the behavior of the atomics precisely here.
  2019. ExplodedNodeSet AfterInvalidateSet;
  2020. StmtNodeBuilder Bldr(AfterPreSet, AfterInvalidateSet, *currBldrCtx);
  2021. for (ExplodedNodeSet::iterator I = AfterPreSet.begin(), E = AfterPreSet.end();
  2022. I != E; ++I) {
  2023. ProgramStateRef State = (*I)->getState();
  2024. const LocationContext *LCtx = (*I)->getLocationContext();
  2025. SmallVector<SVal, 8> ValuesToInvalidate;
  2026. for (unsigned SI = 0, Count = AE->getNumSubExprs(); SI != Count; SI++) {
  2027. const Expr *SubExpr = AE->getSubExprs()[SI];
  2028. SVal SubExprVal = State->getSVal(SubExpr, LCtx);
  2029. ValuesToInvalidate.push_back(SubExprVal);
  2030. }
  2031. State = State->invalidateRegions(ValuesToInvalidate, AE,
  2032. currBldrCtx->blockCount(),
  2033. LCtx,
  2034. /*CausedByPointerEscape*/true,
  2035. /*Symbols=*/nullptr);
  2036. SVal ResultVal = UnknownVal();
  2037. State = State->BindExpr(AE, LCtx, ResultVal);
  2038. Bldr.generateNode(AE, *I, State, nullptr,
  2039. ProgramPoint::PostStmtKind);
  2040. }
  2041. getCheckerManager().runCheckersForPostStmt(Dst, AfterInvalidateSet, AE, *this);
  2042. }
  2043. // A value escapes in three possible cases:
  2044. // (1) We are binding to something that is not a memory region.
  2045. // (2) We are binding to a MemrRegion that does not have stack storage.
  2046. // (3) We are binding to a MemRegion with stack storage that the store
  2047. // does not understand.
  2048. ProgramStateRef ExprEngine::processPointerEscapedOnBind(ProgramStateRef State,
  2049. SVal Loc,
  2050. SVal Val,
  2051. const LocationContext *LCtx) {
  2052. // Are we storing to something that causes the value to "escape"?
  2053. bool escapes = true;
  2054. // TODO: Move to StoreManager.
  2055. if (Optional<loc::MemRegionVal> regionLoc = Loc.getAs<loc::MemRegionVal>()) {
  2056. escapes = !regionLoc->getRegion()->hasStackStorage();
  2057. if (!escapes) {
  2058. // To test (3), generate a new state with the binding added. If it is
  2059. // the same state, then it escapes (since the store cannot represent
  2060. // the binding).
  2061. // Do this only if we know that the store is not supposed to generate the
  2062. // same state.
  2063. SVal StoredVal = State->getSVal(regionLoc->getRegion());
  2064. if (StoredVal != Val)
  2065. escapes = (State == (State->bindLoc(*regionLoc, Val, LCtx)));
  2066. }
  2067. }
  2068. // If our store can represent the binding and we aren't storing to something
  2069. // that doesn't have local storage then just return and have the simulation
  2070. // state continue as is.
  2071. if (!escapes)
  2072. return State;
  2073. // Otherwise, find all symbols referenced by 'val' that we are tracking
  2074. // and stop tracking them.
  2075. CollectReachableSymbolsCallback Scanner =
  2076. State->scanReachableSymbols<CollectReachableSymbolsCallback>(Val);
  2077. const InvalidatedSymbols &EscapedSymbols = Scanner.getSymbols();
  2078. State = getCheckerManager().runCheckersForPointerEscape(State,
  2079. EscapedSymbols,
  2080. /*CallEvent*/ nullptr,
  2081. PSK_EscapeOnBind,
  2082. nullptr);
  2083. return State;
  2084. }
  2085. ProgramStateRef
  2086. ExprEngine::notifyCheckersOfPointerEscape(ProgramStateRef State,
  2087. const InvalidatedSymbols *Invalidated,
  2088. ArrayRef<const MemRegion *> ExplicitRegions,
  2089. ArrayRef<const MemRegion *> Regions,
  2090. const CallEvent *Call,
  2091. RegionAndSymbolInvalidationTraits &ITraits) {
  2092. if (!Invalidated || Invalidated->empty())
  2093. return State;
  2094. if (!Call)
  2095. return getCheckerManager().runCheckersForPointerEscape(State,
  2096. *Invalidated,
  2097. nullptr,
  2098. PSK_EscapeOther,
  2099. &ITraits);
  2100. // If the symbols were invalidated by a call, we want to find out which ones
  2101. // were invalidated directly due to being arguments to the call.
  2102. InvalidatedSymbols SymbolsDirectlyInvalidated;
  2103. for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
  2104. E = ExplicitRegions.end(); I != E; ++I) {
  2105. if (const SymbolicRegion *R = (*I)->StripCasts()->getAs<SymbolicRegion>())
  2106. SymbolsDirectlyInvalidated.insert(R->getSymbol());
  2107. }
  2108. InvalidatedSymbols SymbolsIndirectlyInvalidated;
  2109. for (InvalidatedSymbols::const_iterator I=Invalidated->begin(),
  2110. E = Invalidated->end(); I!=E; ++I) {
  2111. SymbolRef sym = *I;
  2112. if (SymbolsDirectlyInvalidated.count(sym))
  2113. continue;
  2114. SymbolsIndirectlyInvalidated.insert(sym);
  2115. }
  2116. if (!SymbolsDirectlyInvalidated.empty())
  2117. State = getCheckerManager().runCheckersForPointerEscape(State,
  2118. SymbolsDirectlyInvalidated, Call, PSK_DirectEscapeOnCall, &ITraits);
  2119. // Notify about the symbols that get indirectly invalidated by the call.
  2120. if (!SymbolsIndirectlyInvalidated.empty())
  2121. State = getCheckerManager().runCheckersForPointerEscape(State,
  2122. SymbolsIndirectlyInvalidated, Call, PSK_IndirectEscapeOnCall, &ITraits);
  2123. return State;
  2124. }
  2125. /// evalBind - Handle the semantics of binding a value to a specific location.
  2126. /// This method is used by evalStore and (soon) VisitDeclStmt, and others.
  2127. void ExprEngine::evalBind(ExplodedNodeSet &Dst, const Stmt *StoreE,
  2128. ExplodedNode *Pred,
  2129. SVal location, SVal Val,
  2130. bool atDeclInit, const ProgramPoint *PP) {
  2131. const LocationContext *LC = Pred->getLocationContext();
  2132. PostStmt PS(StoreE, LC);
  2133. if (!PP)
  2134. PP = &PS;
  2135. // Do a previsit of the bind.
  2136. ExplodedNodeSet CheckedSet;
  2137. getCheckerManager().runCheckersForBind(CheckedSet, Pred, location, Val,
  2138. StoreE, *this, *PP);
  2139. StmtNodeBuilder Bldr(CheckedSet, Dst, *currBldrCtx);
  2140. // If the location is not a 'Loc', it will already be handled by
  2141. // the checkers. There is nothing left to do.
  2142. if (!location.getAs<Loc>()) {
  2143. const ProgramPoint L = PostStore(StoreE, LC, /*Loc*/nullptr,
  2144. /*tag*/nullptr);
  2145. ProgramStateRef state = Pred->getState();
  2146. state = processPointerEscapedOnBind(state, location, Val, LC);
  2147. Bldr.generateNode(L, state, Pred);
  2148. return;
  2149. }
  2150. for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
  2151. I!=E; ++I) {
  2152. ExplodedNode *PredI = *I;
  2153. ProgramStateRef state = PredI->getState();
  2154. state = processPointerEscapedOnBind(state, location, Val, LC);
  2155. // When binding the value, pass on the hint that this is a initialization.
  2156. // For initializations, we do not need to inform clients of region
  2157. // changes.
  2158. state = state->bindLoc(location.castAs<Loc>(),
  2159. Val, LC, /* notifyChanges = */ !atDeclInit);
  2160. const MemRegion *LocReg = nullptr;
  2161. if (Optional<loc::MemRegionVal> LocRegVal =
  2162. location.getAs<loc::MemRegionVal>()) {
  2163. LocReg = LocRegVal->getRegion();
  2164. }
  2165. const ProgramPoint L = PostStore(StoreE, LC, LocReg, nullptr);
  2166. Bldr.generateNode(L, state, PredI);
  2167. }
  2168. }
  2169. /// evalStore - Handle the semantics of a store via an assignment.
  2170. /// @param Dst The node set to store generated state nodes
  2171. /// @param AssignE The assignment expression if the store happens in an
  2172. /// assignment.
  2173. /// @param LocationE The location expression that is stored to.
  2174. /// @param state The current simulation state
  2175. /// @param location The location to store the value
  2176. /// @param Val The value to be stored
  2177. void ExprEngine::evalStore(ExplodedNodeSet &Dst, const Expr *AssignE,
  2178. const Expr *LocationE,
  2179. ExplodedNode *Pred,
  2180. ProgramStateRef state, SVal location, SVal Val,
  2181. const ProgramPointTag *tag) {
  2182. // Proceed with the store. We use AssignE as the anchor for the PostStore
  2183. // ProgramPoint if it is non-NULL, and LocationE otherwise.
  2184. const Expr *StoreE = AssignE ? AssignE : LocationE;
  2185. // Evaluate the location (checks for bad dereferences).
  2186. ExplodedNodeSet Tmp;
  2187. evalLocation(Tmp, AssignE, LocationE, Pred, state, location, tag, false);
  2188. if (Tmp.empty())
  2189. return;
  2190. if (location.isUndef())
  2191. return;
  2192. for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI)
  2193. evalBind(Dst, StoreE, *NI, location, Val, false);
  2194. }
  2195. void ExprEngine::evalLoad(ExplodedNodeSet &Dst,
  2196. const Expr *NodeEx,
  2197. const Expr *BoundEx,
  2198. ExplodedNode *Pred,
  2199. ProgramStateRef state,
  2200. SVal location,
  2201. const ProgramPointTag *tag,
  2202. QualType LoadTy)
  2203. {
  2204. assert(!location.getAs<NonLoc>() && "location cannot be a NonLoc.");
  2205. // Are we loading from a region? This actually results in two loads; one
  2206. // to fetch the address of the referenced value and one to fetch the
  2207. // referenced value.
  2208. if (const TypedValueRegion *TR =
  2209. dyn_cast_or_null<TypedValueRegion>(location.getAsRegion())) {
  2210. QualType ValTy = TR->getValueType();
  2211. if (const ReferenceType *RT = ValTy->getAs<ReferenceType>()) {
  2212. static SimpleProgramPointTag
  2213. loadReferenceTag(TagProviderName, "Load Reference");
  2214. ExplodedNodeSet Tmp;
  2215. evalLoadCommon(Tmp, NodeEx, BoundEx, Pred, state,
  2216. location, &loadReferenceTag,
  2217. getContext().getPointerType(RT->getPointeeType()));
  2218. // Perform the load from the referenced value.
  2219. for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end() ; I!=E; ++I) {
  2220. state = (*I)->getState();
  2221. location = state->getSVal(BoundEx, (*I)->getLocationContext());
  2222. evalLoadCommon(Dst, NodeEx, BoundEx, *I, state, location, tag, LoadTy);
  2223. }
  2224. return;
  2225. }
  2226. }
  2227. evalLoadCommon(Dst, NodeEx, BoundEx, Pred, state, location, tag, LoadTy);
  2228. }
  2229. void ExprEngine::evalLoadCommon(ExplodedNodeSet &Dst,
  2230. const Expr *NodeEx,
  2231. const Expr *BoundEx,
  2232. ExplodedNode *Pred,
  2233. ProgramStateRef state,
  2234. SVal location,
  2235. const ProgramPointTag *tag,
  2236. QualType LoadTy) {
  2237. assert(NodeEx);
  2238. assert(BoundEx);
  2239. // Evaluate the location (checks for bad dereferences).
  2240. ExplodedNodeSet Tmp;
  2241. evalLocation(Tmp, NodeEx, BoundEx, Pred, state, location, tag, true);
  2242. if (Tmp.empty())
  2243. return;
  2244. StmtNodeBuilder Bldr(Tmp, Dst, *currBldrCtx);
  2245. if (location.isUndef())
  2246. return;
  2247. // Proceed with the load.
  2248. for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI) {
  2249. state = (*NI)->getState();
  2250. const LocationContext *LCtx = (*NI)->getLocationContext();
  2251. SVal V = UnknownVal();
  2252. if (location.isValid()) {
  2253. if (LoadTy.isNull())
  2254. LoadTy = BoundEx->getType();
  2255. V = state->getSVal(location.castAs<Loc>(), LoadTy);
  2256. }
  2257. Bldr.generateNode(NodeEx, *NI, state->BindExpr(BoundEx, LCtx, V), tag,
  2258. ProgramPoint::PostLoadKind);
  2259. }
  2260. }
  2261. void ExprEngine::evalLocation(ExplodedNodeSet &Dst,
  2262. const Stmt *NodeEx,
  2263. const Stmt *BoundEx,
  2264. ExplodedNode *Pred,
  2265. ProgramStateRef state,
  2266. SVal location,
  2267. const ProgramPointTag *tag,
  2268. bool isLoad) {
  2269. StmtNodeBuilder BldrTop(Pred, Dst, *currBldrCtx);
  2270. // Early checks for performance reason.
  2271. if (location.isUnknown()) {
  2272. return;
  2273. }
  2274. ExplodedNodeSet Src;
  2275. BldrTop.takeNodes(Pred);
  2276. StmtNodeBuilder Bldr(Pred, Src, *currBldrCtx);
  2277. if (Pred->getState() != state) {
  2278. // Associate this new state with an ExplodedNode.
  2279. // FIXME: If I pass null tag, the graph is incorrect, e.g for
  2280. // int *p;
  2281. // p = 0;
  2282. // *p = 0xDEADBEEF;
  2283. // "p = 0" is not noted as "Null pointer value stored to 'p'" but
  2284. // instead "int *p" is noted as
  2285. // "Variable 'p' initialized to a null pointer value"
  2286. static SimpleProgramPointTag tag(TagProviderName, "Location");
  2287. Bldr.generateNode(NodeEx, Pred, state, &tag);
  2288. }
  2289. ExplodedNodeSet Tmp;
  2290. getCheckerManager().runCheckersForLocation(Tmp, Src, location, isLoad,
  2291. NodeEx, BoundEx, *this);
  2292. BldrTop.addNodes(Tmp);
  2293. }
  2294. std::pair<const ProgramPointTag *, const ProgramPointTag*>
  2295. ExprEngine::geteagerlyAssumeBinOpBifurcationTags() {
  2296. static SimpleProgramPointTag
  2297. eagerlyAssumeBinOpBifurcationTrue(TagProviderName,
  2298. "Eagerly Assume True"),
  2299. eagerlyAssumeBinOpBifurcationFalse(TagProviderName,
  2300. "Eagerly Assume False");
  2301. return std::make_pair(&eagerlyAssumeBinOpBifurcationTrue,
  2302. &eagerlyAssumeBinOpBifurcationFalse);
  2303. }
  2304. void ExprEngine::evalEagerlyAssumeBinOpBifurcation(ExplodedNodeSet &Dst,
  2305. ExplodedNodeSet &Src,
  2306. const Expr *Ex) {
  2307. StmtNodeBuilder Bldr(Src, Dst, *currBldrCtx);
  2308. for (ExplodedNodeSet::iterator I=Src.begin(), E=Src.end(); I!=E; ++I) {
  2309. ExplodedNode *Pred = *I;
  2310. // Test if the previous node was as the same expression. This can happen
  2311. // when the expression fails to evaluate to anything meaningful and
  2312. // (as an optimization) we don't generate a node.
  2313. ProgramPoint P = Pred->getLocation();
  2314. if (!P.getAs<PostStmt>() || P.castAs<PostStmt>().getStmt() != Ex) {
  2315. continue;
  2316. }
  2317. ProgramStateRef state = Pred->getState();
  2318. SVal V = state->getSVal(Ex, Pred->getLocationContext());
  2319. Optional<nonloc::SymbolVal> SEV = V.getAs<nonloc::SymbolVal>();
  2320. if (SEV && SEV->isExpression()) {
  2321. const std::pair<const ProgramPointTag *, const ProgramPointTag*> &tags =
  2322. geteagerlyAssumeBinOpBifurcationTags();
  2323. ProgramStateRef StateTrue, StateFalse;
  2324. std::tie(StateTrue, StateFalse) = state->assume(*SEV);
  2325. // First assume that the condition is true.
  2326. if (StateTrue) {
  2327. SVal Val = svalBuilder.makeIntVal(1U, Ex->getType());
  2328. StateTrue = StateTrue->BindExpr(Ex, Pred->getLocationContext(), Val);
  2329. Bldr.generateNode(Ex, Pred, StateTrue, tags.first);
  2330. }
  2331. // Next, assume that the condition is false.
  2332. if (StateFalse) {
  2333. SVal Val = svalBuilder.makeIntVal(0U, Ex->getType());
  2334. StateFalse = StateFalse->BindExpr(Ex, Pred->getLocationContext(), Val);
  2335. Bldr.generateNode(Ex, Pred, StateFalse, tags.second);
  2336. }
  2337. }
  2338. }
  2339. }
  2340. void ExprEngine::VisitGCCAsmStmt(const GCCAsmStmt *A, ExplodedNode *Pred,
  2341. ExplodedNodeSet &Dst) {
  2342. StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
  2343. // We have processed both the inputs and the outputs. All of the outputs
  2344. // should evaluate to Locs. Nuke all of their values.
  2345. // FIXME: Some day in the future it would be nice to allow a "plug-in"
  2346. // which interprets the inline asm and stores proper results in the
  2347. // outputs.
  2348. ProgramStateRef state = Pred->getState();
  2349. for (const Expr *O : A->outputs()) {
  2350. SVal X = state->getSVal(O, Pred->getLocationContext());
  2351. assert (!X.getAs<NonLoc>()); // Should be an Lval, or unknown, undef.
  2352. if (Optional<Loc> LV = X.getAs<Loc>())
  2353. state = state->bindLoc(*LV, UnknownVal(), Pred->getLocationContext());
  2354. }
  2355. Bldr.generateNode(A, Pred, state);
  2356. }
  2357. void ExprEngine::VisitMSAsmStmt(const MSAsmStmt *A, ExplodedNode *Pred,
  2358. ExplodedNodeSet &Dst) {
  2359. StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
  2360. Bldr.generateNode(A, Pred, Pred->getState());
  2361. }
  2362. //===----------------------------------------------------------------------===//
  2363. // Visualization.
  2364. //===----------------------------------------------------------------------===//
  2365. #ifndef NDEBUG
  2366. static ExprEngine* GraphPrintCheckerState;
  2367. static SourceManager* GraphPrintSourceManager;
  2368. namespace llvm {
  2369. template<>
  2370. struct DOTGraphTraits<ExplodedNode*> :
  2371. public DefaultDOTGraphTraits {
  2372. DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
  2373. // FIXME: Since we do not cache error nodes in ExprEngine now, this does not
  2374. // work.
  2375. static std::string getNodeAttributes(const ExplodedNode *N, void*) {
  2376. return "";
  2377. }
  2378. // De-duplicate some source location pretty-printing.
  2379. static void printLocation(raw_ostream &Out, SourceLocation SLoc) {
  2380. if (SLoc.isFileID()) {
  2381. Out << "\\lline="
  2382. << GraphPrintSourceManager->getExpansionLineNumber(SLoc)
  2383. << " col="
  2384. << GraphPrintSourceManager->getExpansionColumnNumber(SLoc)
  2385. << "\\l";
  2386. }
  2387. }
  2388. static void printLocation2(raw_ostream &Out, SourceLocation SLoc) {
  2389. if (SLoc.isFileID() && GraphPrintSourceManager->isInMainFile(SLoc))
  2390. Out << "line " << GraphPrintSourceManager->getExpansionLineNumber(SLoc);
  2391. else
  2392. SLoc.print(Out, *GraphPrintSourceManager);
  2393. }
  2394. static std::string getNodeLabel(const ExplodedNode *N, void*){
  2395. std::string sbuf;
  2396. llvm::raw_string_ostream Out(sbuf);
  2397. // Program Location.
  2398. ProgramPoint Loc = N->getLocation();
  2399. switch (Loc.getKind()) {
  2400. case ProgramPoint::BlockEntranceKind: {
  2401. Out << "Block Entrance: B"
  2402. << Loc.castAs<BlockEntrance>().getBlock()->getBlockID();
  2403. break;
  2404. }
  2405. case ProgramPoint::BlockExitKind:
  2406. assert (false);
  2407. break;
  2408. case ProgramPoint::CallEnterKind:
  2409. Out << "CallEnter";
  2410. break;
  2411. case ProgramPoint::CallExitBeginKind:
  2412. Out << "CallExitBegin";
  2413. break;
  2414. case ProgramPoint::CallExitEndKind:
  2415. Out << "CallExitEnd";
  2416. break;
  2417. case ProgramPoint::PostStmtPurgeDeadSymbolsKind:
  2418. Out << "PostStmtPurgeDeadSymbols";
  2419. break;
  2420. case ProgramPoint::PreStmtPurgeDeadSymbolsKind:
  2421. Out << "PreStmtPurgeDeadSymbols";
  2422. break;
  2423. case ProgramPoint::EpsilonKind:
  2424. Out << "Epsilon Point";
  2425. break;
  2426. case ProgramPoint::LoopExitKind: {
  2427. LoopExit LE = Loc.castAs<LoopExit>();
  2428. Out << "LoopExit: " << LE.getLoopStmt()->getStmtClassName();
  2429. break;
  2430. }
  2431. case ProgramPoint::PreImplicitCallKind: {
  2432. ImplicitCallPoint PC = Loc.castAs<ImplicitCallPoint>();
  2433. Out << "PreCall: ";
  2434. // FIXME: Get proper printing options.
  2435. PC.getDecl()->print(Out, LangOptions());
  2436. printLocation(Out, PC.getLocation());
  2437. break;
  2438. }
  2439. case ProgramPoint::PostImplicitCallKind: {
  2440. ImplicitCallPoint PC = Loc.castAs<ImplicitCallPoint>();
  2441. Out << "PostCall: ";
  2442. // FIXME: Get proper printing options.
  2443. PC.getDecl()->print(Out, LangOptions());
  2444. printLocation(Out, PC.getLocation());
  2445. break;
  2446. }
  2447. case ProgramPoint::PostInitializerKind: {
  2448. Out << "PostInitializer: ";
  2449. const CXXCtorInitializer *Init =
  2450. Loc.castAs<PostInitializer>().getInitializer();
  2451. if (const FieldDecl *FD = Init->getAnyMember())
  2452. Out << *FD;
  2453. else {
  2454. QualType Ty = Init->getTypeSourceInfo()->getType();
  2455. Ty = Ty.getLocalUnqualifiedType();
  2456. LangOptions LO; // FIXME.
  2457. Ty.print(Out, LO);
  2458. }
  2459. break;
  2460. }
  2461. case ProgramPoint::BlockEdgeKind: {
  2462. const BlockEdge &E = Loc.castAs<BlockEdge>();
  2463. Out << "Edge: (B" << E.getSrc()->getBlockID() << ", B"
  2464. << E.getDst()->getBlockID() << ')';
  2465. if (const Stmt *T = E.getSrc()->getTerminator()) {
  2466. SourceLocation SLoc = T->getLocStart();
  2467. Out << "\\|Terminator: ";
  2468. LangOptions LO; // FIXME.
  2469. E.getSrc()->printTerminator(Out, LO);
  2470. if (SLoc.isFileID()) {
  2471. Out << "\\lline="
  2472. << GraphPrintSourceManager->getExpansionLineNumber(SLoc)
  2473. << " col="
  2474. << GraphPrintSourceManager->getExpansionColumnNumber(SLoc);
  2475. }
  2476. if (isa<SwitchStmt>(T)) {
  2477. const Stmt *Label = E.getDst()->getLabel();
  2478. if (Label) {
  2479. if (const CaseStmt *C = dyn_cast<CaseStmt>(Label)) {
  2480. Out << "\\lcase ";
  2481. LangOptions LO; // FIXME.
  2482. if (C->getLHS())
  2483. C->getLHS()->printPretty(Out, nullptr, PrintingPolicy(LO));
  2484. if (const Stmt *RHS = C->getRHS()) {
  2485. Out << " .. ";
  2486. RHS->printPretty(Out, nullptr, PrintingPolicy(LO));
  2487. }
  2488. Out << ":";
  2489. }
  2490. else {
  2491. assert (isa<DefaultStmt>(Label));
  2492. Out << "\\ldefault:";
  2493. }
  2494. }
  2495. else
  2496. Out << "\\l(implicit) default:";
  2497. }
  2498. else if (isa<IndirectGotoStmt>(T)) {
  2499. // FIXME
  2500. }
  2501. else {
  2502. Out << "\\lCondition: ";
  2503. if (*E.getSrc()->succ_begin() == E.getDst())
  2504. Out << "true";
  2505. else
  2506. Out << "false";
  2507. }
  2508. Out << "\\l";
  2509. }
  2510. break;
  2511. }
  2512. default: {
  2513. const Stmt *S = Loc.castAs<StmtPoint>().getStmt();
  2514. assert(S != nullptr && "Expecting non-null Stmt");
  2515. Out << S->getStmtClassName() << ' ' << (const void*) S << ' ';
  2516. LangOptions LO; // FIXME.
  2517. S->printPretty(Out, nullptr, PrintingPolicy(LO));
  2518. printLocation(Out, S->getLocStart());
  2519. if (Loc.getAs<PreStmt>())
  2520. Out << "\\lPreStmt\\l;";
  2521. else if (Loc.getAs<PostLoad>())
  2522. Out << "\\lPostLoad\\l;";
  2523. else if (Loc.getAs<PostStore>())
  2524. Out << "\\lPostStore\\l";
  2525. else if (Loc.getAs<PostLValue>())
  2526. Out << "\\lPostLValue\\l";
  2527. else if (Loc.getAs<PostAllocatorCall>())
  2528. Out << "\\lPostAllocatorCall\\l";
  2529. break;
  2530. }
  2531. }
  2532. ProgramStateRef state = N->getState();
  2533. Out << "\\|StateID: " << (const void*) state.get()
  2534. << " NodeID: " << (const void*) N << "\\|";
  2535. // Analysis stack backtrace.
  2536. Out << "Location context stack (from current to outer):\\l";
  2537. const LocationContext *LC = Loc.getLocationContext();
  2538. unsigned Idx = 0;
  2539. for (; LC; LC = LC->getParent(), ++Idx) {
  2540. Out << Idx << ". (" << (const void *)LC << ") ";
  2541. switch (LC->getKind()) {
  2542. case LocationContext::StackFrame:
  2543. if (const NamedDecl *D = dyn_cast<NamedDecl>(LC->getDecl()))
  2544. Out << "Calling " << D->getQualifiedNameAsString();
  2545. else
  2546. Out << "Calling anonymous code";
  2547. if (const Stmt *S = cast<StackFrameContext>(LC)->getCallSite()) {
  2548. Out << " at ";
  2549. printLocation2(Out, S->getLocStart());
  2550. }
  2551. break;
  2552. case LocationContext::Block:
  2553. Out << "Invoking block";
  2554. if (const Decl *D = cast<BlockInvocationContext>(LC)->getBlockDecl()) {
  2555. Out << " defined at ";
  2556. printLocation2(Out, D->getLocStart());
  2557. }
  2558. break;
  2559. case LocationContext::Scope:
  2560. Out << "Entering scope";
  2561. // FIXME: Add more info once ScopeContext is activated.
  2562. break;
  2563. }
  2564. Out << "\\l";
  2565. }
  2566. Out << "\\l";
  2567. state->printDOT(Out);
  2568. Out << "\\l";
  2569. if (const ProgramPointTag *tag = Loc.getTag()) {
  2570. Out << "\\|Tag: " << tag->getTagDescription();
  2571. Out << "\\l";
  2572. }
  2573. return Out.str();
  2574. }
  2575. };
  2576. } // end llvm namespace
  2577. #endif
  2578. void ExprEngine::ViewGraph(bool trim) {
  2579. #ifndef NDEBUG
  2580. if (trim) {
  2581. std::vector<const ExplodedNode*> Src;
  2582. // Flush any outstanding reports to make sure we cover all the nodes.
  2583. // This does not cause them to get displayed.
  2584. for (BugReporter::iterator I=BR.begin(), E=BR.end(); I!=E; ++I)
  2585. const_cast<BugType*>(*I)->FlushReports(BR);
  2586. // Iterate through the reports and get their nodes.
  2587. for (BugReporter::EQClasses_iterator
  2588. EI = BR.EQClasses_begin(), EE = BR.EQClasses_end(); EI != EE; ++EI) {
  2589. ExplodedNode *N = const_cast<ExplodedNode*>(EI->begin()->getErrorNode());
  2590. if (N) Src.push_back(N);
  2591. }
  2592. ViewGraph(Src);
  2593. }
  2594. else {
  2595. GraphPrintCheckerState = this;
  2596. GraphPrintSourceManager = &getContext().getSourceManager();
  2597. llvm::ViewGraph(*G.roots_begin(), "ExprEngine");
  2598. GraphPrintCheckerState = nullptr;
  2599. GraphPrintSourceManager = nullptr;
  2600. }
  2601. #endif
  2602. }
  2603. void ExprEngine::ViewGraph(ArrayRef<const ExplodedNode*> Nodes) {
  2604. #ifndef NDEBUG
  2605. GraphPrintCheckerState = this;
  2606. GraphPrintSourceManager = &getContext().getSourceManager();
  2607. std::unique_ptr<ExplodedGraph> TrimmedG(G.trim(Nodes));
  2608. if (!TrimmedG.get())
  2609. llvm::errs() << "warning: Trimmed ExplodedGraph is empty.\n";
  2610. else
  2611. llvm::ViewGraph(*TrimmedG->roots_begin(), "TrimmedExprEngine");
  2612. GraphPrintCheckerState = nullptr;
  2613. GraphPrintSourceManager = nullptr;
  2614. #endif
  2615. }