IteratorChecker.cpp 88 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390
  1. //===-- IteratorChecker.cpp ---------------------------------------*- C++ -*--//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // Defines a checker for using iterators outside their range (past end). Usage
  10. // means here dereferencing, incrementing etc.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. // In the code, iterator can be represented as a:
  15. // * type-I: typedef-ed pointer. Operations over such iterator, such as
  16. // comparisons or increments, are modeled straightforwardly by the
  17. // analyzer.
  18. // * type-II: structure with its method bodies available. Operations over such
  19. // iterator are inlined by the analyzer, and results of modeling
  20. // these operations are exposing implementation details of the
  21. // iterators, which is not necessarily helping.
  22. // * type-III: completely opaque structure. Operations over such iterator are
  23. // modeled conservatively, producing conjured symbols everywhere.
  24. //
  25. // To handle all these types in a common way we introduce a structure called
  26. // IteratorPosition which is an abstraction of the position the iterator
  27. // represents using symbolic expressions. The checker handles all the
  28. // operations on this structure.
  29. //
  30. // Additionally, depending on the circumstances, operators of types II and III
  31. // can be represented as:
  32. // * type-IIa, type-IIIa: conjured structure symbols - when returned by value
  33. // from conservatively evaluated methods such as
  34. // `.begin()`.
  35. // * type-IIb, type-IIIb: memory regions of iterator-typed objects, such as
  36. // variables or temporaries, when the iterator object is
  37. // currently treated as an lvalue.
  38. // * type-IIc, type-IIIc: compound values of iterator-typed objects, when the
  39. // iterator object is treated as an rvalue taken of a
  40. // particular lvalue, eg. a copy of "type-a" iterator
  41. // object, or an iterator that existed before the
  42. // analysis has started.
  43. //
  44. // To handle any of these three different representations stored in an SVal we
  45. // use setter and getters functions which separate the three cases. To store
  46. // them we use a pointer union of symbol and memory region.
  47. //
  48. // The checker works the following way: We record the begin and the
  49. // past-end iterator for all containers whenever their `.begin()` and `.end()`
  50. // are called. Since the Constraint Manager cannot handle such SVals we need
  51. // to take over its role. We post-check equality and non-equality comparisons
  52. // and record that the two sides are equal if we are in the 'equal' branch
  53. // (true-branch for `==` and false-branch for `!=`).
  54. //
  55. // In case of type-I or type-II iterators we get a concrete integer as a result
  56. // of the comparison (1 or 0) but in case of type-III we only get a Symbol. In
  57. // this latter case we record the symbol and reload it in evalAssume() and do
  58. // the propagation there. We also handle (maybe double) negated comparisons
  59. // which are represented in the form of (x == 0 or x != 0) where x is the
  60. // comparison itself.
  61. //
  62. // Since `SimpleConstraintManager` cannot handle complex symbolic expressions
  63. // we only use expressions of the format S, S+n or S-n for iterator positions
  64. // where S is a conjured symbol and n is an unsigned concrete integer. When
  65. // making an assumption e.g. `S1 + n == S2 + m` we store `S1 - S2 == m - n` as
  66. // a constraint which we later retrieve when doing an actual comparison.
  67. #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
  68. #include "clang/AST/DeclTemplate.h"
  69. #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
  70. #include "clang/StaticAnalyzer/Core/Checker.h"
  71. #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
  72. #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
  73. #include "clang/StaticAnalyzer/Core/PathSensitive/DynamicType.h"
  74. #include <utility>
  75. using namespace clang;
  76. using namespace ento;
  77. namespace {
  78. // Abstract position of an iterator. This helps to handle all three kinds
  79. // of operators in a common way by using a symbolic position.
  80. struct IteratorPosition {
  81. private:
  82. // Container the iterator belongs to
  83. const MemRegion *Cont;
  84. // Whether iterator is valid
  85. const bool Valid;
  86. // Abstract offset
  87. const SymbolRef Offset;
  88. IteratorPosition(const MemRegion *C, bool V, SymbolRef Of)
  89. : Cont(C), Valid(V), Offset(Of) {}
  90. public:
  91. const MemRegion *getContainer() const { return Cont; }
  92. bool isValid() const { return Valid; }
  93. SymbolRef getOffset() const { return Offset; }
  94. IteratorPosition invalidate() const {
  95. return IteratorPosition(Cont, false, Offset);
  96. }
  97. static IteratorPosition getPosition(const MemRegion *C, SymbolRef Of) {
  98. return IteratorPosition(C, true, Of);
  99. }
  100. IteratorPosition setTo(SymbolRef NewOf) const {
  101. return IteratorPosition(Cont, Valid, NewOf);
  102. }
  103. IteratorPosition reAssign(const MemRegion *NewCont) const {
  104. return IteratorPosition(NewCont, Valid, Offset);
  105. }
  106. bool operator==(const IteratorPosition &X) const {
  107. return Cont == X.Cont && Valid == X.Valid && Offset == X.Offset;
  108. }
  109. bool operator!=(const IteratorPosition &X) const {
  110. return Cont != X.Cont || Valid != X.Valid || Offset != X.Offset;
  111. }
  112. void Profile(llvm::FoldingSetNodeID &ID) const {
  113. ID.AddPointer(Cont);
  114. ID.AddInteger(Valid);
  115. ID.Add(Offset);
  116. }
  117. };
  118. // Structure to record the symbolic begin and end position of a container
  119. struct ContainerData {
  120. private:
  121. const SymbolRef Begin, End;
  122. ContainerData(SymbolRef B, SymbolRef E) : Begin(B), End(E) {}
  123. public:
  124. static ContainerData fromBegin(SymbolRef B) {
  125. return ContainerData(B, nullptr);
  126. }
  127. static ContainerData fromEnd(SymbolRef E) {
  128. return ContainerData(nullptr, E);
  129. }
  130. SymbolRef getBegin() const { return Begin; }
  131. SymbolRef getEnd() const { return End; }
  132. ContainerData newBegin(SymbolRef B) const { return ContainerData(B, End); }
  133. ContainerData newEnd(SymbolRef E) const { return ContainerData(Begin, E); }
  134. bool operator==(const ContainerData &X) const {
  135. return Begin == X.Begin && End == X.End;
  136. }
  137. bool operator!=(const ContainerData &X) const {
  138. return Begin != X.Begin || End != X.End;
  139. }
  140. void Profile(llvm::FoldingSetNodeID &ID) const {
  141. ID.Add(Begin);
  142. ID.Add(End);
  143. }
  144. };
  145. class IteratorChecker
  146. : public Checker<check::PreCall, check::PostCall,
  147. check::PostStmt<MaterializeTemporaryExpr>, check::Bind,
  148. check::LiveSymbols, check::DeadSymbols> {
  149. std::unique_ptr<BugType> OutOfRangeBugType;
  150. std::unique_ptr<BugType> MismatchedBugType;
  151. std::unique_ptr<BugType> InvalidatedBugType;
  152. void handleComparison(CheckerContext &C, const Expr *CE, const SVal &RetVal,
  153. const SVal &LVal, const SVal &RVal,
  154. OverloadedOperatorKind Op) const;
  155. void processComparison(CheckerContext &C, ProgramStateRef State,
  156. SymbolRef Sym1, SymbolRef Sym2, const SVal &RetVal,
  157. OverloadedOperatorKind Op) const;
  158. void verifyAccess(CheckerContext &C, const SVal &Val) const;
  159. void verifyDereference(CheckerContext &C, const SVal &Val) const;
  160. void handleIncrement(CheckerContext &C, const SVal &RetVal, const SVal &Iter,
  161. bool Postfix) const;
  162. void handleDecrement(CheckerContext &C, const SVal &RetVal, const SVal &Iter,
  163. bool Postfix) const;
  164. void handleRandomIncrOrDecr(CheckerContext &C, OverloadedOperatorKind Op,
  165. const SVal &RetVal, const SVal &LHS,
  166. const SVal &RHS) const;
  167. void handleBegin(CheckerContext &C, const Expr *CE, const SVal &RetVal,
  168. const SVal &Cont) const;
  169. void handleEnd(CheckerContext &C, const Expr *CE, const SVal &RetVal,
  170. const SVal &Cont) const;
  171. void assignToContainer(CheckerContext &C, const Expr *CE, const SVal &RetVal,
  172. const MemRegion *Cont) const;
  173. void handleAssign(CheckerContext &C, const SVal &Cont,
  174. const Expr *CE = nullptr,
  175. const SVal &OldCont = UndefinedVal()) const;
  176. void handleClear(CheckerContext &C, const SVal &Cont) const;
  177. void handlePushBack(CheckerContext &C, const SVal &Cont) const;
  178. void handlePopBack(CheckerContext &C, const SVal &Cont) const;
  179. void handlePushFront(CheckerContext &C, const SVal &Cont) const;
  180. void handlePopFront(CheckerContext &C, const SVal &Cont) const;
  181. void handleInsert(CheckerContext &C, const SVal &Iter) const;
  182. void handleErase(CheckerContext &C, const SVal &Iter) const;
  183. void handleErase(CheckerContext &C, const SVal &Iter1,
  184. const SVal &Iter2) const;
  185. void handleEraseAfter(CheckerContext &C, const SVal &Iter) const;
  186. void handleEraseAfter(CheckerContext &C, const SVal &Iter1,
  187. const SVal &Iter2) const;
  188. void verifyIncrement(CheckerContext &C, const SVal &Iter) const;
  189. void verifyDecrement(CheckerContext &C, const SVal &Iter) const;
  190. void verifyRandomIncrOrDecr(CheckerContext &C, OverloadedOperatorKind Op,
  191. const SVal &LHS, const SVal &RHS) const;
  192. void verifyMatch(CheckerContext &C, const SVal &Iter,
  193. const MemRegion *Cont) const;
  194. void verifyMatch(CheckerContext &C, const SVal &Iter1,
  195. const SVal &Iter2) const;
  196. IteratorPosition advancePosition(CheckerContext &C, OverloadedOperatorKind Op,
  197. const IteratorPosition &Pos,
  198. const SVal &Distance) const;
  199. void reportOutOfRangeBug(const StringRef &Message, const SVal &Val,
  200. CheckerContext &C, ExplodedNode *ErrNode) const;
  201. void reportMismatchedBug(const StringRef &Message, const SVal &Val1,
  202. const SVal &Val2, CheckerContext &C,
  203. ExplodedNode *ErrNode) const;
  204. void reportMismatchedBug(const StringRef &Message, const SVal &Val,
  205. const MemRegion *Reg, CheckerContext &C,
  206. ExplodedNode *ErrNode) const;
  207. void reportInvalidatedBug(const StringRef &Message, const SVal &Val,
  208. CheckerContext &C, ExplodedNode *ErrNode) const;
  209. public:
  210. IteratorChecker();
  211. enum CheckKind {
  212. CK_IteratorRangeChecker,
  213. CK_MismatchedIteratorChecker,
  214. CK_InvalidatedIteratorChecker,
  215. CK_NumCheckKinds
  216. };
  217. DefaultBool ChecksEnabled[CK_NumCheckKinds];
  218. CheckerNameRef CheckNames[CK_NumCheckKinds];
  219. void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
  220. void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
  221. void checkBind(SVal Loc, SVal Val, const Stmt *S, CheckerContext &C) const;
  222. void checkPostStmt(const CXXConstructExpr *CCE, CheckerContext &C) const;
  223. void checkPostStmt(const DeclStmt *DS, CheckerContext &C) const;
  224. void checkPostStmt(const MaterializeTemporaryExpr *MTE,
  225. CheckerContext &C) const;
  226. void checkLiveSymbols(ProgramStateRef State, SymbolReaper &SR) const;
  227. void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const;
  228. };
  229. } // namespace
  230. REGISTER_MAP_WITH_PROGRAMSTATE(IteratorSymbolMap, SymbolRef, IteratorPosition)
  231. REGISTER_MAP_WITH_PROGRAMSTATE(IteratorRegionMap, const MemRegion *,
  232. IteratorPosition)
  233. REGISTER_MAP_WITH_PROGRAMSTATE(ContainerMap, const MemRegion *, ContainerData)
  234. namespace {
  235. bool isIteratorType(const QualType &Type);
  236. bool isIterator(const CXXRecordDecl *CRD);
  237. bool isComparisonOperator(OverloadedOperatorKind OK);
  238. bool isBeginCall(const FunctionDecl *Func);
  239. bool isEndCall(const FunctionDecl *Func);
  240. bool isAssignCall(const FunctionDecl *Func);
  241. bool isClearCall(const FunctionDecl *Func);
  242. bool isPushBackCall(const FunctionDecl *Func);
  243. bool isEmplaceBackCall(const FunctionDecl *Func);
  244. bool isPopBackCall(const FunctionDecl *Func);
  245. bool isPushFrontCall(const FunctionDecl *Func);
  246. bool isEmplaceFrontCall(const FunctionDecl *Func);
  247. bool isPopFrontCall(const FunctionDecl *Func);
  248. bool isInsertCall(const FunctionDecl *Func);
  249. bool isEraseCall(const FunctionDecl *Func);
  250. bool isEraseAfterCall(const FunctionDecl *Func);
  251. bool isEmplaceCall(const FunctionDecl *Func);
  252. bool isAssignmentOperator(OverloadedOperatorKind OK);
  253. bool isSimpleComparisonOperator(OverloadedOperatorKind OK);
  254. bool isAccessOperator(OverloadedOperatorKind OK);
  255. bool isDereferenceOperator(OverloadedOperatorKind OK);
  256. bool isIncrementOperator(OverloadedOperatorKind OK);
  257. bool isDecrementOperator(OverloadedOperatorKind OK);
  258. bool isRandomIncrOrDecrOperator(OverloadedOperatorKind OK);
  259. bool hasSubscriptOperator(ProgramStateRef State, const MemRegion *Reg);
  260. bool frontModifiable(ProgramStateRef State, const MemRegion *Reg);
  261. bool backModifiable(ProgramStateRef State, const MemRegion *Reg);
  262. SymbolRef getContainerBegin(ProgramStateRef State, const MemRegion *Cont);
  263. SymbolRef getContainerEnd(ProgramStateRef State, const MemRegion *Cont);
  264. ProgramStateRef createContainerBegin(ProgramStateRef State,
  265. const MemRegion *Cont, const Expr *E,
  266. QualType T, const LocationContext *LCtx,
  267. unsigned BlockCount);
  268. ProgramStateRef createContainerEnd(ProgramStateRef State, const MemRegion *Cont,
  269. const Expr *E, QualType T,
  270. const LocationContext *LCtx,
  271. unsigned BlockCount);
  272. const IteratorPosition *getIteratorPosition(ProgramStateRef State,
  273. const SVal &Val);
  274. ProgramStateRef setIteratorPosition(ProgramStateRef State, const SVal &Val,
  275. const IteratorPosition &Pos);
  276. ProgramStateRef removeIteratorPosition(ProgramStateRef State, const SVal &Val);
  277. ProgramStateRef assumeNoOverflow(ProgramStateRef State, SymbolRef Sym,
  278. long Scale);
  279. ProgramStateRef invalidateAllIteratorPositions(ProgramStateRef State,
  280. const MemRegion *Cont);
  281. ProgramStateRef
  282. invalidateAllIteratorPositionsExcept(ProgramStateRef State,
  283. const MemRegion *Cont, SymbolRef Offset,
  284. BinaryOperator::Opcode Opc);
  285. ProgramStateRef invalidateIteratorPositions(ProgramStateRef State,
  286. SymbolRef Offset,
  287. BinaryOperator::Opcode Opc);
  288. ProgramStateRef invalidateIteratorPositions(ProgramStateRef State,
  289. SymbolRef Offset1,
  290. BinaryOperator::Opcode Opc1,
  291. SymbolRef Offset2,
  292. BinaryOperator::Opcode Opc2);
  293. ProgramStateRef reassignAllIteratorPositions(ProgramStateRef State,
  294. const MemRegion *Cont,
  295. const MemRegion *NewCont);
  296. ProgramStateRef reassignAllIteratorPositionsUnless(ProgramStateRef State,
  297. const MemRegion *Cont,
  298. const MemRegion *NewCont,
  299. SymbolRef Offset,
  300. BinaryOperator::Opcode Opc);
  301. ProgramStateRef rebaseSymbolInIteratorPositionsIf(
  302. ProgramStateRef State, SValBuilder &SVB, SymbolRef OldSym,
  303. SymbolRef NewSym, SymbolRef CondSym, BinaryOperator::Opcode Opc);
  304. ProgramStateRef relateSymbols(ProgramStateRef State, SymbolRef Sym1,
  305. SymbolRef Sym2, bool Equal);
  306. const ContainerData *getContainerData(ProgramStateRef State,
  307. const MemRegion *Cont);
  308. ProgramStateRef setContainerData(ProgramStateRef State, const MemRegion *Cont,
  309. const ContainerData &CData);
  310. bool hasLiveIterators(ProgramStateRef State, const MemRegion *Cont);
  311. bool isBoundThroughLazyCompoundVal(const Environment &Env,
  312. const MemRegion *Reg);
  313. bool isPastTheEnd(ProgramStateRef State, const IteratorPosition &Pos);
  314. bool isAheadOfRange(ProgramStateRef State, const IteratorPosition &Pos);
  315. bool isBehindPastTheEnd(ProgramStateRef State, const IteratorPosition &Pos);
  316. bool isZero(ProgramStateRef State, const NonLoc &Val);
  317. } // namespace
  318. IteratorChecker::IteratorChecker() {
  319. OutOfRangeBugType.reset(
  320. new BugType(this, "Iterator out of range", "Misuse of STL APIs"));
  321. MismatchedBugType.reset(
  322. new BugType(this, "Iterator(s) mismatched", "Misuse of STL APIs",
  323. /*SuppressOnSink=*/true));
  324. InvalidatedBugType.reset(
  325. new BugType(this, "Iterator invalidated", "Misuse of STL APIs"));
  326. }
  327. void IteratorChecker::checkPreCall(const CallEvent &Call,
  328. CheckerContext &C) const {
  329. // Check for out of range access or access of invalidated position and
  330. // iterator mismatches
  331. const auto *Func = dyn_cast_or_null<FunctionDecl>(Call.getDecl());
  332. if (!Func)
  333. return;
  334. if (Func->isOverloadedOperator()) {
  335. if (ChecksEnabled[CK_InvalidatedIteratorChecker] &&
  336. isAccessOperator(Func->getOverloadedOperator())) {
  337. // Check for any kind of access of invalidated iterator positions
  338. if (const auto *InstCall = dyn_cast<CXXInstanceCall>(&Call)) {
  339. verifyAccess(C, InstCall->getCXXThisVal());
  340. } else {
  341. verifyAccess(C, Call.getArgSVal(0));
  342. }
  343. }
  344. if (ChecksEnabled[CK_IteratorRangeChecker]) {
  345. if (isIncrementOperator(Func->getOverloadedOperator())) {
  346. // Check for out-of-range incrementions
  347. if (const auto *InstCall = dyn_cast<CXXInstanceCall>(&Call)) {
  348. verifyIncrement(C, InstCall->getCXXThisVal());
  349. } else {
  350. if (Call.getNumArgs() >= 1) {
  351. verifyIncrement(C, Call.getArgSVal(0));
  352. }
  353. }
  354. } else if (isDecrementOperator(Func->getOverloadedOperator())) {
  355. // Check for out-of-range decrementions
  356. if (const auto *InstCall = dyn_cast<CXXInstanceCall>(&Call)) {
  357. verifyDecrement(C, InstCall->getCXXThisVal());
  358. } else {
  359. if (Call.getNumArgs() >= 1) {
  360. verifyDecrement(C, Call.getArgSVal(0));
  361. }
  362. }
  363. } else if (isRandomIncrOrDecrOperator(Func->getOverloadedOperator())) {
  364. if (const auto *InstCall = dyn_cast<CXXInstanceCall>(&Call)) {
  365. // Check for out-of-range incrementions and decrementions
  366. if (Call.getNumArgs() >= 1 &&
  367. Call.getArgExpr(0)->getType()->isIntegralOrEnumerationType()) {
  368. verifyRandomIncrOrDecr(C, Func->getOverloadedOperator(),
  369. InstCall->getCXXThisVal(),
  370. Call.getArgSVal(0));
  371. }
  372. } else {
  373. if (Call.getNumArgs() >= 2 &&
  374. Call.getArgExpr(1)->getType()->isIntegralOrEnumerationType()) {
  375. verifyRandomIncrOrDecr(C, Func->getOverloadedOperator(),
  376. Call.getArgSVal(0), Call.getArgSVal(1));
  377. }
  378. }
  379. } else if (isDereferenceOperator(Func->getOverloadedOperator())) {
  380. // Check for dereference of out-of-range iterators
  381. if (const auto *InstCall = dyn_cast<CXXInstanceCall>(&Call)) {
  382. verifyDereference(C, InstCall->getCXXThisVal());
  383. } else {
  384. verifyDereference(C, Call.getArgSVal(0));
  385. }
  386. }
  387. } else if (ChecksEnabled[CK_MismatchedIteratorChecker] &&
  388. isComparisonOperator(Func->getOverloadedOperator())) {
  389. // Check for comparisons of iterators of different containers
  390. if (const auto *InstCall = dyn_cast<CXXInstanceCall>(&Call)) {
  391. if (Call.getNumArgs() < 1)
  392. return;
  393. if (!isIteratorType(InstCall->getCXXThisExpr()->getType()) ||
  394. !isIteratorType(Call.getArgExpr(0)->getType()))
  395. return;
  396. verifyMatch(C, InstCall->getCXXThisVal(), Call.getArgSVal(0));
  397. } else {
  398. if (Call.getNumArgs() < 2)
  399. return;
  400. if (!isIteratorType(Call.getArgExpr(0)->getType()) ||
  401. !isIteratorType(Call.getArgExpr(1)->getType()))
  402. return;
  403. verifyMatch(C, Call.getArgSVal(0), Call.getArgSVal(1));
  404. }
  405. }
  406. } else if (const auto *InstCall = dyn_cast<CXXInstanceCall>(&Call)) {
  407. if (!ChecksEnabled[CK_MismatchedIteratorChecker])
  408. return;
  409. const auto *ContReg = InstCall->getCXXThisVal().getAsRegion();
  410. if (!ContReg)
  411. return;
  412. // Check for erase, insert and emplace using iterator of another container
  413. if (isEraseCall(Func) || isEraseAfterCall(Func)) {
  414. verifyMatch(C, Call.getArgSVal(0),
  415. InstCall->getCXXThisVal().getAsRegion());
  416. if (Call.getNumArgs() == 2) {
  417. verifyMatch(C, Call.getArgSVal(1),
  418. InstCall->getCXXThisVal().getAsRegion());
  419. }
  420. } else if (isInsertCall(Func)) {
  421. verifyMatch(C, Call.getArgSVal(0),
  422. InstCall->getCXXThisVal().getAsRegion());
  423. if (Call.getNumArgs() == 3 &&
  424. isIteratorType(Call.getArgExpr(1)->getType()) &&
  425. isIteratorType(Call.getArgExpr(2)->getType())) {
  426. verifyMatch(C, Call.getArgSVal(1), Call.getArgSVal(2));
  427. }
  428. } else if (isEmplaceCall(Func)) {
  429. verifyMatch(C, Call.getArgSVal(0),
  430. InstCall->getCXXThisVal().getAsRegion());
  431. }
  432. } else if (isa<CXXConstructorCall>(&Call)) {
  433. // Check match of first-last iterator pair in a constructor of a container
  434. if (Call.getNumArgs() < 2)
  435. return;
  436. const auto *Ctr = cast<CXXConstructorDecl>(Call.getDecl());
  437. if (Ctr->getNumParams() < 2)
  438. return;
  439. if (Ctr->getParamDecl(0)->getName() != "first" ||
  440. Ctr->getParamDecl(1)->getName() != "last")
  441. return;
  442. if (!isIteratorType(Call.getArgExpr(0)->getType()) ||
  443. !isIteratorType(Call.getArgExpr(1)->getType()))
  444. return;
  445. verifyMatch(C, Call.getArgSVal(0), Call.getArgSVal(1));
  446. } else {
  447. // The main purpose of iterators is to abstract away from different
  448. // containers and provide a (maybe limited) uniform access to them.
  449. // This implies that any correctly written template function that
  450. // works on multiple containers using iterators takes different
  451. // template parameters for different containers. So we can safely
  452. // assume that passing iterators of different containers as arguments
  453. // whose type replaces the same template parameter is a bug.
  454. //
  455. // Example:
  456. // template<typename I1, typename I2>
  457. // void f(I1 first1, I1 last1, I2 first2, I2 last2);
  458. //
  459. // In this case the first two arguments to f() must be iterators must belong
  460. // to the same container and the last to also to the same container but
  461. // not necessarily to the same as the first two.
  462. if (!ChecksEnabled[CK_MismatchedIteratorChecker])
  463. return;
  464. const auto *Templ = Func->getPrimaryTemplate();
  465. if (!Templ)
  466. return;
  467. const auto *TParams = Templ->getTemplateParameters();
  468. const auto *TArgs = Func->getTemplateSpecializationArgs();
  469. // Iterate over all the template parameters
  470. for (size_t I = 0; I < TParams->size(); ++I) {
  471. const auto *TPDecl = dyn_cast<TemplateTypeParmDecl>(TParams->getParam(I));
  472. if (!TPDecl)
  473. continue;
  474. if (TPDecl->isParameterPack())
  475. continue;
  476. const auto TAType = TArgs->get(I).getAsType();
  477. if (!isIteratorType(TAType))
  478. continue;
  479. SVal LHS = UndefinedVal();
  480. // For every template parameter which is an iterator type in the
  481. // instantiation look for all functions' parameters' type by it and
  482. // check whether they belong to the same container
  483. for (auto J = 0U; J < Func->getNumParams(); ++J) {
  484. const auto *Param = Func->getParamDecl(J);
  485. const auto *ParamType =
  486. Param->getType()->getAs<SubstTemplateTypeParmType>();
  487. if (!ParamType ||
  488. ParamType->getReplacedParameter()->getDecl() != TPDecl)
  489. continue;
  490. if (LHS.isUndef()) {
  491. LHS = Call.getArgSVal(J);
  492. } else {
  493. verifyMatch(C, LHS, Call.getArgSVal(J));
  494. }
  495. }
  496. }
  497. }
  498. }
  499. void IteratorChecker::checkPostCall(const CallEvent &Call,
  500. CheckerContext &C) const {
  501. // Record new iterator positions and iterator position changes
  502. const auto *Func = dyn_cast_or_null<FunctionDecl>(Call.getDecl());
  503. if (!Func)
  504. return;
  505. if (Func->isOverloadedOperator()) {
  506. const auto Op = Func->getOverloadedOperator();
  507. if (isAssignmentOperator(Op)) {
  508. // Overloaded 'operator=' must be a non-static member function.
  509. const auto *InstCall = cast<CXXInstanceCall>(&Call);
  510. if (cast<CXXMethodDecl>(Func)->isMoveAssignmentOperator()) {
  511. handleAssign(C, InstCall->getCXXThisVal(), Call.getOriginExpr(),
  512. Call.getArgSVal(0));
  513. return;
  514. }
  515. handleAssign(C, InstCall->getCXXThisVal());
  516. return;
  517. } else if (isSimpleComparisonOperator(Op)) {
  518. const auto *OrigExpr = Call.getOriginExpr();
  519. if (!OrigExpr)
  520. return;
  521. if (const auto *InstCall = dyn_cast<CXXInstanceCall>(&Call)) {
  522. handleComparison(C, OrigExpr, Call.getReturnValue(),
  523. InstCall->getCXXThisVal(), Call.getArgSVal(0), Op);
  524. return;
  525. }
  526. handleComparison(C, OrigExpr, Call.getReturnValue(), Call.getArgSVal(0),
  527. Call.getArgSVal(1), Op);
  528. return;
  529. } else if (isRandomIncrOrDecrOperator(Func->getOverloadedOperator())) {
  530. if (const auto *InstCall = dyn_cast<CXXInstanceCall>(&Call)) {
  531. if (Call.getNumArgs() >= 1 &&
  532. Call.getArgExpr(0)->getType()->isIntegralOrEnumerationType()) {
  533. handleRandomIncrOrDecr(C, Func->getOverloadedOperator(),
  534. Call.getReturnValue(),
  535. InstCall->getCXXThisVal(), Call.getArgSVal(0));
  536. return;
  537. }
  538. } else {
  539. if (Call.getNumArgs() >= 2 &&
  540. Call.getArgExpr(1)->getType()->isIntegralOrEnumerationType()) {
  541. handleRandomIncrOrDecr(C, Func->getOverloadedOperator(),
  542. Call.getReturnValue(), Call.getArgSVal(0),
  543. Call.getArgSVal(1));
  544. return;
  545. }
  546. }
  547. } else if (isIncrementOperator(Func->getOverloadedOperator())) {
  548. if (const auto *InstCall = dyn_cast<CXXInstanceCall>(&Call)) {
  549. handleIncrement(C, Call.getReturnValue(), InstCall->getCXXThisVal(),
  550. Call.getNumArgs());
  551. return;
  552. }
  553. handleIncrement(C, Call.getReturnValue(), Call.getArgSVal(0),
  554. Call.getNumArgs());
  555. return;
  556. } else if (isDecrementOperator(Func->getOverloadedOperator())) {
  557. if (const auto *InstCall = dyn_cast<CXXInstanceCall>(&Call)) {
  558. handleDecrement(C, Call.getReturnValue(), InstCall->getCXXThisVal(),
  559. Call.getNumArgs());
  560. return;
  561. }
  562. handleDecrement(C, Call.getReturnValue(), Call.getArgSVal(0),
  563. Call.getNumArgs());
  564. return;
  565. }
  566. } else {
  567. if (const auto *InstCall = dyn_cast<CXXInstanceCall>(&Call)) {
  568. if (isAssignCall(Func)) {
  569. handleAssign(C, InstCall->getCXXThisVal());
  570. return;
  571. }
  572. if (isClearCall(Func)) {
  573. handleClear(C, InstCall->getCXXThisVal());
  574. return;
  575. }
  576. if (isPushBackCall(Func) || isEmplaceBackCall(Func)) {
  577. handlePushBack(C, InstCall->getCXXThisVal());
  578. return;
  579. }
  580. if (isPopBackCall(Func)) {
  581. handlePopBack(C, InstCall->getCXXThisVal());
  582. return;
  583. }
  584. if (isPushFrontCall(Func) || isEmplaceFrontCall(Func)) {
  585. handlePushFront(C, InstCall->getCXXThisVal());
  586. return;
  587. }
  588. if (isPopFrontCall(Func)) {
  589. handlePopFront(C, InstCall->getCXXThisVal());
  590. return;
  591. }
  592. if (isInsertCall(Func) || isEmplaceCall(Func)) {
  593. handleInsert(C, Call.getArgSVal(0));
  594. return;
  595. }
  596. if (isEraseCall(Func)) {
  597. if (Call.getNumArgs() == 1) {
  598. handleErase(C, Call.getArgSVal(0));
  599. return;
  600. }
  601. if (Call.getNumArgs() == 2) {
  602. handleErase(C, Call.getArgSVal(0), Call.getArgSVal(1));
  603. return;
  604. }
  605. }
  606. if (isEraseAfterCall(Func)) {
  607. if (Call.getNumArgs() == 1) {
  608. handleEraseAfter(C, Call.getArgSVal(0));
  609. return;
  610. }
  611. if (Call.getNumArgs() == 2) {
  612. handleEraseAfter(C, Call.getArgSVal(0), Call.getArgSVal(1));
  613. return;
  614. }
  615. }
  616. }
  617. const auto *OrigExpr = Call.getOriginExpr();
  618. if (!OrigExpr)
  619. return;
  620. if (!isIteratorType(Call.getResultType()))
  621. return;
  622. auto State = C.getState();
  623. if (const auto *InstCall = dyn_cast<CXXInstanceCall>(&Call)) {
  624. if (isBeginCall(Func)) {
  625. handleBegin(C, OrigExpr, Call.getReturnValue(),
  626. InstCall->getCXXThisVal());
  627. return;
  628. }
  629. if (isEndCall(Func)) {
  630. handleEnd(C, OrigExpr, Call.getReturnValue(),
  631. InstCall->getCXXThisVal());
  632. return;
  633. }
  634. }
  635. // Already bound to container?
  636. if (getIteratorPosition(State, Call.getReturnValue()))
  637. return;
  638. // Copy-like and move constructors
  639. if (isa<CXXConstructorCall>(&Call) && Call.getNumArgs() == 1) {
  640. if (const auto *Pos = getIteratorPosition(State, Call.getArgSVal(0))) {
  641. State = setIteratorPosition(State, Call.getReturnValue(), *Pos);
  642. if (cast<CXXConstructorDecl>(Func)->isMoveConstructor()) {
  643. State = removeIteratorPosition(State, Call.getArgSVal(0));
  644. }
  645. C.addTransition(State);
  646. return;
  647. }
  648. }
  649. // Assumption: if return value is an iterator which is not yet bound to a
  650. // container, then look for the first iterator argument, and
  651. // bind the return value to the same container. This approach
  652. // works for STL algorithms.
  653. // FIXME: Add a more conservative mode
  654. for (unsigned i = 0; i < Call.getNumArgs(); ++i) {
  655. if (isIteratorType(Call.getArgExpr(i)->getType())) {
  656. if (const auto *Pos = getIteratorPosition(State, Call.getArgSVal(i))) {
  657. assignToContainer(C, OrigExpr, Call.getReturnValue(),
  658. Pos->getContainer());
  659. return;
  660. }
  661. }
  662. }
  663. }
  664. }
  665. void IteratorChecker::checkBind(SVal Loc, SVal Val, const Stmt *S,
  666. CheckerContext &C) const {
  667. auto State = C.getState();
  668. const auto *Pos = getIteratorPosition(State, Val);
  669. if (Pos) {
  670. State = setIteratorPosition(State, Loc, *Pos);
  671. C.addTransition(State);
  672. } else {
  673. const auto *OldPos = getIteratorPosition(State, Loc);
  674. if (OldPos) {
  675. State = removeIteratorPosition(State, Loc);
  676. C.addTransition(State);
  677. }
  678. }
  679. }
  680. void IteratorChecker::checkPostStmt(const MaterializeTemporaryExpr *MTE,
  681. CheckerContext &C) const {
  682. /* Transfer iterator state to temporary objects */
  683. auto State = C.getState();
  684. const auto *Pos =
  685. getIteratorPosition(State, C.getSVal(MTE->GetTemporaryExpr()));
  686. if (!Pos)
  687. return;
  688. State = setIteratorPosition(State, C.getSVal(MTE), *Pos);
  689. C.addTransition(State);
  690. }
  691. void IteratorChecker::checkLiveSymbols(ProgramStateRef State,
  692. SymbolReaper &SR) const {
  693. // Keep symbolic expressions of iterator positions, container begins and ends
  694. // alive
  695. auto RegionMap = State->get<IteratorRegionMap>();
  696. for (const auto Reg : RegionMap) {
  697. const auto Offset = Reg.second.getOffset();
  698. for (auto i = Offset->symbol_begin(); i != Offset->symbol_end(); ++i)
  699. if (isa<SymbolData>(*i))
  700. SR.markLive(*i);
  701. }
  702. auto SymbolMap = State->get<IteratorSymbolMap>();
  703. for (const auto Sym : SymbolMap) {
  704. const auto Offset = Sym.second.getOffset();
  705. for (auto i = Offset->symbol_begin(); i != Offset->symbol_end(); ++i)
  706. if (isa<SymbolData>(*i))
  707. SR.markLive(*i);
  708. }
  709. auto ContMap = State->get<ContainerMap>();
  710. for (const auto Cont : ContMap) {
  711. const auto CData = Cont.second;
  712. if (CData.getBegin()) {
  713. SR.markLive(CData.getBegin());
  714. if(const auto *SIE = dyn_cast<SymIntExpr>(CData.getBegin()))
  715. SR.markLive(SIE->getLHS());
  716. }
  717. if (CData.getEnd()) {
  718. SR.markLive(CData.getEnd());
  719. if(const auto *SIE = dyn_cast<SymIntExpr>(CData.getEnd()))
  720. SR.markLive(SIE->getLHS());
  721. }
  722. }
  723. }
  724. void IteratorChecker::checkDeadSymbols(SymbolReaper &SR,
  725. CheckerContext &C) const {
  726. // Cleanup
  727. auto State = C.getState();
  728. auto RegionMap = State->get<IteratorRegionMap>();
  729. for (const auto Reg : RegionMap) {
  730. if (!SR.isLiveRegion(Reg.first)) {
  731. // The region behind the `LazyCompoundVal` is often cleaned up before
  732. // the `LazyCompoundVal` itself. If there are iterator positions keyed
  733. // by these regions their cleanup must be deferred.
  734. if (!isBoundThroughLazyCompoundVal(State->getEnvironment(), Reg.first)) {
  735. State = State->remove<IteratorRegionMap>(Reg.first);
  736. }
  737. }
  738. }
  739. auto SymbolMap = State->get<IteratorSymbolMap>();
  740. for (const auto Sym : SymbolMap) {
  741. if (!SR.isLive(Sym.first)) {
  742. State = State->remove<IteratorSymbolMap>(Sym.first);
  743. }
  744. }
  745. auto ContMap = State->get<ContainerMap>();
  746. for (const auto Cont : ContMap) {
  747. if (!SR.isLiveRegion(Cont.first)) {
  748. // We must keep the container data while it has live iterators to be able
  749. // to compare them to the begin and the end of the container.
  750. if (!hasLiveIterators(State, Cont.first)) {
  751. State = State->remove<ContainerMap>(Cont.first);
  752. }
  753. }
  754. }
  755. C.addTransition(State);
  756. }
  757. void IteratorChecker::handleComparison(CheckerContext &C, const Expr *CE,
  758. const SVal &RetVal, const SVal &LVal,
  759. const SVal &RVal,
  760. OverloadedOperatorKind Op) const {
  761. // Record the operands and the operator of the comparison for the next
  762. // evalAssume, if the result is a symbolic expression. If it is a concrete
  763. // value (only one branch is possible), then transfer the state between
  764. // the operands according to the operator and the result
  765. auto State = C.getState();
  766. const auto *LPos = getIteratorPosition(State, LVal);
  767. const auto *RPos = getIteratorPosition(State, RVal);
  768. const MemRegion *Cont = nullptr;
  769. if (LPos) {
  770. Cont = LPos->getContainer();
  771. } else if (RPos) {
  772. Cont = RPos->getContainer();
  773. }
  774. if (!Cont)
  775. return;
  776. // At least one of the iterators have recorded positions. If one of them has
  777. // not then create a new symbol for the offset.
  778. SymbolRef Sym;
  779. if (!LPos || !RPos) {
  780. auto &SymMgr = C.getSymbolManager();
  781. Sym = SymMgr.conjureSymbol(CE, C.getLocationContext(),
  782. C.getASTContext().LongTy, C.blockCount());
  783. State = assumeNoOverflow(State, Sym, 4);
  784. }
  785. if (!LPos) {
  786. State = setIteratorPosition(State, LVal,
  787. IteratorPosition::getPosition(Cont, Sym));
  788. LPos = getIteratorPosition(State, LVal);
  789. } else if (!RPos) {
  790. State = setIteratorPosition(State, RVal,
  791. IteratorPosition::getPosition(Cont, Sym));
  792. RPos = getIteratorPosition(State, RVal);
  793. }
  794. processComparison(C, State, LPos->getOffset(), RPos->getOffset(), RetVal, Op);
  795. }
  796. void IteratorChecker::processComparison(CheckerContext &C,
  797. ProgramStateRef State, SymbolRef Sym1,
  798. SymbolRef Sym2, const SVal &RetVal,
  799. OverloadedOperatorKind Op) const {
  800. if (const auto TruthVal = RetVal.getAs<nonloc::ConcreteInt>()) {
  801. if ((State = relateSymbols(State, Sym1, Sym2,
  802. (Op == OO_EqualEqual) ==
  803. (TruthVal->getValue() != 0)))) {
  804. C.addTransition(State);
  805. } else {
  806. C.generateSink(State, C.getPredecessor());
  807. }
  808. return;
  809. }
  810. const auto ConditionVal = RetVal.getAs<DefinedSVal>();
  811. if (!ConditionVal)
  812. return;
  813. if (auto StateTrue = relateSymbols(State, Sym1, Sym2, Op == OO_EqualEqual)) {
  814. StateTrue = StateTrue->assume(*ConditionVal, true);
  815. C.addTransition(StateTrue);
  816. }
  817. if (auto StateFalse = relateSymbols(State, Sym1, Sym2, Op != OO_EqualEqual)) {
  818. StateFalse = StateFalse->assume(*ConditionVal, false);
  819. C.addTransition(StateFalse);
  820. }
  821. }
  822. void IteratorChecker::verifyDereference(CheckerContext &C,
  823. const SVal &Val) const {
  824. auto State = C.getState();
  825. const auto *Pos = getIteratorPosition(State, Val);
  826. if (Pos && isPastTheEnd(State, *Pos)) {
  827. auto *N = C.generateErrorNode(State);
  828. if (!N)
  829. return;
  830. reportOutOfRangeBug("Past-the-end iterator dereferenced.", Val, C, N);
  831. return;
  832. }
  833. }
  834. void IteratorChecker::verifyAccess(CheckerContext &C, const SVal &Val) const {
  835. auto State = C.getState();
  836. const auto *Pos = getIteratorPosition(State, Val);
  837. if (Pos && !Pos->isValid()) {
  838. auto *N = C.generateErrorNode(State);
  839. if (!N) {
  840. return;
  841. }
  842. reportInvalidatedBug("Invalidated iterator accessed.", Val, C, N);
  843. }
  844. }
  845. void IteratorChecker::handleIncrement(CheckerContext &C, const SVal &RetVal,
  846. const SVal &Iter, bool Postfix) const {
  847. // Increment the symbolic expressions which represents the position of the
  848. // iterator
  849. auto State = C.getState();
  850. const auto *Pos = getIteratorPosition(State, Iter);
  851. if (Pos) {
  852. auto &SymMgr = C.getSymbolManager();
  853. auto &BVF = SymMgr.getBasicVals();
  854. const auto NewPos =
  855. advancePosition(C, OO_Plus, *Pos,
  856. nonloc::ConcreteInt(BVF.getValue(llvm::APSInt::get(1))));
  857. State = setIteratorPosition(State, Iter, NewPos);
  858. State = setIteratorPosition(State, RetVal, Postfix ? *Pos : NewPos);
  859. C.addTransition(State);
  860. }
  861. }
  862. void IteratorChecker::handleDecrement(CheckerContext &C, const SVal &RetVal,
  863. const SVal &Iter, bool Postfix) const {
  864. // Decrement the symbolic expressions which represents the position of the
  865. // iterator
  866. auto State = C.getState();
  867. const auto *Pos = getIteratorPosition(State, Iter);
  868. if (Pos) {
  869. auto &SymMgr = C.getSymbolManager();
  870. auto &BVF = SymMgr.getBasicVals();
  871. const auto NewPos =
  872. advancePosition(C, OO_Minus, *Pos,
  873. nonloc::ConcreteInt(BVF.getValue(llvm::APSInt::get(1))));
  874. State = setIteratorPosition(State, Iter, NewPos);
  875. State = setIteratorPosition(State, RetVal, Postfix ? *Pos : NewPos);
  876. C.addTransition(State);
  877. }
  878. }
  879. void IteratorChecker::handleRandomIncrOrDecr(CheckerContext &C,
  880. OverloadedOperatorKind Op,
  881. const SVal &RetVal,
  882. const SVal &LHS,
  883. const SVal &RHS) const {
  884. // Increment or decrement the symbolic expressions which represents the
  885. // position of the iterator
  886. auto State = C.getState();
  887. const auto *Pos = getIteratorPosition(State, LHS);
  888. if (!Pos)
  889. return;
  890. const auto *value = &RHS;
  891. if (auto loc = RHS.getAs<Loc>()) {
  892. const auto val = State->getRawSVal(*loc);
  893. value = &val;
  894. }
  895. auto &TgtVal = (Op == OO_PlusEqual || Op == OO_MinusEqual) ? LHS : RetVal;
  896. State =
  897. setIteratorPosition(State, TgtVal, advancePosition(C, Op, *Pos, *value));
  898. C.addTransition(State);
  899. }
  900. void IteratorChecker::verifyIncrement(CheckerContext &C,
  901. const SVal &Iter) const {
  902. auto &BVF = C.getSValBuilder().getBasicValueFactory();
  903. verifyRandomIncrOrDecr(C, OO_Plus, Iter,
  904. nonloc::ConcreteInt(BVF.getValue(llvm::APSInt::get(1))));
  905. }
  906. void IteratorChecker::verifyDecrement(CheckerContext &C,
  907. const SVal &Iter) const {
  908. auto &BVF = C.getSValBuilder().getBasicValueFactory();
  909. verifyRandomIncrOrDecr(C, OO_Minus, Iter,
  910. nonloc::ConcreteInt(BVF.getValue(llvm::APSInt::get(1))));
  911. }
  912. void IteratorChecker::verifyRandomIncrOrDecr(CheckerContext &C,
  913. OverloadedOperatorKind Op,
  914. const SVal &LHS,
  915. const SVal &RHS) const {
  916. auto State = C.getState();
  917. // If the iterator is initially inside its range, then the operation is valid
  918. const auto *Pos = getIteratorPosition(State, LHS);
  919. if (!Pos)
  920. return;
  921. auto Value = RHS;
  922. if (auto ValAsLoc = RHS.getAs<Loc>()) {
  923. Value = State->getRawSVal(*ValAsLoc);
  924. }
  925. if (Value.isUnknown())
  926. return;
  927. // Incremention or decremention by 0 is never a bug.
  928. if (isZero(State, Value.castAs<NonLoc>()))
  929. return;
  930. // The result may be the past-end iterator of the container, but any other
  931. // out of range position is undefined behaviour
  932. if (isAheadOfRange(State, advancePosition(C, Op, *Pos, Value))) {
  933. auto *N = C.generateErrorNode(State);
  934. if (!N)
  935. return;
  936. reportOutOfRangeBug("Iterator decremented ahead of its valid range.", LHS,
  937. C, N);
  938. }
  939. if (isBehindPastTheEnd(State, advancePosition(C, Op, *Pos, Value))) {
  940. auto *N = C.generateErrorNode(State);
  941. if (!N)
  942. return;
  943. reportOutOfRangeBug("Iterator incremented behind the past-the-end "
  944. "iterator.", LHS, C, N);
  945. }
  946. }
  947. void IteratorChecker::verifyMatch(CheckerContext &C, const SVal &Iter,
  948. const MemRegion *Cont) const {
  949. // Verify match between a container and the container of an iterator
  950. Cont = Cont->getMostDerivedObjectRegion();
  951. if (const auto *ContSym = Cont->getSymbolicBase()) {
  952. if (isa<SymbolConjured>(ContSym->getSymbol()))
  953. return;
  954. }
  955. auto State = C.getState();
  956. const auto *Pos = getIteratorPosition(State, Iter);
  957. if (!Pos)
  958. return;
  959. const auto *IterCont = Pos->getContainer();
  960. // Skip symbolic regions based on conjured symbols. Two conjured symbols
  961. // may or may not be the same. For example, the same function can return
  962. // the same or a different container but we get different conjured symbols
  963. // for each call. This may cause false positives so omit them from the check.
  964. if (const auto *ContSym = IterCont->getSymbolicBase()) {
  965. if (isa<SymbolConjured>(ContSym->getSymbol()))
  966. return;
  967. }
  968. if (IterCont != Cont) {
  969. auto *N = C.generateNonFatalErrorNode(State);
  970. if (!N) {
  971. return;
  972. }
  973. reportMismatchedBug("Container accessed using foreign iterator argument.",
  974. Iter, Cont, C, N);
  975. }
  976. }
  977. void IteratorChecker::verifyMatch(CheckerContext &C, const SVal &Iter1,
  978. const SVal &Iter2) const {
  979. // Verify match between the containers of two iterators
  980. auto State = C.getState();
  981. const auto *Pos1 = getIteratorPosition(State, Iter1);
  982. if (!Pos1)
  983. return;
  984. const auto *IterCont1 = Pos1->getContainer();
  985. // Skip symbolic regions based on conjured symbols. Two conjured symbols
  986. // may or may not be the same. For example, the same function can return
  987. // the same or a different container but we get different conjured symbols
  988. // for each call. This may cause false positives so omit them from the check.
  989. if (const auto *ContSym = IterCont1->getSymbolicBase()) {
  990. if (isa<SymbolConjured>(ContSym->getSymbol()))
  991. return;
  992. }
  993. const auto *Pos2 = getIteratorPosition(State, Iter2);
  994. if (!Pos2)
  995. return;
  996. const auto *IterCont2 = Pos2->getContainer();
  997. if (const auto *ContSym = IterCont2->getSymbolicBase()) {
  998. if (isa<SymbolConjured>(ContSym->getSymbol()))
  999. return;
  1000. }
  1001. if (IterCont1 != IterCont2) {
  1002. auto *N = C.generateNonFatalErrorNode(State);
  1003. if (!N)
  1004. return;
  1005. reportMismatchedBug("Iterators of different containers used where the "
  1006. "same container is expected.", Iter1, Iter2, C, N);
  1007. }
  1008. }
  1009. void IteratorChecker::handleBegin(CheckerContext &C, const Expr *CE,
  1010. const SVal &RetVal, const SVal &Cont) const {
  1011. const auto *ContReg = Cont.getAsRegion();
  1012. if (!ContReg)
  1013. return;
  1014. ContReg = ContReg->getMostDerivedObjectRegion();
  1015. // If the container already has a begin symbol then use it. Otherwise first
  1016. // create a new one.
  1017. auto State = C.getState();
  1018. auto BeginSym = getContainerBegin(State, ContReg);
  1019. if (!BeginSym) {
  1020. State = createContainerBegin(State, ContReg, CE, C.getASTContext().LongTy,
  1021. C.getLocationContext(), C.blockCount());
  1022. BeginSym = getContainerBegin(State, ContReg);
  1023. }
  1024. State = setIteratorPosition(State, RetVal,
  1025. IteratorPosition::getPosition(ContReg, BeginSym));
  1026. C.addTransition(State);
  1027. }
  1028. void IteratorChecker::handleEnd(CheckerContext &C, const Expr *CE,
  1029. const SVal &RetVal, const SVal &Cont) const {
  1030. const auto *ContReg = Cont.getAsRegion();
  1031. if (!ContReg)
  1032. return;
  1033. ContReg = ContReg->getMostDerivedObjectRegion();
  1034. // If the container already has an end symbol then use it. Otherwise first
  1035. // create a new one.
  1036. auto State = C.getState();
  1037. auto EndSym = getContainerEnd(State, ContReg);
  1038. if (!EndSym) {
  1039. State = createContainerEnd(State, ContReg, CE, C.getASTContext().LongTy,
  1040. C.getLocationContext(), C.blockCount());
  1041. EndSym = getContainerEnd(State, ContReg);
  1042. }
  1043. State = setIteratorPosition(State, RetVal,
  1044. IteratorPosition::getPosition(ContReg, EndSym));
  1045. C.addTransition(State);
  1046. }
  1047. void IteratorChecker::assignToContainer(CheckerContext &C, const Expr *CE,
  1048. const SVal &RetVal,
  1049. const MemRegion *Cont) const {
  1050. Cont = Cont->getMostDerivedObjectRegion();
  1051. auto State = C.getState();
  1052. auto &SymMgr = C.getSymbolManager();
  1053. auto Sym = SymMgr.conjureSymbol(CE, C.getLocationContext(),
  1054. C.getASTContext().LongTy, C.blockCount());
  1055. State = assumeNoOverflow(State, Sym, 4);
  1056. State = setIteratorPosition(State, RetVal,
  1057. IteratorPosition::getPosition(Cont, Sym));
  1058. C.addTransition(State);
  1059. }
  1060. void IteratorChecker::handleAssign(CheckerContext &C, const SVal &Cont,
  1061. const Expr *CE, const SVal &OldCont) const {
  1062. const auto *ContReg = Cont.getAsRegion();
  1063. if (!ContReg)
  1064. return;
  1065. ContReg = ContReg->getMostDerivedObjectRegion();
  1066. // Assignment of a new value to a container always invalidates all its
  1067. // iterators
  1068. auto State = C.getState();
  1069. const auto CData = getContainerData(State, ContReg);
  1070. if (CData) {
  1071. State = invalidateAllIteratorPositions(State, ContReg);
  1072. }
  1073. // In case of move, iterators of the old container (except the past-end
  1074. // iterators) remain valid but refer to the new container
  1075. if (!OldCont.isUndef()) {
  1076. const auto *OldContReg = OldCont.getAsRegion();
  1077. if (OldContReg) {
  1078. OldContReg = OldContReg->getMostDerivedObjectRegion();
  1079. const auto OldCData = getContainerData(State, OldContReg);
  1080. if (OldCData) {
  1081. if (const auto OldEndSym = OldCData->getEnd()) {
  1082. // If we already assigned an "end" symbol to the old container, then
  1083. // first reassign all iterator positions to the new container which
  1084. // are not past the container (thus not greater or equal to the
  1085. // current "end" symbol).
  1086. State = reassignAllIteratorPositionsUnless(State, OldContReg, ContReg,
  1087. OldEndSym, BO_GE);
  1088. auto &SymMgr = C.getSymbolManager();
  1089. auto &SVB = C.getSValBuilder();
  1090. // Then generate and assign a new "end" symbol for the new container.
  1091. auto NewEndSym =
  1092. SymMgr.conjureSymbol(CE, C.getLocationContext(),
  1093. C.getASTContext().LongTy, C.blockCount());
  1094. State = assumeNoOverflow(State, NewEndSym, 4);
  1095. if (CData) {
  1096. State = setContainerData(State, ContReg, CData->newEnd(NewEndSym));
  1097. } else {
  1098. State = setContainerData(State, ContReg,
  1099. ContainerData::fromEnd(NewEndSym));
  1100. }
  1101. // Finally, replace the old "end" symbol in the already reassigned
  1102. // iterator positions with the new "end" symbol.
  1103. State = rebaseSymbolInIteratorPositionsIf(
  1104. State, SVB, OldEndSym, NewEndSym, OldEndSym, BO_LT);
  1105. } else {
  1106. // There was no "end" symbol assigned yet to the old container,
  1107. // so reassign all iterator positions to the new container.
  1108. State = reassignAllIteratorPositions(State, OldContReg, ContReg);
  1109. }
  1110. if (const auto OldBeginSym = OldCData->getBegin()) {
  1111. // If we already assigned a "begin" symbol to the old container, then
  1112. // assign it to the new container and remove it from the old one.
  1113. if (CData) {
  1114. State =
  1115. setContainerData(State, ContReg, CData->newBegin(OldBeginSym));
  1116. } else {
  1117. State = setContainerData(State, ContReg,
  1118. ContainerData::fromBegin(OldBeginSym));
  1119. }
  1120. State =
  1121. setContainerData(State, OldContReg, OldCData->newEnd(nullptr));
  1122. }
  1123. } else {
  1124. // There was neither "begin" nor "end" symbol assigned yet to the old
  1125. // container, so reassign all iterator positions to the new container.
  1126. State = reassignAllIteratorPositions(State, OldContReg, ContReg);
  1127. }
  1128. }
  1129. }
  1130. C.addTransition(State);
  1131. }
  1132. void IteratorChecker::handleClear(CheckerContext &C, const SVal &Cont) const {
  1133. const auto *ContReg = Cont.getAsRegion();
  1134. if (!ContReg)
  1135. return;
  1136. ContReg = ContReg->getMostDerivedObjectRegion();
  1137. // The clear() operation invalidates all the iterators, except the past-end
  1138. // iterators of list-like containers
  1139. auto State = C.getState();
  1140. if (!hasSubscriptOperator(State, ContReg) ||
  1141. !backModifiable(State, ContReg)) {
  1142. const auto CData = getContainerData(State, ContReg);
  1143. if (CData) {
  1144. if (const auto EndSym = CData->getEnd()) {
  1145. State =
  1146. invalidateAllIteratorPositionsExcept(State, ContReg, EndSym, BO_GE);
  1147. C.addTransition(State);
  1148. return;
  1149. }
  1150. }
  1151. }
  1152. State = invalidateAllIteratorPositions(State, ContReg);
  1153. C.addTransition(State);
  1154. }
  1155. void IteratorChecker::handlePushBack(CheckerContext &C,
  1156. const SVal &Cont) const {
  1157. const auto *ContReg = Cont.getAsRegion();
  1158. if (!ContReg)
  1159. return;
  1160. ContReg = ContReg->getMostDerivedObjectRegion();
  1161. // For deque-like containers invalidate all iterator positions
  1162. auto State = C.getState();
  1163. if (hasSubscriptOperator(State, ContReg) && frontModifiable(State, ContReg)) {
  1164. State = invalidateAllIteratorPositions(State, ContReg);
  1165. C.addTransition(State);
  1166. return;
  1167. }
  1168. const auto CData = getContainerData(State, ContReg);
  1169. if (!CData)
  1170. return;
  1171. // For vector-like containers invalidate the past-end iterator positions
  1172. if (const auto EndSym = CData->getEnd()) {
  1173. if (hasSubscriptOperator(State, ContReg)) {
  1174. State = invalidateIteratorPositions(State, EndSym, BO_GE);
  1175. }
  1176. auto &SymMgr = C.getSymbolManager();
  1177. auto &BVF = SymMgr.getBasicVals();
  1178. auto &SVB = C.getSValBuilder();
  1179. const auto newEndSym =
  1180. SVB.evalBinOp(State, BO_Add,
  1181. nonloc::SymbolVal(EndSym),
  1182. nonloc::ConcreteInt(BVF.getValue(llvm::APSInt::get(1))),
  1183. SymMgr.getType(EndSym)).getAsSymbol();
  1184. State = setContainerData(State, ContReg, CData->newEnd(newEndSym));
  1185. }
  1186. C.addTransition(State);
  1187. }
  1188. void IteratorChecker::handlePopBack(CheckerContext &C, const SVal &Cont) const {
  1189. const auto *ContReg = Cont.getAsRegion();
  1190. if (!ContReg)
  1191. return;
  1192. ContReg = ContReg->getMostDerivedObjectRegion();
  1193. auto State = C.getState();
  1194. const auto CData = getContainerData(State, ContReg);
  1195. if (!CData)
  1196. return;
  1197. if (const auto EndSym = CData->getEnd()) {
  1198. auto &SymMgr = C.getSymbolManager();
  1199. auto &BVF = SymMgr.getBasicVals();
  1200. auto &SVB = C.getSValBuilder();
  1201. const auto BackSym =
  1202. SVB.evalBinOp(State, BO_Sub,
  1203. nonloc::SymbolVal(EndSym),
  1204. nonloc::ConcreteInt(BVF.getValue(llvm::APSInt::get(1))),
  1205. SymMgr.getType(EndSym)).getAsSymbol();
  1206. // For vector-like and deque-like containers invalidate the last and the
  1207. // past-end iterator positions. For list-like containers only invalidate
  1208. // the last position
  1209. if (hasSubscriptOperator(State, ContReg) &&
  1210. backModifiable(State, ContReg)) {
  1211. State = invalidateIteratorPositions(State, BackSym, BO_GE);
  1212. State = setContainerData(State, ContReg, CData->newEnd(nullptr));
  1213. } else {
  1214. State = invalidateIteratorPositions(State, BackSym, BO_EQ);
  1215. }
  1216. auto newEndSym = BackSym;
  1217. State = setContainerData(State, ContReg, CData->newEnd(newEndSym));
  1218. C.addTransition(State);
  1219. }
  1220. }
  1221. void IteratorChecker::handlePushFront(CheckerContext &C,
  1222. const SVal &Cont) const {
  1223. const auto *ContReg = Cont.getAsRegion();
  1224. if (!ContReg)
  1225. return;
  1226. ContReg = ContReg->getMostDerivedObjectRegion();
  1227. // For deque-like containers invalidate all iterator positions
  1228. auto State = C.getState();
  1229. if (hasSubscriptOperator(State, ContReg)) {
  1230. State = invalidateAllIteratorPositions(State, ContReg);
  1231. C.addTransition(State);
  1232. } else {
  1233. const auto CData = getContainerData(State, ContReg);
  1234. if (!CData)
  1235. return;
  1236. if (const auto BeginSym = CData->getBegin()) {
  1237. auto &SymMgr = C.getSymbolManager();
  1238. auto &BVF = SymMgr.getBasicVals();
  1239. auto &SVB = C.getSValBuilder();
  1240. const auto newBeginSym =
  1241. SVB.evalBinOp(State, BO_Sub,
  1242. nonloc::SymbolVal(BeginSym),
  1243. nonloc::ConcreteInt(BVF.getValue(llvm::APSInt::get(1))),
  1244. SymMgr.getType(BeginSym)).getAsSymbol();
  1245. State = setContainerData(State, ContReg, CData->newBegin(newBeginSym));
  1246. C.addTransition(State);
  1247. }
  1248. }
  1249. }
  1250. void IteratorChecker::handlePopFront(CheckerContext &C,
  1251. const SVal &Cont) const {
  1252. const auto *ContReg = Cont.getAsRegion();
  1253. if (!ContReg)
  1254. return;
  1255. ContReg = ContReg->getMostDerivedObjectRegion();
  1256. auto State = C.getState();
  1257. const auto CData = getContainerData(State, ContReg);
  1258. if (!CData)
  1259. return;
  1260. // For deque-like containers invalidate all iterator positions. For list-like
  1261. // iterators only invalidate the first position
  1262. if (const auto BeginSym = CData->getBegin()) {
  1263. if (hasSubscriptOperator(State, ContReg)) {
  1264. State = invalidateIteratorPositions(State, BeginSym, BO_LE);
  1265. } else {
  1266. State = invalidateIteratorPositions(State, BeginSym, BO_EQ);
  1267. }
  1268. auto &SymMgr = C.getSymbolManager();
  1269. auto &BVF = SymMgr.getBasicVals();
  1270. auto &SVB = C.getSValBuilder();
  1271. const auto newBeginSym =
  1272. SVB.evalBinOp(State, BO_Add,
  1273. nonloc::SymbolVal(BeginSym),
  1274. nonloc::ConcreteInt(BVF.getValue(llvm::APSInt::get(1))),
  1275. SymMgr.getType(BeginSym)).getAsSymbol();
  1276. State = setContainerData(State, ContReg, CData->newBegin(newBeginSym));
  1277. C.addTransition(State);
  1278. }
  1279. }
  1280. void IteratorChecker::handleInsert(CheckerContext &C, const SVal &Iter) const {
  1281. auto State = C.getState();
  1282. const auto *Pos = getIteratorPosition(State, Iter);
  1283. if (!Pos)
  1284. return;
  1285. // For deque-like containers invalidate all iterator positions. For
  1286. // vector-like containers invalidate iterator positions after the insertion.
  1287. const auto *Cont = Pos->getContainer();
  1288. if (hasSubscriptOperator(State, Cont) && backModifiable(State, Cont)) {
  1289. if (frontModifiable(State, Cont)) {
  1290. State = invalidateAllIteratorPositions(State, Cont);
  1291. } else {
  1292. State = invalidateIteratorPositions(State, Pos->getOffset(), BO_GE);
  1293. }
  1294. if (const auto *CData = getContainerData(State, Cont)) {
  1295. if (const auto EndSym = CData->getEnd()) {
  1296. State = invalidateIteratorPositions(State, EndSym, BO_GE);
  1297. State = setContainerData(State, Cont, CData->newEnd(nullptr));
  1298. }
  1299. }
  1300. C.addTransition(State);
  1301. }
  1302. }
  1303. void IteratorChecker::handleErase(CheckerContext &C, const SVal &Iter) const {
  1304. auto State = C.getState();
  1305. const auto *Pos = getIteratorPosition(State, Iter);
  1306. if (!Pos)
  1307. return;
  1308. // For deque-like containers invalidate all iterator positions. For
  1309. // vector-like containers invalidate iterator positions at and after the
  1310. // deletion. For list-like containers only invalidate the deleted position.
  1311. const auto *Cont = Pos->getContainer();
  1312. if (hasSubscriptOperator(State, Cont) && backModifiable(State, Cont)) {
  1313. if (frontModifiable(State, Cont)) {
  1314. State = invalidateAllIteratorPositions(State, Cont);
  1315. } else {
  1316. State = invalidateIteratorPositions(State, Pos->getOffset(), BO_GE);
  1317. }
  1318. if (const auto *CData = getContainerData(State, Cont)) {
  1319. if (const auto EndSym = CData->getEnd()) {
  1320. State = invalidateIteratorPositions(State, EndSym, BO_GE);
  1321. State = setContainerData(State, Cont, CData->newEnd(nullptr));
  1322. }
  1323. }
  1324. } else {
  1325. State = invalidateIteratorPositions(State, Pos->getOffset(), BO_EQ);
  1326. }
  1327. C.addTransition(State);
  1328. }
  1329. void IteratorChecker::handleErase(CheckerContext &C, const SVal &Iter1,
  1330. const SVal &Iter2) const {
  1331. auto State = C.getState();
  1332. const auto *Pos1 = getIteratorPosition(State, Iter1);
  1333. const auto *Pos2 = getIteratorPosition(State, Iter2);
  1334. if (!Pos1 || !Pos2)
  1335. return;
  1336. // For deque-like containers invalidate all iterator positions. For
  1337. // vector-like containers invalidate iterator positions at and after the
  1338. // deletion range. For list-like containers only invalidate the deleted
  1339. // position range [first..last].
  1340. const auto *Cont = Pos1->getContainer();
  1341. if (hasSubscriptOperator(State, Cont) && backModifiable(State, Cont)) {
  1342. if (frontModifiable(State, Cont)) {
  1343. State = invalidateAllIteratorPositions(State, Cont);
  1344. } else {
  1345. State = invalidateIteratorPositions(State, Pos1->getOffset(), BO_GE);
  1346. }
  1347. if (const auto *CData = getContainerData(State, Cont)) {
  1348. if (const auto EndSym = CData->getEnd()) {
  1349. State = invalidateIteratorPositions(State, EndSym, BO_GE);
  1350. State = setContainerData(State, Cont, CData->newEnd(nullptr));
  1351. }
  1352. }
  1353. } else {
  1354. State = invalidateIteratorPositions(State, Pos1->getOffset(), BO_GE,
  1355. Pos2->getOffset(), BO_LT);
  1356. }
  1357. C.addTransition(State);
  1358. }
  1359. void IteratorChecker::handleEraseAfter(CheckerContext &C,
  1360. const SVal &Iter) const {
  1361. auto State = C.getState();
  1362. const auto *Pos = getIteratorPosition(State, Iter);
  1363. if (!Pos)
  1364. return;
  1365. // Invalidate the deleted iterator position, which is the position of the
  1366. // parameter plus one.
  1367. auto &SymMgr = C.getSymbolManager();
  1368. auto &BVF = SymMgr.getBasicVals();
  1369. auto &SVB = C.getSValBuilder();
  1370. const auto NextSym =
  1371. SVB.evalBinOp(State, BO_Add,
  1372. nonloc::SymbolVal(Pos->getOffset()),
  1373. nonloc::ConcreteInt(BVF.getValue(llvm::APSInt::get(1))),
  1374. SymMgr.getType(Pos->getOffset())).getAsSymbol();
  1375. State = invalidateIteratorPositions(State, NextSym, BO_EQ);
  1376. C.addTransition(State);
  1377. }
  1378. void IteratorChecker::handleEraseAfter(CheckerContext &C, const SVal &Iter1,
  1379. const SVal &Iter2) const {
  1380. auto State = C.getState();
  1381. const auto *Pos1 = getIteratorPosition(State, Iter1);
  1382. const auto *Pos2 = getIteratorPosition(State, Iter2);
  1383. if (!Pos1 || !Pos2)
  1384. return;
  1385. // Invalidate the deleted iterator position range (first..last)
  1386. State = invalidateIteratorPositions(State, Pos1->getOffset(), BO_GT,
  1387. Pos2->getOffset(), BO_LT);
  1388. C.addTransition(State);
  1389. }
  1390. IteratorPosition IteratorChecker::advancePosition(CheckerContext &C,
  1391. OverloadedOperatorKind Op,
  1392. const IteratorPosition &Pos,
  1393. const SVal &Distance) const {
  1394. auto State = C.getState();
  1395. auto &SymMgr = C.getSymbolManager();
  1396. auto &SVB = C.getSValBuilder();
  1397. assert ((Op == OO_Plus || Op == OO_PlusEqual ||
  1398. Op == OO_Minus || Op == OO_MinusEqual) &&
  1399. "Advance operator must be one of +, -, += and -=.");
  1400. auto BinOp = (Op == OO_Plus || Op == OO_PlusEqual) ? BO_Add : BO_Sub;
  1401. if (const auto IntDist = Distance.getAs<nonloc::ConcreteInt>()) {
  1402. // For concrete integers we can calculate the new position
  1403. return Pos.setTo(SVB.evalBinOp(State, BinOp,
  1404. nonloc::SymbolVal(Pos.getOffset()), *IntDist,
  1405. SymMgr.getType(Pos.getOffset()))
  1406. .getAsSymbol());
  1407. } else {
  1408. // For other symbols create a new symbol to keep expressions simple
  1409. const auto &LCtx = C.getLocationContext();
  1410. const auto NewPosSym = SymMgr.conjureSymbol(nullptr, LCtx,
  1411. SymMgr.getType(Pos.getOffset()),
  1412. C.blockCount());
  1413. State = assumeNoOverflow(State, NewPosSym, 4);
  1414. return Pos.setTo(NewPosSym);
  1415. }
  1416. }
  1417. void IteratorChecker::reportOutOfRangeBug(const StringRef &Message,
  1418. const SVal &Val, CheckerContext &C,
  1419. ExplodedNode *ErrNode) const {
  1420. auto R = std::make_unique<PathSensitiveBugReport>(*OutOfRangeBugType, Message,
  1421. ErrNode);
  1422. R->markInteresting(Val);
  1423. C.emitReport(std::move(R));
  1424. }
  1425. void IteratorChecker::reportMismatchedBug(const StringRef &Message,
  1426. const SVal &Val1, const SVal &Val2,
  1427. CheckerContext &C,
  1428. ExplodedNode *ErrNode) const {
  1429. auto R = std::make_unique<PathSensitiveBugReport>(*MismatchedBugType, Message,
  1430. ErrNode);
  1431. R->markInteresting(Val1);
  1432. R->markInteresting(Val2);
  1433. C.emitReport(std::move(R));
  1434. }
  1435. void IteratorChecker::reportMismatchedBug(const StringRef &Message,
  1436. const SVal &Val, const MemRegion *Reg,
  1437. CheckerContext &C,
  1438. ExplodedNode *ErrNode) const {
  1439. auto R = std::make_unique<PathSensitiveBugReport>(*MismatchedBugType, Message,
  1440. ErrNode);
  1441. R->markInteresting(Val);
  1442. R->markInteresting(Reg);
  1443. C.emitReport(std::move(R));
  1444. }
  1445. void IteratorChecker::reportInvalidatedBug(const StringRef &Message,
  1446. const SVal &Val, CheckerContext &C,
  1447. ExplodedNode *ErrNode) const {
  1448. auto R = std::make_unique<PathSensitiveBugReport>(*InvalidatedBugType,
  1449. Message, ErrNode);
  1450. R->markInteresting(Val);
  1451. C.emitReport(std::move(R));
  1452. }
  1453. namespace {
  1454. bool isLess(ProgramStateRef State, SymbolRef Sym1, SymbolRef Sym2);
  1455. bool isGreater(ProgramStateRef State, SymbolRef Sym1, SymbolRef Sym2);
  1456. bool isEqual(ProgramStateRef State, SymbolRef Sym1, SymbolRef Sym2);
  1457. bool compare(ProgramStateRef State, SymbolRef Sym1, SymbolRef Sym2,
  1458. BinaryOperator::Opcode Opc);
  1459. bool compare(ProgramStateRef State, NonLoc NL1, NonLoc NL2,
  1460. BinaryOperator::Opcode Opc);
  1461. const CXXRecordDecl *getCXXRecordDecl(ProgramStateRef State,
  1462. const MemRegion *Reg);
  1463. SymbolRef rebaseSymbol(ProgramStateRef State, SValBuilder &SVB, SymbolRef Expr,
  1464. SymbolRef OldSym, SymbolRef NewSym);
  1465. bool isIteratorType(const QualType &Type) {
  1466. if (Type->isPointerType())
  1467. return true;
  1468. const auto *CRD = Type->getUnqualifiedDesugaredType()->getAsCXXRecordDecl();
  1469. return isIterator(CRD);
  1470. }
  1471. bool isIterator(const CXXRecordDecl *CRD) {
  1472. if (!CRD)
  1473. return false;
  1474. const auto Name = CRD->getName();
  1475. if (!(Name.endswith_lower("iterator") || Name.endswith_lower("iter") ||
  1476. Name.endswith_lower("it")))
  1477. return false;
  1478. bool HasCopyCtor = false, HasCopyAssign = true, HasDtor = false,
  1479. HasPreIncrOp = false, HasPostIncrOp = false, HasDerefOp = false;
  1480. for (const auto *Method : CRD->methods()) {
  1481. if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(Method)) {
  1482. if (Ctor->isCopyConstructor()) {
  1483. HasCopyCtor = !Ctor->isDeleted() && Ctor->getAccess() == AS_public;
  1484. }
  1485. continue;
  1486. }
  1487. if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(Method)) {
  1488. HasDtor = !Dtor->isDeleted() && Dtor->getAccess() == AS_public;
  1489. continue;
  1490. }
  1491. if (Method->isCopyAssignmentOperator()) {
  1492. HasCopyAssign = !Method->isDeleted() && Method->getAccess() == AS_public;
  1493. continue;
  1494. }
  1495. if (!Method->isOverloadedOperator())
  1496. continue;
  1497. const auto OPK = Method->getOverloadedOperator();
  1498. if (OPK == OO_PlusPlus) {
  1499. HasPreIncrOp = HasPreIncrOp || (Method->getNumParams() == 0);
  1500. HasPostIncrOp = HasPostIncrOp || (Method->getNumParams() == 1);
  1501. continue;
  1502. }
  1503. if (OPK == OO_Star) {
  1504. HasDerefOp = (Method->getNumParams() == 0);
  1505. continue;
  1506. }
  1507. }
  1508. return HasCopyCtor && HasCopyAssign && HasDtor && HasPreIncrOp &&
  1509. HasPostIncrOp && HasDerefOp;
  1510. }
  1511. bool isComparisonOperator(OverloadedOperatorKind OK) {
  1512. return OK == OO_EqualEqual || OK == OO_ExclaimEqual || OK == OO_Less ||
  1513. OK == OO_LessEqual || OK == OO_Greater || OK == OO_GreaterEqual;
  1514. }
  1515. bool isBeginCall(const FunctionDecl *Func) {
  1516. const auto *IdInfo = Func->getIdentifier();
  1517. if (!IdInfo)
  1518. return false;
  1519. return IdInfo->getName().endswith_lower("begin");
  1520. }
  1521. bool isEndCall(const FunctionDecl *Func) {
  1522. const auto *IdInfo = Func->getIdentifier();
  1523. if (!IdInfo)
  1524. return false;
  1525. return IdInfo->getName().endswith_lower("end");
  1526. }
  1527. bool isAssignCall(const FunctionDecl *Func) {
  1528. const auto *IdInfo = Func->getIdentifier();
  1529. if (!IdInfo)
  1530. return false;
  1531. if (Func->getNumParams() > 2)
  1532. return false;
  1533. return IdInfo->getName() == "assign";
  1534. }
  1535. bool isClearCall(const FunctionDecl *Func) {
  1536. const auto *IdInfo = Func->getIdentifier();
  1537. if (!IdInfo)
  1538. return false;
  1539. if (Func->getNumParams() > 0)
  1540. return false;
  1541. return IdInfo->getName() == "clear";
  1542. }
  1543. bool isPushBackCall(const FunctionDecl *Func) {
  1544. const auto *IdInfo = Func->getIdentifier();
  1545. if (!IdInfo)
  1546. return false;
  1547. if (Func->getNumParams() != 1)
  1548. return false;
  1549. return IdInfo->getName() == "push_back";
  1550. }
  1551. bool isEmplaceBackCall(const FunctionDecl *Func) {
  1552. const auto *IdInfo = Func->getIdentifier();
  1553. if (!IdInfo)
  1554. return false;
  1555. if (Func->getNumParams() < 1)
  1556. return false;
  1557. return IdInfo->getName() == "emplace_back";
  1558. }
  1559. bool isPopBackCall(const FunctionDecl *Func) {
  1560. const auto *IdInfo = Func->getIdentifier();
  1561. if (!IdInfo)
  1562. return false;
  1563. if (Func->getNumParams() > 0)
  1564. return false;
  1565. return IdInfo->getName() == "pop_back";
  1566. }
  1567. bool isPushFrontCall(const FunctionDecl *Func) {
  1568. const auto *IdInfo = Func->getIdentifier();
  1569. if (!IdInfo)
  1570. return false;
  1571. if (Func->getNumParams() != 1)
  1572. return false;
  1573. return IdInfo->getName() == "push_front";
  1574. }
  1575. bool isEmplaceFrontCall(const FunctionDecl *Func) {
  1576. const auto *IdInfo = Func->getIdentifier();
  1577. if (!IdInfo)
  1578. return false;
  1579. if (Func->getNumParams() < 1)
  1580. return false;
  1581. return IdInfo->getName() == "emplace_front";
  1582. }
  1583. bool isPopFrontCall(const FunctionDecl *Func) {
  1584. const auto *IdInfo = Func->getIdentifier();
  1585. if (!IdInfo)
  1586. return false;
  1587. if (Func->getNumParams() > 0)
  1588. return false;
  1589. return IdInfo->getName() == "pop_front";
  1590. }
  1591. bool isInsertCall(const FunctionDecl *Func) {
  1592. const auto *IdInfo = Func->getIdentifier();
  1593. if (!IdInfo)
  1594. return false;
  1595. if (Func->getNumParams() < 2 || Func->getNumParams() > 3)
  1596. return false;
  1597. if (!isIteratorType(Func->getParamDecl(0)->getType()))
  1598. return false;
  1599. return IdInfo->getName() == "insert";
  1600. }
  1601. bool isEmplaceCall(const FunctionDecl *Func) {
  1602. const auto *IdInfo = Func->getIdentifier();
  1603. if (!IdInfo)
  1604. return false;
  1605. if (Func->getNumParams() < 2)
  1606. return false;
  1607. if (!isIteratorType(Func->getParamDecl(0)->getType()))
  1608. return false;
  1609. return IdInfo->getName() == "emplace";
  1610. }
  1611. bool isEraseCall(const FunctionDecl *Func) {
  1612. const auto *IdInfo = Func->getIdentifier();
  1613. if (!IdInfo)
  1614. return false;
  1615. if (Func->getNumParams() < 1 || Func->getNumParams() > 2)
  1616. return false;
  1617. if (!isIteratorType(Func->getParamDecl(0)->getType()))
  1618. return false;
  1619. if (Func->getNumParams() == 2 &&
  1620. !isIteratorType(Func->getParamDecl(1)->getType()))
  1621. return false;
  1622. return IdInfo->getName() == "erase";
  1623. }
  1624. bool isEraseAfterCall(const FunctionDecl *Func) {
  1625. const auto *IdInfo = Func->getIdentifier();
  1626. if (!IdInfo)
  1627. return false;
  1628. if (Func->getNumParams() < 1 || Func->getNumParams() > 2)
  1629. return false;
  1630. if (!isIteratorType(Func->getParamDecl(0)->getType()))
  1631. return false;
  1632. if (Func->getNumParams() == 2 &&
  1633. !isIteratorType(Func->getParamDecl(1)->getType()))
  1634. return false;
  1635. return IdInfo->getName() == "erase_after";
  1636. }
  1637. bool isAssignmentOperator(OverloadedOperatorKind OK) { return OK == OO_Equal; }
  1638. bool isSimpleComparisonOperator(OverloadedOperatorKind OK) {
  1639. return OK == OO_EqualEqual || OK == OO_ExclaimEqual;
  1640. }
  1641. bool isAccessOperator(OverloadedOperatorKind OK) {
  1642. return isDereferenceOperator(OK) || isIncrementOperator(OK) ||
  1643. isDecrementOperator(OK) || isRandomIncrOrDecrOperator(OK);
  1644. }
  1645. bool isDereferenceOperator(OverloadedOperatorKind OK) {
  1646. return OK == OO_Star || OK == OO_Arrow || OK == OO_ArrowStar ||
  1647. OK == OO_Subscript;
  1648. }
  1649. bool isIncrementOperator(OverloadedOperatorKind OK) {
  1650. return OK == OO_PlusPlus;
  1651. }
  1652. bool isDecrementOperator(OverloadedOperatorKind OK) {
  1653. return OK == OO_MinusMinus;
  1654. }
  1655. bool isRandomIncrOrDecrOperator(OverloadedOperatorKind OK) {
  1656. return OK == OO_Plus || OK == OO_PlusEqual || OK == OO_Minus ||
  1657. OK == OO_MinusEqual;
  1658. }
  1659. bool hasSubscriptOperator(ProgramStateRef State, const MemRegion *Reg) {
  1660. const auto *CRD = getCXXRecordDecl(State, Reg);
  1661. if (!CRD)
  1662. return false;
  1663. for (const auto *Method : CRD->methods()) {
  1664. if (!Method->isOverloadedOperator())
  1665. continue;
  1666. const auto OPK = Method->getOverloadedOperator();
  1667. if (OPK == OO_Subscript) {
  1668. return true;
  1669. }
  1670. }
  1671. return false;
  1672. }
  1673. bool frontModifiable(ProgramStateRef State, const MemRegion *Reg) {
  1674. const auto *CRD = getCXXRecordDecl(State, Reg);
  1675. if (!CRD)
  1676. return false;
  1677. for (const auto *Method : CRD->methods()) {
  1678. if (!Method->getDeclName().isIdentifier())
  1679. continue;
  1680. if (Method->getName() == "push_front" || Method->getName() == "pop_front") {
  1681. return true;
  1682. }
  1683. }
  1684. return false;
  1685. }
  1686. bool backModifiable(ProgramStateRef State, const MemRegion *Reg) {
  1687. const auto *CRD = getCXXRecordDecl(State, Reg);
  1688. if (!CRD)
  1689. return false;
  1690. for (const auto *Method : CRD->methods()) {
  1691. if (!Method->getDeclName().isIdentifier())
  1692. continue;
  1693. if (Method->getName() == "push_back" || Method->getName() == "pop_back") {
  1694. return true;
  1695. }
  1696. }
  1697. return false;
  1698. }
  1699. const CXXRecordDecl *getCXXRecordDecl(ProgramStateRef State,
  1700. const MemRegion *Reg) {
  1701. auto TI = getDynamicTypeInfo(State, Reg);
  1702. if (!TI.isValid())
  1703. return nullptr;
  1704. auto Type = TI.getType();
  1705. if (const auto *RefT = Type->getAs<ReferenceType>()) {
  1706. Type = RefT->getPointeeType();
  1707. }
  1708. return Type->getUnqualifiedDesugaredType()->getAsCXXRecordDecl();
  1709. }
  1710. SymbolRef getContainerBegin(ProgramStateRef State, const MemRegion *Cont) {
  1711. const auto *CDataPtr = getContainerData(State, Cont);
  1712. if (!CDataPtr)
  1713. return nullptr;
  1714. return CDataPtr->getBegin();
  1715. }
  1716. SymbolRef getContainerEnd(ProgramStateRef State, const MemRegion *Cont) {
  1717. const auto *CDataPtr = getContainerData(State, Cont);
  1718. if (!CDataPtr)
  1719. return nullptr;
  1720. return CDataPtr->getEnd();
  1721. }
  1722. ProgramStateRef createContainerBegin(ProgramStateRef State,
  1723. const MemRegion *Cont, const Expr *E,
  1724. QualType T, const LocationContext *LCtx,
  1725. unsigned BlockCount) {
  1726. // Only create if it does not exist
  1727. const auto *CDataPtr = getContainerData(State, Cont);
  1728. if (CDataPtr && CDataPtr->getBegin())
  1729. return State;
  1730. auto &SymMgr = State->getSymbolManager();
  1731. const SymbolConjured *Sym = SymMgr.conjureSymbol(E, LCtx, T, BlockCount,
  1732. "begin");
  1733. State = assumeNoOverflow(State, Sym, 4);
  1734. if (CDataPtr) {
  1735. const auto CData = CDataPtr->newBegin(Sym);
  1736. return setContainerData(State, Cont, CData);
  1737. }
  1738. const auto CData = ContainerData::fromBegin(Sym);
  1739. return setContainerData(State, Cont, CData);
  1740. }
  1741. ProgramStateRef createContainerEnd(ProgramStateRef State, const MemRegion *Cont,
  1742. const Expr *E, QualType T,
  1743. const LocationContext *LCtx,
  1744. unsigned BlockCount) {
  1745. // Only create if it does not exist
  1746. const auto *CDataPtr = getContainerData(State, Cont);
  1747. if (CDataPtr && CDataPtr->getEnd())
  1748. return State;
  1749. auto &SymMgr = State->getSymbolManager();
  1750. const SymbolConjured *Sym = SymMgr.conjureSymbol(E, LCtx, T, BlockCount,
  1751. "end");
  1752. State = assumeNoOverflow(State, Sym, 4);
  1753. if (CDataPtr) {
  1754. const auto CData = CDataPtr->newEnd(Sym);
  1755. return setContainerData(State, Cont, CData);
  1756. }
  1757. const auto CData = ContainerData::fromEnd(Sym);
  1758. return setContainerData(State, Cont, CData);
  1759. }
  1760. const ContainerData *getContainerData(ProgramStateRef State,
  1761. const MemRegion *Cont) {
  1762. return State->get<ContainerMap>(Cont);
  1763. }
  1764. ProgramStateRef setContainerData(ProgramStateRef State, const MemRegion *Cont,
  1765. const ContainerData &CData) {
  1766. return State->set<ContainerMap>(Cont, CData);
  1767. }
  1768. const IteratorPosition *getIteratorPosition(ProgramStateRef State,
  1769. const SVal &Val) {
  1770. if (auto Reg = Val.getAsRegion()) {
  1771. Reg = Reg->getMostDerivedObjectRegion();
  1772. return State->get<IteratorRegionMap>(Reg);
  1773. } else if (const auto Sym = Val.getAsSymbol()) {
  1774. return State->get<IteratorSymbolMap>(Sym);
  1775. } else if (const auto LCVal = Val.getAs<nonloc::LazyCompoundVal>()) {
  1776. return State->get<IteratorRegionMap>(LCVal->getRegion());
  1777. }
  1778. return nullptr;
  1779. }
  1780. ProgramStateRef setIteratorPosition(ProgramStateRef State, const SVal &Val,
  1781. const IteratorPosition &Pos) {
  1782. if (auto Reg = Val.getAsRegion()) {
  1783. Reg = Reg->getMostDerivedObjectRegion();
  1784. return State->set<IteratorRegionMap>(Reg, Pos);
  1785. } else if (const auto Sym = Val.getAsSymbol()) {
  1786. return State->set<IteratorSymbolMap>(Sym, Pos);
  1787. } else if (const auto LCVal = Val.getAs<nonloc::LazyCompoundVal>()) {
  1788. return State->set<IteratorRegionMap>(LCVal->getRegion(), Pos);
  1789. }
  1790. return nullptr;
  1791. }
  1792. ProgramStateRef removeIteratorPosition(ProgramStateRef State, const SVal &Val) {
  1793. if (auto Reg = Val.getAsRegion()) {
  1794. Reg = Reg->getMostDerivedObjectRegion();
  1795. return State->remove<IteratorRegionMap>(Reg);
  1796. } else if (const auto Sym = Val.getAsSymbol()) {
  1797. return State->remove<IteratorSymbolMap>(Sym);
  1798. } else if (const auto LCVal = Val.getAs<nonloc::LazyCompoundVal>()) {
  1799. return State->remove<IteratorRegionMap>(LCVal->getRegion());
  1800. }
  1801. return nullptr;
  1802. }
  1803. ProgramStateRef relateSymbols(ProgramStateRef State, SymbolRef Sym1,
  1804. SymbolRef Sym2, bool Equal) {
  1805. auto &SVB = State->getStateManager().getSValBuilder();
  1806. // FIXME: This code should be reworked as follows:
  1807. // 1. Subtract the operands using evalBinOp().
  1808. // 2. Assume that the result doesn't overflow.
  1809. // 3. Compare the result to 0.
  1810. // 4. Assume the result of the comparison.
  1811. const auto comparison =
  1812. SVB.evalBinOp(State, BO_EQ, nonloc::SymbolVal(Sym1),
  1813. nonloc::SymbolVal(Sym2), SVB.getConditionType());
  1814. assert(comparison.getAs<DefinedSVal>() &&
  1815. "Symbol comparison must be a `DefinedSVal`");
  1816. auto NewState = State->assume(comparison.castAs<DefinedSVal>(), Equal);
  1817. if (!NewState)
  1818. return nullptr;
  1819. if (const auto CompSym = comparison.getAsSymbol()) {
  1820. assert(isa<SymIntExpr>(CompSym) &&
  1821. "Symbol comparison must be a `SymIntExpr`");
  1822. assert(BinaryOperator::isComparisonOp(
  1823. cast<SymIntExpr>(CompSym)->getOpcode()) &&
  1824. "Symbol comparison must be a comparison");
  1825. return assumeNoOverflow(NewState, cast<SymIntExpr>(CompSym)->getLHS(), 2);
  1826. }
  1827. return NewState;
  1828. }
  1829. bool hasLiveIterators(ProgramStateRef State, const MemRegion *Cont) {
  1830. auto RegionMap = State->get<IteratorRegionMap>();
  1831. for (const auto Reg : RegionMap) {
  1832. if (Reg.second.getContainer() == Cont)
  1833. return true;
  1834. }
  1835. auto SymbolMap = State->get<IteratorSymbolMap>();
  1836. for (const auto Sym : SymbolMap) {
  1837. if (Sym.second.getContainer() == Cont)
  1838. return true;
  1839. }
  1840. return false;
  1841. }
  1842. bool isBoundThroughLazyCompoundVal(const Environment &Env,
  1843. const MemRegion *Reg) {
  1844. for (const auto Binding: Env) {
  1845. if (const auto LCVal = Binding.second.getAs<nonloc::LazyCompoundVal>()) {
  1846. if (LCVal->getRegion() == Reg)
  1847. return true;
  1848. }
  1849. }
  1850. return false;
  1851. }
  1852. // This function tells the analyzer's engine that symbols produced by our
  1853. // checker, most notably iterator positions, are relatively small.
  1854. // A distance between items in the container should not be very large.
  1855. // By assuming that it is within around 1/8 of the address space,
  1856. // we can help the analyzer perform operations on these symbols
  1857. // without being afraid of integer overflows.
  1858. // FIXME: Should we provide it as an API, so that all checkers could use it?
  1859. ProgramStateRef assumeNoOverflow(ProgramStateRef State, SymbolRef Sym,
  1860. long Scale) {
  1861. SValBuilder &SVB = State->getStateManager().getSValBuilder();
  1862. BasicValueFactory &BV = SVB.getBasicValueFactory();
  1863. QualType T = Sym->getType();
  1864. assert(T->isSignedIntegerOrEnumerationType());
  1865. APSIntType AT = BV.getAPSIntType(T);
  1866. ProgramStateRef NewState = State;
  1867. llvm::APSInt Max = AT.getMaxValue() / AT.getValue(Scale);
  1868. SVal IsCappedFromAbove =
  1869. SVB.evalBinOpNN(State, BO_LE, nonloc::SymbolVal(Sym),
  1870. nonloc::ConcreteInt(Max), SVB.getConditionType());
  1871. if (auto DV = IsCappedFromAbove.getAs<DefinedSVal>()) {
  1872. NewState = NewState->assume(*DV, true);
  1873. if (!NewState)
  1874. return State;
  1875. }
  1876. llvm::APSInt Min = -Max;
  1877. SVal IsCappedFromBelow =
  1878. SVB.evalBinOpNN(State, BO_GE, nonloc::SymbolVal(Sym),
  1879. nonloc::ConcreteInt(Min), SVB.getConditionType());
  1880. if (auto DV = IsCappedFromBelow.getAs<DefinedSVal>()) {
  1881. NewState = NewState->assume(*DV, true);
  1882. if (!NewState)
  1883. return State;
  1884. }
  1885. return NewState;
  1886. }
  1887. template <typename Condition, typename Process>
  1888. ProgramStateRef processIteratorPositions(ProgramStateRef State, Condition Cond,
  1889. Process Proc) {
  1890. auto &RegionMapFactory = State->get_context<IteratorRegionMap>();
  1891. auto RegionMap = State->get<IteratorRegionMap>();
  1892. bool Changed = false;
  1893. for (const auto Reg : RegionMap) {
  1894. if (Cond(Reg.second)) {
  1895. RegionMap = RegionMapFactory.add(RegionMap, Reg.first, Proc(Reg.second));
  1896. Changed = true;
  1897. }
  1898. }
  1899. if (Changed)
  1900. State = State->set<IteratorRegionMap>(RegionMap);
  1901. auto &SymbolMapFactory = State->get_context<IteratorSymbolMap>();
  1902. auto SymbolMap = State->get<IteratorSymbolMap>();
  1903. Changed = false;
  1904. for (const auto Sym : SymbolMap) {
  1905. if (Cond(Sym.second)) {
  1906. SymbolMap = SymbolMapFactory.add(SymbolMap, Sym.first, Proc(Sym.second));
  1907. Changed = true;
  1908. }
  1909. }
  1910. if (Changed)
  1911. State = State->set<IteratorSymbolMap>(SymbolMap);
  1912. return State;
  1913. }
  1914. ProgramStateRef invalidateAllIteratorPositions(ProgramStateRef State,
  1915. const MemRegion *Cont) {
  1916. auto MatchCont = [&](const IteratorPosition &Pos) {
  1917. return Pos.getContainer() == Cont;
  1918. };
  1919. auto Invalidate = [&](const IteratorPosition &Pos) {
  1920. return Pos.invalidate();
  1921. };
  1922. return processIteratorPositions(State, MatchCont, Invalidate);
  1923. }
  1924. ProgramStateRef
  1925. invalidateAllIteratorPositionsExcept(ProgramStateRef State,
  1926. const MemRegion *Cont, SymbolRef Offset,
  1927. BinaryOperator::Opcode Opc) {
  1928. auto MatchContAndCompare = [&](const IteratorPosition &Pos) {
  1929. return Pos.getContainer() == Cont &&
  1930. !compare(State, Pos.getOffset(), Offset, Opc);
  1931. };
  1932. auto Invalidate = [&](const IteratorPosition &Pos) {
  1933. return Pos.invalidate();
  1934. };
  1935. return processIteratorPositions(State, MatchContAndCompare, Invalidate);
  1936. }
  1937. ProgramStateRef invalidateIteratorPositions(ProgramStateRef State,
  1938. SymbolRef Offset,
  1939. BinaryOperator::Opcode Opc) {
  1940. auto Compare = [&](const IteratorPosition &Pos) {
  1941. return compare(State, Pos.getOffset(), Offset, Opc);
  1942. };
  1943. auto Invalidate = [&](const IteratorPosition &Pos) {
  1944. return Pos.invalidate();
  1945. };
  1946. return processIteratorPositions(State, Compare, Invalidate);
  1947. }
  1948. ProgramStateRef invalidateIteratorPositions(ProgramStateRef State,
  1949. SymbolRef Offset1,
  1950. BinaryOperator::Opcode Opc1,
  1951. SymbolRef Offset2,
  1952. BinaryOperator::Opcode Opc2) {
  1953. auto Compare = [&](const IteratorPosition &Pos) {
  1954. return compare(State, Pos.getOffset(), Offset1, Opc1) &&
  1955. compare(State, Pos.getOffset(), Offset2, Opc2);
  1956. };
  1957. auto Invalidate = [&](const IteratorPosition &Pos) {
  1958. return Pos.invalidate();
  1959. };
  1960. return processIteratorPositions(State, Compare, Invalidate);
  1961. }
  1962. ProgramStateRef reassignAllIteratorPositions(ProgramStateRef State,
  1963. const MemRegion *Cont,
  1964. const MemRegion *NewCont) {
  1965. auto MatchCont = [&](const IteratorPosition &Pos) {
  1966. return Pos.getContainer() == Cont;
  1967. };
  1968. auto ReAssign = [&](const IteratorPosition &Pos) {
  1969. return Pos.reAssign(NewCont);
  1970. };
  1971. return processIteratorPositions(State, MatchCont, ReAssign);
  1972. }
  1973. ProgramStateRef reassignAllIteratorPositionsUnless(ProgramStateRef State,
  1974. const MemRegion *Cont,
  1975. const MemRegion *NewCont,
  1976. SymbolRef Offset,
  1977. BinaryOperator::Opcode Opc) {
  1978. auto MatchContAndCompare = [&](const IteratorPosition &Pos) {
  1979. return Pos.getContainer() == Cont &&
  1980. !compare(State, Pos.getOffset(), Offset, Opc);
  1981. };
  1982. auto ReAssign = [&](const IteratorPosition &Pos) {
  1983. return Pos.reAssign(NewCont);
  1984. };
  1985. return processIteratorPositions(State, MatchContAndCompare, ReAssign);
  1986. }
  1987. // This function rebases symbolic expression `OldSym + Int` to `NewSym + Int`,
  1988. // `OldSym - Int` to `NewSym - Int` and `OldSym` to `NewSym` in any iterator
  1989. // position offsets where `CondSym` is true.
  1990. ProgramStateRef rebaseSymbolInIteratorPositionsIf(
  1991. ProgramStateRef State, SValBuilder &SVB, SymbolRef OldSym,
  1992. SymbolRef NewSym, SymbolRef CondSym, BinaryOperator::Opcode Opc) {
  1993. auto LessThanEnd = [&](const IteratorPosition &Pos) {
  1994. return compare(State, Pos.getOffset(), CondSym, Opc);
  1995. };
  1996. auto RebaseSymbol = [&](const IteratorPosition &Pos) {
  1997. return Pos.setTo(rebaseSymbol(State, SVB, Pos.getOffset(), OldSym,
  1998. NewSym));
  1999. };
  2000. return processIteratorPositions(State, LessThanEnd, RebaseSymbol);
  2001. }
  2002. // This function rebases symbolic expression `OldExpr + Int` to `NewExpr + Int`,
  2003. // `OldExpr - Int` to `NewExpr - Int` and `OldExpr` to `NewExpr` in expression
  2004. // `OrigExpr`.
  2005. SymbolRef rebaseSymbol(ProgramStateRef State, SValBuilder &SVB,
  2006. SymbolRef OrigExpr, SymbolRef OldExpr,
  2007. SymbolRef NewSym) {
  2008. auto &SymMgr = SVB.getSymbolManager();
  2009. auto Diff = SVB.evalBinOpNN(State, BO_Sub, nonloc::SymbolVal(OrigExpr),
  2010. nonloc::SymbolVal(OldExpr),
  2011. SymMgr.getType(OrigExpr));
  2012. const auto DiffInt = Diff.getAs<nonloc::ConcreteInt>();
  2013. if (!DiffInt)
  2014. return OrigExpr;
  2015. return SVB.evalBinOpNN(State, BO_Add, *DiffInt, nonloc::SymbolVal(NewSym),
  2016. SymMgr.getType(OrigExpr)).getAsSymbol();
  2017. }
  2018. bool isZero(ProgramStateRef State, const NonLoc &Val) {
  2019. auto &BVF = State->getBasicVals();
  2020. return compare(State, Val,
  2021. nonloc::ConcreteInt(BVF.getValue(llvm::APSInt::get(0))),
  2022. BO_EQ);
  2023. }
  2024. bool isPastTheEnd(ProgramStateRef State, const IteratorPosition &Pos) {
  2025. const auto *Cont = Pos.getContainer();
  2026. const auto *CData = getContainerData(State, Cont);
  2027. if (!CData)
  2028. return false;
  2029. const auto End = CData->getEnd();
  2030. if (End) {
  2031. if (isEqual(State, Pos.getOffset(), End)) {
  2032. return true;
  2033. }
  2034. }
  2035. return false;
  2036. }
  2037. bool isAheadOfRange(ProgramStateRef State, const IteratorPosition &Pos) {
  2038. const auto *Cont = Pos.getContainer();
  2039. const auto *CData = getContainerData(State, Cont);
  2040. if (!CData)
  2041. return false;
  2042. const auto Beg = CData->getBegin();
  2043. if (Beg) {
  2044. if (isLess(State, Pos.getOffset(), Beg)) {
  2045. return true;
  2046. }
  2047. }
  2048. return false;
  2049. }
  2050. bool isBehindPastTheEnd(ProgramStateRef State, const IteratorPosition &Pos) {
  2051. const auto *Cont = Pos.getContainer();
  2052. const auto *CData = getContainerData(State, Cont);
  2053. if (!CData)
  2054. return false;
  2055. const auto End = CData->getEnd();
  2056. if (End) {
  2057. if (isGreater(State, Pos.getOffset(), End)) {
  2058. return true;
  2059. }
  2060. }
  2061. return false;
  2062. }
  2063. bool isLess(ProgramStateRef State, SymbolRef Sym1, SymbolRef Sym2) {
  2064. return compare(State, Sym1, Sym2, BO_LT);
  2065. }
  2066. bool isGreater(ProgramStateRef State, SymbolRef Sym1, SymbolRef Sym2) {
  2067. return compare(State, Sym1, Sym2, BO_GT);
  2068. }
  2069. bool isEqual(ProgramStateRef State, SymbolRef Sym1, SymbolRef Sym2) {
  2070. return compare(State, Sym1, Sym2, BO_EQ);
  2071. }
  2072. bool compare(ProgramStateRef State, SymbolRef Sym1, SymbolRef Sym2,
  2073. BinaryOperator::Opcode Opc) {
  2074. return compare(State, nonloc::SymbolVal(Sym1), nonloc::SymbolVal(Sym2), Opc);
  2075. }
  2076. bool compare(ProgramStateRef State, NonLoc NL1, NonLoc NL2,
  2077. BinaryOperator::Opcode Opc) {
  2078. auto &SVB = State->getStateManager().getSValBuilder();
  2079. const auto comparison =
  2080. SVB.evalBinOp(State, Opc, NL1, NL2, SVB.getConditionType());
  2081. assert(comparison.getAs<DefinedSVal>() &&
  2082. "Symbol comparison must be a `DefinedSVal`");
  2083. return !State->assume(comparison.castAs<DefinedSVal>(), false);
  2084. }
  2085. } // namespace
  2086. void ento::registerIteratorModeling(CheckerManager &mgr) {
  2087. mgr.registerChecker<IteratorChecker>();
  2088. }
  2089. bool ento::shouldRegisterIteratorModeling(const LangOptions &LO) {
  2090. return true;
  2091. }
  2092. #define REGISTER_CHECKER(name) \
  2093. void ento::register##name(CheckerManager &Mgr) { \
  2094. auto *checker = Mgr.getChecker<IteratorChecker>(); \
  2095. checker->ChecksEnabled[IteratorChecker::CK_##name] = true; \
  2096. checker->CheckNames[IteratorChecker::CK_##name] = \
  2097. Mgr.getCurrentCheckerName(); \
  2098. } \
  2099. \
  2100. bool ento::shouldRegister##name(const LangOptions &LO) { return true; }
  2101. REGISTER_CHECKER(IteratorRangeChecker)
  2102. REGISTER_CHECKER(MismatchedIteratorChecker)
  2103. REGISTER_CHECKER(InvalidatedIteratorChecker)