CStringChecker.cpp 85 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270
  1. //= CStringChecker.cpp - Checks calls to C string functions --------*- C++ -*-//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This defines CStringChecker, which is an assortment of checks on calls
  11. // to functions in <string.h>.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "ClangSACheckers.h"
  15. #include "InterCheckerAPI.h"
  16. #include "clang/Basic/CharInfo.h"
  17. #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
  18. #include "clang/StaticAnalyzer/Core/Checker.h"
  19. #include "clang/StaticAnalyzer/Core/CheckerManager.h"
  20. #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
  21. #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
  22. #include "llvm/ADT/STLExtras.h"
  23. #include "llvm/ADT/SmallString.h"
  24. #include "llvm/Support/raw_ostream.h"
  25. using namespace clang;
  26. using namespace ento;
  27. namespace {
  28. class CStringChecker : public Checker< eval::Call,
  29. check::PreStmt<DeclStmt>,
  30. check::LiveSymbols,
  31. check::DeadSymbols,
  32. check::RegionChanges
  33. > {
  34. mutable std::unique_ptr<BugType> BT_Null, BT_Bounds, BT_Overlap,
  35. BT_NotCString, BT_AdditionOverflow;
  36. mutable const char *CurrentFunctionDescription;
  37. public:
  38. /// The filter is used to filter out the diagnostics which are not enabled by
  39. /// the user.
  40. struct CStringChecksFilter {
  41. DefaultBool CheckCStringNullArg;
  42. DefaultBool CheckCStringOutOfBounds;
  43. DefaultBool CheckCStringBufferOverlap;
  44. DefaultBool CheckCStringNotNullTerm;
  45. CheckName CheckNameCStringNullArg;
  46. CheckName CheckNameCStringOutOfBounds;
  47. CheckName CheckNameCStringBufferOverlap;
  48. CheckName CheckNameCStringNotNullTerm;
  49. };
  50. CStringChecksFilter Filter;
  51. static void *getTag() { static int tag; return &tag; }
  52. bool evalCall(const CallExpr *CE, CheckerContext &C) const;
  53. void checkPreStmt(const DeclStmt *DS, CheckerContext &C) const;
  54. void checkLiveSymbols(ProgramStateRef state, SymbolReaper &SR) const;
  55. void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const;
  56. ProgramStateRef
  57. checkRegionChanges(ProgramStateRef state,
  58. const InvalidatedSymbols *,
  59. ArrayRef<const MemRegion *> ExplicitRegions,
  60. ArrayRef<const MemRegion *> Regions,
  61. const LocationContext *LCtx,
  62. const CallEvent *Call) const;
  63. typedef void (CStringChecker::*FnCheck)(CheckerContext &,
  64. const CallExpr *) const;
  65. void evalMemcpy(CheckerContext &C, const CallExpr *CE) const;
  66. void evalMempcpy(CheckerContext &C, const CallExpr *CE) const;
  67. void evalMemmove(CheckerContext &C, const CallExpr *CE) const;
  68. void evalBcopy(CheckerContext &C, const CallExpr *CE) const;
  69. void evalCopyCommon(CheckerContext &C, const CallExpr *CE,
  70. ProgramStateRef state,
  71. const Expr *Size,
  72. const Expr *Source,
  73. const Expr *Dest,
  74. bool Restricted = false,
  75. bool IsMempcpy = false) const;
  76. void evalMemcmp(CheckerContext &C, const CallExpr *CE) const;
  77. void evalstrLength(CheckerContext &C, const CallExpr *CE) const;
  78. void evalstrnLength(CheckerContext &C, const CallExpr *CE) const;
  79. void evalstrLengthCommon(CheckerContext &C,
  80. const CallExpr *CE,
  81. bool IsStrnlen = false) const;
  82. void evalStrcpy(CheckerContext &C, const CallExpr *CE) const;
  83. void evalStrncpy(CheckerContext &C, const CallExpr *CE) const;
  84. void evalStpcpy(CheckerContext &C, const CallExpr *CE) const;
  85. void evalStrcpyCommon(CheckerContext &C,
  86. const CallExpr *CE,
  87. bool returnEnd,
  88. bool isBounded,
  89. bool isAppending) const;
  90. void evalStrcat(CheckerContext &C, const CallExpr *CE) const;
  91. void evalStrncat(CheckerContext &C, const CallExpr *CE) const;
  92. void evalStrcmp(CheckerContext &C, const CallExpr *CE) const;
  93. void evalStrncmp(CheckerContext &C, const CallExpr *CE) const;
  94. void evalStrcasecmp(CheckerContext &C, const CallExpr *CE) const;
  95. void evalStrncasecmp(CheckerContext &C, const CallExpr *CE) const;
  96. void evalStrcmpCommon(CheckerContext &C,
  97. const CallExpr *CE,
  98. bool isBounded = false,
  99. bool ignoreCase = false) const;
  100. void evalStrsep(CheckerContext &C, const CallExpr *CE) const;
  101. void evalStdCopy(CheckerContext &C, const CallExpr *CE) const;
  102. void evalStdCopyBackward(CheckerContext &C, const CallExpr *CE) const;
  103. void evalStdCopyCommon(CheckerContext &C, const CallExpr *CE) const;
  104. void evalMemset(CheckerContext &C, const CallExpr *CE) const;
  105. // Utility methods
  106. std::pair<ProgramStateRef , ProgramStateRef >
  107. static assumeZero(CheckerContext &C,
  108. ProgramStateRef state, SVal V, QualType Ty);
  109. static ProgramStateRef setCStringLength(ProgramStateRef state,
  110. const MemRegion *MR,
  111. SVal strLength);
  112. static SVal getCStringLengthForRegion(CheckerContext &C,
  113. ProgramStateRef &state,
  114. const Expr *Ex,
  115. const MemRegion *MR,
  116. bool hypothetical);
  117. SVal getCStringLength(CheckerContext &C,
  118. ProgramStateRef &state,
  119. const Expr *Ex,
  120. SVal Buf,
  121. bool hypothetical = false) const;
  122. const StringLiteral *getCStringLiteral(CheckerContext &C,
  123. ProgramStateRef &state,
  124. const Expr *expr,
  125. SVal val) const;
  126. static ProgramStateRef InvalidateBuffer(CheckerContext &C,
  127. ProgramStateRef state,
  128. const Expr *Ex, SVal V,
  129. bool IsSourceBuffer,
  130. const Expr *Size);
  131. static bool SummarizeRegion(raw_ostream &os, ASTContext &Ctx,
  132. const MemRegion *MR);
  133. // Re-usable checks
  134. ProgramStateRef checkNonNull(CheckerContext &C,
  135. ProgramStateRef state,
  136. const Expr *S,
  137. SVal l) const;
  138. ProgramStateRef CheckLocation(CheckerContext &C,
  139. ProgramStateRef state,
  140. const Expr *S,
  141. SVal l,
  142. const char *message = nullptr) const;
  143. ProgramStateRef CheckBufferAccess(CheckerContext &C,
  144. ProgramStateRef state,
  145. const Expr *Size,
  146. const Expr *FirstBuf,
  147. const Expr *SecondBuf,
  148. const char *firstMessage = nullptr,
  149. const char *secondMessage = nullptr,
  150. bool WarnAboutSize = false) const;
  151. ProgramStateRef CheckBufferAccess(CheckerContext &C,
  152. ProgramStateRef state,
  153. const Expr *Size,
  154. const Expr *Buf,
  155. const char *message = nullptr,
  156. bool WarnAboutSize = false) const {
  157. // This is a convenience override.
  158. return CheckBufferAccess(C, state, Size, Buf, nullptr, message, nullptr,
  159. WarnAboutSize);
  160. }
  161. ProgramStateRef CheckOverlap(CheckerContext &C,
  162. ProgramStateRef state,
  163. const Expr *Size,
  164. const Expr *First,
  165. const Expr *Second) const;
  166. void emitOverlapBug(CheckerContext &C,
  167. ProgramStateRef state,
  168. const Stmt *First,
  169. const Stmt *Second) const;
  170. ProgramStateRef checkAdditionOverflow(CheckerContext &C,
  171. ProgramStateRef state,
  172. NonLoc left,
  173. NonLoc right) const;
  174. // Return true if the destination buffer of the copy function may be in bound.
  175. // Expects SVal of Size to be positive and unsigned.
  176. // Expects SVal of FirstBuf to be a FieldRegion.
  177. static bool IsFirstBufInBound(CheckerContext &C,
  178. ProgramStateRef state,
  179. const Expr *FirstBuf,
  180. const Expr *Size);
  181. };
  182. } //end anonymous namespace
  183. REGISTER_MAP_WITH_PROGRAMSTATE(CStringLength, const MemRegion *, SVal)
  184. //===----------------------------------------------------------------------===//
  185. // Individual checks and utility methods.
  186. //===----------------------------------------------------------------------===//
  187. std::pair<ProgramStateRef , ProgramStateRef >
  188. CStringChecker::assumeZero(CheckerContext &C, ProgramStateRef state, SVal V,
  189. QualType Ty) {
  190. Optional<DefinedSVal> val = V.getAs<DefinedSVal>();
  191. if (!val)
  192. return std::pair<ProgramStateRef , ProgramStateRef >(state, state);
  193. SValBuilder &svalBuilder = C.getSValBuilder();
  194. DefinedOrUnknownSVal zero = svalBuilder.makeZeroVal(Ty);
  195. return state->assume(svalBuilder.evalEQ(state, *val, zero));
  196. }
  197. ProgramStateRef CStringChecker::checkNonNull(CheckerContext &C,
  198. ProgramStateRef state,
  199. const Expr *S, SVal l) const {
  200. // If a previous check has failed, propagate the failure.
  201. if (!state)
  202. return nullptr;
  203. ProgramStateRef stateNull, stateNonNull;
  204. std::tie(stateNull, stateNonNull) = assumeZero(C, state, l, S->getType());
  205. if (stateNull && !stateNonNull) {
  206. if (!Filter.CheckCStringNullArg)
  207. return nullptr;
  208. ExplodedNode *N = C.generateErrorNode(stateNull);
  209. if (!N)
  210. return nullptr;
  211. if (!BT_Null)
  212. BT_Null.reset(new BuiltinBug(
  213. Filter.CheckNameCStringNullArg, categories::UnixAPI,
  214. "Null pointer argument in call to byte string function"));
  215. SmallString<80> buf;
  216. llvm::raw_svector_ostream os(buf);
  217. assert(CurrentFunctionDescription);
  218. os << "Null pointer argument in call to " << CurrentFunctionDescription;
  219. // Generate a report for this bug.
  220. BuiltinBug *BT = static_cast<BuiltinBug*>(BT_Null.get());
  221. auto report = llvm::make_unique<BugReport>(*BT, os.str(), N);
  222. report->addRange(S->getSourceRange());
  223. bugreporter::trackNullOrUndefValue(N, S, *report);
  224. C.emitReport(std::move(report));
  225. return nullptr;
  226. }
  227. // From here on, assume that the value is non-null.
  228. assert(stateNonNull);
  229. return stateNonNull;
  230. }
  231. // FIXME: This was originally copied from ArrayBoundChecker.cpp. Refactor?
  232. ProgramStateRef CStringChecker::CheckLocation(CheckerContext &C,
  233. ProgramStateRef state,
  234. const Expr *S, SVal l,
  235. const char *warningMsg) const {
  236. // If a previous check has failed, propagate the failure.
  237. if (!state)
  238. return nullptr;
  239. // Check for out of bound array element access.
  240. const MemRegion *R = l.getAsRegion();
  241. if (!R)
  242. return state;
  243. const ElementRegion *ER = dyn_cast<ElementRegion>(R);
  244. if (!ER)
  245. return state;
  246. if (ER->getValueType() != C.getASTContext().CharTy)
  247. return state;
  248. // Get the size of the array.
  249. const SubRegion *superReg = cast<SubRegion>(ER->getSuperRegion());
  250. SValBuilder &svalBuilder = C.getSValBuilder();
  251. SVal Extent =
  252. svalBuilder.convertToArrayIndex(superReg->getExtent(svalBuilder));
  253. DefinedOrUnknownSVal Size = Extent.castAs<DefinedOrUnknownSVal>();
  254. // Get the index of the accessed element.
  255. DefinedOrUnknownSVal Idx = ER->getIndex().castAs<DefinedOrUnknownSVal>();
  256. ProgramStateRef StInBound = state->assumeInBound(Idx, Size, true);
  257. ProgramStateRef StOutBound = state->assumeInBound(Idx, Size, false);
  258. if (StOutBound && !StInBound) {
  259. ExplodedNode *N = C.generateErrorNode(StOutBound);
  260. if (!N)
  261. return nullptr;
  262. if (!BT_Bounds) {
  263. BT_Bounds.reset(new BuiltinBug(
  264. Filter.CheckNameCStringOutOfBounds, "Out-of-bound array access",
  265. "Byte string function accesses out-of-bound array element"));
  266. }
  267. BuiltinBug *BT = static_cast<BuiltinBug*>(BT_Bounds.get());
  268. // Generate a report for this bug.
  269. std::unique_ptr<BugReport> report;
  270. if (warningMsg) {
  271. report = llvm::make_unique<BugReport>(*BT, warningMsg, N);
  272. } else {
  273. assert(CurrentFunctionDescription);
  274. assert(CurrentFunctionDescription[0] != '\0');
  275. SmallString<80> buf;
  276. llvm::raw_svector_ostream os(buf);
  277. os << toUppercase(CurrentFunctionDescription[0])
  278. << &CurrentFunctionDescription[1]
  279. << " accesses out-of-bound array element";
  280. report = llvm::make_unique<BugReport>(*BT, os.str(), N);
  281. }
  282. // FIXME: It would be nice to eventually make this diagnostic more clear,
  283. // e.g., by referencing the original declaration or by saying *why* this
  284. // reference is outside the range.
  285. report->addRange(S->getSourceRange());
  286. C.emitReport(std::move(report));
  287. return nullptr;
  288. }
  289. // Array bound check succeeded. From this point forward the array bound
  290. // should always succeed.
  291. return StInBound;
  292. }
  293. ProgramStateRef CStringChecker::CheckBufferAccess(CheckerContext &C,
  294. ProgramStateRef state,
  295. const Expr *Size,
  296. const Expr *FirstBuf,
  297. const Expr *SecondBuf,
  298. const char *firstMessage,
  299. const char *secondMessage,
  300. bool WarnAboutSize) const {
  301. // If a previous check has failed, propagate the failure.
  302. if (!state)
  303. return nullptr;
  304. SValBuilder &svalBuilder = C.getSValBuilder();
  305. ASTContext &Ctx = svalBuilder.getContext();
  306. const LocationContext *LCtx = C.getLocationContext();
  307. QualType sizeTy = Size->getType();
  308. QualType PtrTy = Ctx.getPointerType(Ctx.CharTy);
  309. // Check that the first buffer is non-null.
  310. SVal BufVal = C.getSVal(FirstBuf);
  311. state = checkNonNull(C, state, FirstBuf, BufVal);
  312. if (!state)
  313. return nullptr;
  314. // If out-of-bounds checking is turned off, skip the rest.
  315. if (!Filter.CheckCStringOutOfBounds)
  316. return state;
  317. // Get the access length and make sure it is known.
  318. // FIXME: This assumes the caller has already checked that the access length
  319. // is positive. And that it's unsigned.
  320. SVal LengthVal = C.getSVal(Size);
  321. Optional<NonLoc> Length = LengthVal.getAs<NonLoc>();
  322. if (!Length)
  323. return state;
  324. // Compute the offset of the last element to be accessed: size-1.
  325. NonLoc One = svalBuilder.makeIntVal(1, sizeTy).castAs<NonLoc>();
  326. NonLoc LastOffset = svalBuilder
  327. .evalBinOpNN(state, BO_Sub, *Length, One, sizeTy).castAs<NonLoc>();
  328. // Check that the first buffer is sufficiently long.
  329. SVal BufStart = svalBuilder.evalCast(BufVal, PtrTy, FirstBuf->getType());
  330. if (Optional<Loc> BufLoc = BufStart.getAs<Loc>()) {
  331. const Expr *warningExpr = (WarnAboutSize ? Size : FirstBuf);
  332. SVal BufEnd = svalBuilder.evalBinOpLN(state, BO_Add, *BufLoc,
  333. LastOffset, PtrTy);
  334. state = CheckLocation(C, state, warningExpr, BufEnd, firstMessage);
  335. // If the buffer isn't large enough, abort.
  336. if (!state)
  337. return nullptr;
  338. }
  339. // If there's a second buffer, check it as well.
  340. if (SecondBuf) {
  341. BufVal = state->getSVal(SecondBuf, LCtx);
  342. state = checkNonNull(C, state, SecondBuf, BufVal);
  343. if (!state)
  344. return nullptr;
  345. BufStart = svalBuilder.evalCast(BufVal, PtrTy, SecondBuf->getType());
  346. if (Optional<Loc> BufLoc = BufStart.getAs<Loc>()) {
  347. const Expr *warningExpr = (WarnAboutSize ? Size : SecondBuf);
  348. SVal BufEnd = svalBuilder.evalBinOpLN(state, BO_Add, *BufLoc,
  349. LastOffset, PtrTy);
  350. state = CheckLocation(C, state, warningExpr, BufEnd, secondMessage);
  351. }
  352. }
  353. // Large enough or not, return this state!
  354. return state;
  355. }
  356. ProgramStateRef CStringChecker::CheckOverlap(CheckerContext &C,
  357. ProgramStateRef state,
  358. const Expr *Size,
  359. const Expr *First,
  360. const Expr *Second) const {
  361. if (!Filter.CheckCStringBufferOverlap)
  362. return state;
  363. // Do a simple check for overlap: if the two arguments are from the same
  364. // buffer, see if the end of the first is greater than the start of the second
  365. // or vice versa.
  366. // If a previous check has failed, propagate the failure.
  367. if (!state)
  368. return nullptr;
  369. ProgramStateRef stateTrue, stateFalse;
  370. // Get the buffer values and make sure they're known locations.
  371. const LocationContext *LCtx = C.getLocationContext();
  372. SVal firstVal = state->getSVal(First, LCtx);
  373. SVal secondVal = state->getSVal(Second, LCtx);
  374. Optional<Loc> firstLoc = firstVal.getAs<Loc>();
  375. if (!firstLoc)
  376. return state;
  377. Optional<Loc> secondLoc = secondVal.getAs<Loc>();
  378. if (!secondLoc)
  379. return state;
  380. // Are the two values the same?
  381. SValBuilder &svalBuilder = C.getSValBuilder();
  382. std::tie(stateTrue, stateFalse) =
  383. state->assume(svalBuilder.evalEQ(state, *firstLoc, *secondLoc));
  384. if (stateTrue && !stateFalse) {
  385. // If the values are known to be equal, that's automatically an overlap.
  386. emitOverlapBug(C, stateTrue, First, Second);
  387. return nullptr;
  388. }
  389. // assume the two expressions are not equal.
  390. assert(stateFalse);
  391. state = stateFalse;
  392. // Which value comes first?
  393. QualType cmpTy = svalBuilder.getConditionType();
  394. SVal reverse = svalBuilder.evalBinOpLL(state, BO_GT,
  395. *firstLoc, *secondLoc, cmpTy);
  396. Optional<DefinedOrUnknownSVal> reverseTest =
  397. reverse.getAs<DefinedOrUnknownSVal>();
  398. if (!reverseTest)
  399. return state;
  400. std::tie(stateTrue, stateFalse) = state->assume(*reverseTest);
  401. if (stateTrue) {
  402. if (stateFalse) {
  403. // If we don't know which one comes first, we can't perform this test.
  404. return state;
  405. } else {
  406. // Switch the values so that firstVal is before secondVal.
  407. std::swap(firstLoc, secondLoc);
  408. // Switch the Exprs as well, so that they still correspond.
  409. std::swap(First, Second);
  410. }
  411. }
  412. // Get the length, and make sure it too is known.
  413. SVal LengthVal = state->getSVal(Size, LCtx);
  414. Optional<NonLoc> Length = LengthVal.getAs<NonLoc>();
  415. if (!Length)
  416. return state;
  417. // Convert the first buffer's start address to char*.
  418. // Bail out if the cast fails.
  419. ASTContext &Ctx = svalBuilder.getContext();
  420. QualType CharPtrTy = Ctx.getPointerType(Ctx.CharTy);
  421. SVal FirstStart = svalBuilder.evalCast(*firstLoc, CharPtrTy,
  422. First->getType());
  423. Optional<Loc> FirstStartLoc = FirstStart.getAs<Loc>();
  424. if (!FirstStartLoc)
  425. return state;
  426. // Compute the end of the first buffer. Bail out if THAT fails.
  427. SVal FirstEnd = svalBuilder.evalBinOpLN(state, BO_Add,
  428. *FirstStartLoc, *Length, CharPtrTy);
  429. Optional<Loc> FirstEndLoc = FirstEnd.getAs<Loc>();
  430. if (!FirstEndLoc)
  431. return state;
  432. // Is the end of the first buffer past the start of the second buffer?
  433. SVal Overlap = svalBuilder.evalBinOpLL(state, BO_GT,
  434. *FirstEndLoc, *secondLoc, cmpTy);
  435. Optional<DefinedOrUnknownSVal> OverlapTest =
  436. Overlap.getAs<DefinedOrUnknownSVal>();
  437. if (!OverlapTest)
  438. return state;
  439. std::tie(stateTrue, stateFalse) = state->assume(*OverlapTest);
  440. if (stateTrue && !stateFalse) {
  441. // Overlap!
  442. emitOverlapBug(C, stateTrue, First, Second);
  443. return nullptr;
  444. }
  445. // assume the two expressions don't overlap.
  446. assert(stateFalse);
  447. return stateFalse;
  448. }
  449. void CStringChecker::emitOverlapBug(CheckerContext &C, ProgramStateRef state,
  450. const Stmt *First, const Stmt *Second) const {
  451. ExplodedNode *N = C.generateErrorNode(state);
  452. if (!N)
  453. return;
  454. if (!BT_Overlap)
  455. BT_Overlap.reset(new BugType(Filter.CheckNameCStringBufferOverlap,
  456. categories::UnixAPI, "Improper arguments"));
  457. // Generate a report for this bug.
  458. auto report = llvm::make_unique<BugReport>(
  459. *BT_Overlap, "Arguments must not be overlapping buffers", N);
  460. report->addRange(First->getSourceRange());
  461. report->addRange(Second->getSourceRange());
  462. C.emitReport(std::move(report));
  463. }
  464. ProgramStateRef CStringChecker::checkAdditionOverflow(CheckerContext &C,
  465. ProgramStateRef state,
  466. NonLoc left,
  467. NonLoc right) const {
  468. // If out-of-bounds checking is turned off, skip the rest.
  469. if (!Filter.CheckCStringOutOfBounds)
  470. return state;
  471. // If a previous check has failed, propagate the failure.
  472. if (!state)
  473. return nullptr;
  474. SValBuilder &svalBuilder = C.getSValBuilder();
  475. BasicValueFactory &BVF = svalBuilder.getBasicValueFactory();
  476. QualType sizeTy = svalBuilder.getContext().getSizeType();
  477. const llvm::APSInt &maxValInt = BVF.getMaxValue(sizeTy);
  478. NonLoc maxVal = svalBuilder.makeIntVal(maxValInt);
  479. SVal maxMinusRight;
  480. if (right.getAs<nonloc::ConcreteInt>()) {
  481. maxMinusRight = svalBuilder.evalBinOpNN(state, BO_Sub, maxVal, right,
  482. sizeTy);
  483. } else {
  484. // Try switching the operands. (The order of these two assignments is
  485. // important!)
  486. maxMinusRight = svalBuilder.evalBinOpNN(state, BO_Sub, maxVal, left,
  487. sizeTy);
  488. left = right;
  489. }
  490. if (Optional<NonLoc> maxMinusRightNL = maxMinusRight.getAs<NonLoc>()) {
  491. QualType cmpTy = svalBuilder.getConditionType();
  492. // If left > max - right, we have an overflow.
  493. SVal willOverflow = svalBuilder.evalBinOpNN(state, BO_GT, left,
  494. *maxMinusRightNL, cmpTy);
  495. ProgramStateRef stateOverflow, stateOkay;
  496. std::tie(stateOverflow, stateOkay) =
  497. state->assume(willOverflow.castAs<DefinedOrUnknownSVal>());
  498. if (stateOverflow && !stateOkay) {
  499. // We have an overflow. Emit a bug report.
  500. ExplodedNode *N = C.generateErrorNode(stateOverflow);
  501. if (!N)
  502. return nullptr;
  503. if (!BT_AdditionOverflow)
  504. BT_AdditionOverflow.reset(
  505. new BuiltinBug(Filter.CheckNameCStringOutOfBounds, "API",
  506. "Sum of expressions causes overflow"));
  507. // This isn't a great error message, but this should never occur in real
  508. // code anyway -- you'd have to create a buffer longer than a size_t can
  509. // represent, which is sort of a contradiction.
  510. const char *warning =
  511. "This expression will create a string whose length is too big to "
  512. "be represented as a size_t";
  513. // Generate a report for this bug.
  514. C.emitReport(
  515. llvm::make_unique<BugReport>(*BT_AdditionOverflow, warning, N));
  516. return nullptr;
  517. }
  518. // From now on, assume an overflow didn't occur.
  519. assert(stateOkay);
  520. state = stateOkay;
  521. }
  522. return state;
  523. }
  524. ProgramStateRef CStringChecker::setCStringLength(ProgramStateRef state,
  525. const MemRegion *MR,
  526. SVal strLength) {
  527. assert(!strLength.isUndef() && "Attempt to set an undefined string length");
  528. MR = MR->StripCasts();
  529. switch (MR->getKind()) {
  530. case MemRegion::StringRegionKind:
  531. // FIXME: This can happen if we strcpy() into a string region. This is
  532. // undefined [C99 6.4.5p6], but we should still warn about it.
  533. return state;
  534. case MemRegion::SymbolicRegionKind:
  535. case MemRegion::AllocaRegionKind:
  536. case MemRegion::VarRegionKind:
  537. case MemRegion::FieldRegionKind:
  538. case MemRegion::ObjCIvarRegionKind:
  539. // These are the types we can currently track string lengths for.
  540. break;
  541. case MemRegion::ElementRegionKind:
  542. // FIXME: Handle element regions by upper-bounding the parent region's
  543. // string length.
  544. return state;
  545. default:
  546. // Other regions (mostly non-data) can't have a reliable C string length.
  547. // For now, just ignore the change.
  548. // FIXME: These are rare but not impossible. We should output some kind of
  549. // warning for things like strcpy((char[]){'a', 0}, "b");
  550. return state;
  551. }
  552. if (strLength.isUnknown())
  553. return state->remove<CStringLength>(MR);
  554. return state->set<CStringLength>(MR, strLength);
  555. }
  556. SVal CStringChecker::getCStringLengthForRegion(CheckerContext &C,
  557. ProgramStateRef &state,
  558. const Expr *Ex,
  559. const MemRegion *MR,
  560. bool hypothetical) {
  561. if (!hypothetical) {
  562. // If there's a recorded length, go ahead and return it.
  563. const SVal *Recorded = state->get<CStringLength>(MR);
  564. if (Recorded)
  565. return *Recorded;
  566. }
  567. // Otherwise, get a new symbol and update the state.
  568. SValBuilder &svalBuilder = C.getSValBuilder();
  569. QualType sizeTy = svalBuilder.getContext().getSizeType();
  570. SVal strLength = svalBuilder.getMetadataSymbolVal(CStringChecker::getTag(),
  571. MR, Ex, sizeTy,
  572. C.getLocationContext(),
  573. C.blockCount());
  574. if (!hypothetical) {
  575. if (Optional<NonLoc> strLn = strLength.getAs<NonLoc>()) {
  576. // In case of unbounded calls strlen etc bound the range to SIZE_MAX/4
  577. BasicValueFactory &BVF = svalBuilder.getBasicValueFactory();
  578. const llvm::APSInt &maxValInt = BVF.getMaxValue(sizeTy);
  579. llvm::APSInt fourInt = APSIntType(maxValInt).getValue(4);
  580. const llvm::APSInt *maxLengthInt = BVF.evalAPSInt(BO_Div, maxValInt,
  581. fourInt);
  582. NonLoc maxLength = svalBuilder.makeIntVal(*maxLengthInt);
  583. SVal evalLength = svalBuilder.evalBinOpNN(state, BO_LE, *strLn,
  584. maxLength, sizeTy);
  585. state = state->assume(evalLength.castAs<DefinedOrUnknownSVal>(), true);
  586. }
  587. state = state->set<CStringLength>(MR, strLength);
  588. }
  589. return strLength;
  590. }
  591. SVal CStringChecker::getCStringLength(CheckerContext &C, ProgramStateRef &state,
  592. const Expr *Ex, SVal Buf,
  593. bool hypothetical) const {
  594. const MemRegion *MR = Buf.getAsRegion();
  595. if (!MR) {
  596. // If we can't get a region, see if it's something we /know/ isn't a
  597. // C string. In the context of locations, the only time we can issue such
  598. // a warning is for labels.
  599. if (Optional<loc::GotoLabel> Label = Buf.getAs<loc::GotoLabel>()) {
  600. if (!Filter.CheckCStringNotNullTerm)
  601. return UndefinedVal();
  602. if (ExplodedNode *N = C.generateNonFatalErrorNode(state)) {
  603. if (!BT_NotCString)
  604. BT_NotCString.reset(new BuiltinBug(
  605. Filter.CheckNameCStringNotNullTerm, categories::UnixAPI,
  606. "Argument is not a null-terminated string."));
  607. SmallString<120> buf;
  608. llvm::raw_svector_ostream os(buf);
  609. assert(CurrentFunctionDescription);
  610. os << "Argument to " << CurrentFunctionDescription
  611. << " is the address of the label '" << Label->getLabel()->getName()
  612. << "', which is not a null-terminated string";
  613. // Generate a report for this bug.
  614. auto report = llvm::make_unique<BugReport>(*BT_NotCString, os.str(), N);
  615. report->addRange(Ex->getSourceRange());
  616. C.emitReport(std::move(report));
  617. }
  618. return UndefinedVal();
  619. }
  620. // If it's not a region and not a label, give up.
  621. return UnknownVal();
  622. }
  623. // If we have a region, strip casts from it and see if we can figure out
  624. // its length. For anything we can't figure out, just return UnknownVal.
  625. MR = MR->StripCasts();
  626. switch (MR->getKind()) {
  627. case MemRegion::StringRegionKind: {
  628. // Modifying the contents of string regions is undefined [C99 6.4.5p6],
  629. // so we can assume that the byte length is the correct C string length.
  630. SValBuilder &svalBuilder = C.getSValBuilder();
  631. QualType sizeTy = svalBuilder.getContext().getSizeType();
  632. const StringLiteral *strLit = cast<StringRegion>(MR)->getStringLiteral();
  633. return svalBuilder.makeIntVal(strLit->getByteLength(), sizeTy);
  634. }
  635. case MemRegion::SymbolicRegionKind:
  636. case MemRegion::AllocaRegionKind:
  637. case MemRegion::VarRegionKind:
  638. case MemRegion::FieldRegionKind:
  639. case MemRegion::ObjCIvarRegionKind:
  640. return getCStringLengthForRegion(C, state, Ex, MR, hypothetical);
  641. case MemRegion::CompoundLiteralRegionKind:
  642. // FIXME: Can we track this? Is it necessary?
  643. return UnknownVal();
  644. case MemRegion::ElementRegionKind:
  645. // FIXME: How can we handle this? It's not good enough to subtract the
  646. // offset from the base string length; consider "123\x00567" and &a[5].
  647. return UnknownVal();
  648. default:
  649. // Other regions (mostly non-data) can't have a reliable C string length.
  650. // In this case, an error is emitted and UndefinedVal is returned.
  651. // The caller should always be prepared to handle this case.
  652. if (!Filter.CheckCStringNotNullTerm)
  653. return UndefinedVal();
  654. if (ExplodedNode *N = C.generateNonFatalErrorNode(state)) {
  655. if (!BT_NotCString)
  656. BT_NotCString.reset(new BuiltinBug(
  657. Filter.CheckNameCStringNotNullTerm, categories::UnixAPI,
  658. "Argument is not a null-terminated string."));
  659. SmallString<120> buf;
  660. llvm::raw_svector_ostream os(buf);
  661. assert(CurrentFunctionDescription);
  662. os << "Argument to " << CurrentFunctionDescription << " is ";
  663. if (SummarizeRegion(os, C.getASTContext(), MR))
  664. os << ", which is not a null-terminated string";
  665. else
  666. os << "not a null-terminated string";
  667. // Generate a report for this bug.
  668. auto report = llvm::make_unique<BugReport>(*BT_NotCString, os.str(), N);
  669. report->addRange(Ex->getSourceRange());
  670. C.emitReport(std::move(report));
  671. }
  672. return UndefinedVal();
  673. }
  674. }
  675. const StringLiteral *CStringChecker::getCStringLiteral(CheckerContext &C,
  676. ProgramStateRef &state, const Expr *expr, SVal val) const {
  677. // Get the memory region pointed to by the val.
  678. const MemRegion *bufRegion = val.getAsRegion();
  679. if (!bufRegion)
  680. return nullptr;
  681. // Strip casts off the memory region.
  682. bufRegion = bufRegion->StripCasts();
  683. // Cast the memory region to a string region.
  684. const StringRegion *strRegion= dyn_cast<StringRegion>(bufRegion);
  685. if (!strRegion)
  686. return nullptr;
  687. // Return the actual string in the string region.
  688. return strRegion->getStringLiteral();
  689. }
  690. bool CStringChecker::IsFirstBufInBound(CheckerContext &C,
  691. ProgramStateRef state,
  692. const Expr *FirstBuf,
  693. const Expr *Size) {
  694. // If we do not know that the buffer is long enough we return 'true'.
  695. // Otherwise the parent region of this field region would also get
  696. // invalidated, which would lead to warnings based on an unknown state.
  697. // Originally copied from CheckBufferAccess and CheckLocation.
  698. SValBuilder &svalBuilder = C.getSValBuilder();
  699. ASTContext &Ctx = svalBuilder.getContext();
  700. const LocationContext *LCtx = C.getLocationContext();
  701. QualType sizeTy = Size->getType();
  702. QualType PtrTy = Ctx.getPointerType(Ctx.CharTy);
  703. SVal BufVal = state->getSVal(FirstBuf, LCtx);
  704. SVal LengthVal = state->getSVal(Size, LCtx);
  705. Optional<NonLoc> Length = LengthVal.getAs<NonLoc>();
  706. if (!Length)
  707. return true; // cf top comment.
  708. // Compute the offset of the last element to be accessed: size-1.
  709. NonLoc One = svalBuilder.makeIntVal(1, sizeTy).castAs<NonLoc>();
  710. NonLoc LastOffset =
  711. svalBuilder.evalBinOpNN(state, BO_Sub, *Length, One, sizeTy)
  712. .castAs<NonLoc>();
  713. // Check that the first buffer is sufficiently long.
  714. SVal BufStart = svalBuilder.evalCast(BufVal, PtrTy, FirstBuf->getType());
  715. Optional<Loc> BufLoc = BufStart.getAs<Loc>();
  716. if (!BufLoc)
  717. return true; // cf top comment.
  718. SVal BufEnd =
  719. svalBuilder.evalBinOpLN(state, BO_Add, *BufLoc, LastOffset, PtrTy);
  720. // Check for out of bound array element access.
  721. const MemRegion *R = BufEnd.getAsRegion();
  722. if (!R)
  723. return true; // cf top comment.
  724. const ElementRegion *ER = dyn_cast<ElementRegion>(R);
  725. if (!ER)
  726. return true; // cf top comment.
  727. // FIXME: Does this crash when a non-standard definition
  728. // of a library function is encountered?
  729. assert(ER->getValueType() == C.getASTContext().CharTy &&
  730. "IsFirstBufInBound should only be called with char* ElementRegions");
  731. // Get the size of the array.
  732. const SubRegion *superReg = cast<SubRegion>(ER->getSuperRegion());
  733. SVal Extent =
  734. svalBuilder.convertToArrayIndex(superReg->getExtent(svalBuilder));
  735. DefinedOrUnknownSVal ExtentSize = Extent.castAs<DefinedOrUnknownSVal>();
  736. // Get the index of the accessed element.
  737. DefinedOrUnknownSVal Idx = ER->getIndex().castAs<DefinedOrUnknownSVal>();
  738. ProgramStateRef StInBound = state->assumeInBound(Idx, ExtentSize, true);
  739. return static_cast<bool>(StInBound);
  740. }
  741. ProgramStateRef CStringChecker::InvalidateBuffer(CheckerContext &C,
  742. ProgramStateRef state,
  743. const Expr *E, SVal V,
  744. bool IsSourceBuffer,
  745. const Expr *Size) {
  746. Optional<Loc> L = V.getAs<Loc>();
  747. if (!L)
  748. return state;
  749. // FIXME: This is a simplified version of what's in CFRefCount.cpp -- it makes
  750. // some assumptions about the value that CFRefCount can't. Even so, it should
  751. // probably be refactored.
  752. if (Optional<loc::MemRegionVal> MR = L->getAs<loc::MemRegionVal>()) {
  753. const MemRegion *R = MR->getRegion()->StripCasts();
  754. // Are we dealing with an ElementRegion? If so, we should be invalidating
  755. // the super-region.
  756. if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
  757. R = ER->getSuperRegion();
  758. // FIXME: What about layers of ElementRegions?
  759. }
  760. // Invalidate this region.
  761. const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
  762. bool CausesPointerEscape = false;
  763. RegionAndSymbolInvalidationTraits ITraits;
  764. // Invalidate and escape only indirect regions accessible through the source
  765. // buffer.
  766. if (IsSourceBuffer) {
  767. ITraits.setTrait(R->getBaseRegion(),
  768. RegionAndSymbolInvalidationTraits::TK_PreserveContents);
  769. ITraits.setTrait(R, RegionAndSymbolInvalidationTraits::TK_SuppressEscape);
  770. CausesPointerEscape = true;
  771. } else {
  772. const MemRegion::Kind& K = R->getKind();
  773. if (K == MemRegion::FieldRegionKind)
  774. if (Size && IsFirstBufInBound(C, state, E, Size)) {
  775. // If destination buffer is a field region and access is in bound,
  776. // do not invalidate its super region.
  777. ITraits.setTrait(
  778. R,
  779. RegionAndSymbolInvalidationTraits::TK_DoNotInvalidateSuperRegion);
  780. }
  781. }
  782. return state->invalidateRegions(R, E, C.blockCount(), LCtx,
  783. CausesPointerEscape, nullptr, nullptr,
  784. &ITraits);
  785. }
  786. // If we have a non-region value by chance, just remove the binding.
  787. // FIXME: is this necessary or correct? This handles the non-Region
  788. // cases. Is it ever valid to store to these?
  789. return state->killBinding(*L);
  790. }
  791. bool CStringChecker::SummarizeRegion(raw_ostream &os, ASTContext &Ctx,
  792. const MemRegion *MR) {
  793. const TypedValueRegion *TVR = dyn_cast<TypedValueRegion>(MR);
  794. switch (MR->getKind()) {
  795. case MemRegion::FunctionCodeRegionKind: {
  796. const NamedDecl *FD = cast<FunctionCodeRegion>(MR)->getDecl();
  797. if (FD)
  798. os << "the address of the function '" << *FD << '\'';
  799. else
  800. os << "the address of a function";
  801. return true;
  802. }
  803. case MemRegion::BlockCodeRegionKind:
  804. os << "block text";
  805. return true;
  806. case MemRegion::BlockDataRegionKind:
  807. os << "a block";
  808. return true;
  809. case MemRegion::CXXThisRegionKind:
  810. case MemRegion::CXXTempObjectRegionKind:
  811. os << "a C++ temp object of type " << TVR->getValueType().getAsString();
  812. return true;
  813. case MemRegion::VarRegionKind:
  814. os << "a variable of type" << TVR->getValueType().getAsString();
  815. return true;
  816. case MemRegion::FieldRegionKind:
  817. os << "a field of type " << TVR->getValueType().getAsString();
  818. return true;
  819. case MemRegion::ObjCIvarRegionKind:
  820. os << "an instance variable of type " << TVR->getValueType().getAsString();
  821. return true;
  822. default:
  823. return false;
  824. }
  825. }
  826. //===----------------------------------------------------------------------===//
  827. // evaluation of individual function calls.
  828. //===----------------------------------------------------------------------===//
  829. void CStringChecker::evalCopyCommon(CheckerContext &C,
  830. const CallExpr *CE,
  831. ProgramStateRef state,
  832. const Expr *Size, const Expr *Dest,
  833. const Expr *Source, bool Restricted,
  834. bool IsMempcpy) const {
  835. CurrentFunctionDescription = "memory copy function";
  836. // See if the size argument is zero.
  837. const LocationContext *LCtx = C.getLocationContext();
  838. SVal sizeVal = state->getSVal(Size, LCtx);
  839. QualType sizeTy = Size->getType();
  840. ProgramStateRef stateZeroSize, stateNonZeroSize;
  841. std::tie(stateZeroSize, stateNonZeroSize) =
  842. assumeZero(C, state, sizeVal, sizeTy);
  843. // Get the value of the Dest.
  844. SVal destVal = state->getSVal(Dest, LCtx);
  845. // If the size is zero, there won't be any actual memory access, so
  846. // just bind the return value to the destination buffer and return.
  847. if (stateZeroSize && !stateNonZeroSize) {
  848. stateZeroSize = stateZeroSize->BindExpr(CE, LCtx, destVal);
  849. C.addTransition(stateZeroSize);
  850. return;
  851. }
  852. // If the size can be nonzero, we have to check the other arguments.
  853. if (stateNonZeroSize) {
  854. state = stateNonZeroSize;
  855. // Ensure the destination is not null. If it is NULL there will be a
  856. // NULL pointer dereference.
  857. state = checkNonNull(C, state, Dest, destVal);
  858. if (!state)
  859. return;
  860. // Get the value of the Src.
  861. SVal srcVal = state->getSVal(Source, LCtx);
  862. // Ensure the source is not null. If it is NULL there will be a
  863. // NULL pointer dereference.
  864. state = checkNonNull(C, state, Source, srcVal);
  865. if (!state)
  866. return;
  867. // Ensure the accesses are valid and that the buffers do not overlap.
  868. const char * const writeWarning =
  869. "Memory copy function overflows destination buffer";
  870. state = CheckBufferAccess(C, state, Size, Dest, Source,
  871. writeWarning, /* sourceWarning = */ nullptr);
  872. if (Restricted)
  873. state = CheckOverlap(C, state, Size, Dest, Source);
  874. if (!state)
  875. return;
  876. // If this is mempcpy, get the byte after the last byte copied and
  877. // bind the expr.
  878. if (IsMempcpy) {
  879. // Get the byte after the last byte copied.
  880. SValBuilder &SvalBuilder = C.getSValBuilder();
  881. ASTContext &Ctx = SvalBuilder.getContext();
  882. QualType CharPtrTy = Ctx.getPointerType(Ctx.CharTy);
  883. SVal DestRegCharVal =
  884. SvalBuilder.evalCast(destVal, CharPtrTy, Dest->getType());
  885. SVal lastElement = C.getSValBuilder().evalBinOp(
  886. state, BO_Add, DestRegCharVal, sizeVal, Dest->getType());
  887. // If we don't know how much we copied, we can at least
  888. // conjure a return value for later.
  889. if (lastElement.isUnknown())
  890. lastElement = C.getSValBuilder().conjureSymbolVal(nullptr, CE, LCtx,
  891. C.blockCount());
  892. // The byte after the last byte copied is the return value.
  893. state = state->BindExpr(CE, LCtx, lastElement);
  894. } else {
  895. // All other copies return the destination buffer.
  896. // (Well, bcopy() has a void return type, but this won't hurt.)
  897. state = state->BindExpr(CE, LCtx, destVal);
  898. }
  899. // Invalidate the destination (regular invalidation without pointer-escaping
  900. // the address of the top-level region).
  901. // FIXME: Even if we can't perfectly model the copy, we should see if we
  902. // can use LazyCompoundVals to copy the source values into the destination.
  903. // This would probably remove any existing bindings past the end of the
  904. // copied region, but that's still an improvement over blank invalidation.
  905. state = InvalidateBuffer(C, state, Dest, C.getSVal(Dest),
  906. /*IsSourceBuffer*/false, Size);
  907. // Invalidate the source (const-invalidation without const-pointer-escaping
  908. // the address of the top-level region).
  909. state = InvalidateBuffer(C, state, Source, C.getSVal(Source),
  910. /*IsSourceBuffer*/true, nullptr);
  911. C.addTransition(state);
  912. }
  913. }
  914. void CStringChecker::evalMemcpy(CheckerContext &C, const CallExpr *CE) const {
  915. if (CE->getNumArgs() < 3)
  916. return;
  917. // void *memcpy(void *restrict dst, const void *restrict src, size_t n);
  918. // The return value is the address of the destination buffer.
  919. const Expr *Dest = CE->getArg(0);
  920. ProgramStateRef state = C.getState();
  921. evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1), true);
  922. }
  923. void CStringChecker::evalMempcpy(CheckerContext &C, const CallExpr *CE) const {
  924. if (CE->getNumArgs() < 3)
  925. return;
  926. // void *mempcpy(void *restrict dst, const void *restrict src, size_t n);
  927. // The return value is a pointer to the byte following the last written byte.
  928. const Expr *Dest = CE->getArg(0);
  929. ProgramStateRef state = C.getState();
  930. evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1), true, true);
  931. }
  932. void CStringChecker::evalMemmove(CheckerContext &C, const CallExpr *CE) const {
  933. if (CE->getNumArgs() < 3)
  934. return;
  935. // void *memmove(void *dst, const void *src, size_t n);
  936. // The return value is the address of the destination buffer.
  937. const Expr *Dest = CE->getArg(0);
  938. ProgramStateRef state = C.getState();
  939. evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1));
  940. }
  941. void CStringChecker::evalBcopy(CheckerContext &C, const CallExpr *CE) const {
  942. if (CE->getNumArgs() < 3)
  943. return;
  944. // void bcopy(const void *src, void *dst, size_t n);
  945. evalCopyCommon(C, CE, C.getState(),
  946. CE->getArg(2), CE->getArg(1), CE->getArg(0));
  947. }
  948. void CStringChecker::evalMemcmp(CheckerContext &C, const CallExpr *CE) const {
  949. if (CE->getNumArgs() < 3)
  950. return;
  951. // int memcmp(const void *s1, const void *s2, size_t n);
  952. CurrentFunctionDescription = "memory comparison function";
  953. const Expr *Left = CE->getArg(0);
  954. const Expr *Right = CE->getArg(1);
  955. const Expr *Size = CE->getArg(2);
  956. ProgramStateRef state = C.getState();
  957. SValBuilder &svalBuilder = C.getSValBuilder();
  958. // See if the size argument is zero.
  959. const LocationContext *LCtx = C.getLocationContext();
  960. SVal sizeVal = state->getSVal(Size, LCtx);
  961. QualType sizeTy = Size->getType();
  962. ProgramStateRef stateZeroSize, stateNonZeroSize;
  963. std::tie(stateZeroSize, stateNonZeroSize) =
  964. assumeZero(C, state, sizeVal, sizeTy);
  965. // If the size can be zero, the result will be 0 in that case, and we don't
  966. // have to check either of the buffers.
  967. if (stateZeroSize) {
  968. state = stateZeroSize;
  969. state = state->BindExpr(CE, LCtx,
  970. svalBuilder.makeZeroVal(CE->getType()));
  971. C.addTransition(state);
  972. }
  973. // If the size can be nonzero, we have to check the other arguments.
  974. if (stateNonZeroSize) {
  975. state = stateNonZeroSize;
  976. // If we know the two buffers are the same, we know the result is 0.
  977. // First, get the two buffers' addresses. Another checker will have already
  978. // made sure they're not undefined.
  979. DefinedOrUnknownSVal LV =
  980. state->getSVal(Left, LCtx).castAs<DefinedOrUnknownSVal>();
  981. DefinedOrUnknownSVal RV =
  982. state->getSVal(Right, LCtx).castAs<DefinedOrUnknownSVal>();
  983. // See if they are the same.
  984. DefinedOrUnknownSVal SameBuf = svalBuilder.evalEQ(state, LV, RV);
  985. ProgramStateRef StSameBuf, StNotSameBuf;
  986. std::tie(StSameBuf, StNotSameBuf) = state->assume(SameBuf);
  987. // If the two arguments might be the same buffer, we know the result is 0,
  988. // and we only need to check one size.
  989. if (StSameBuf) {
  990. state = StSameBuf;
  991. state = CheckBufferAccess(C, state, Size, Left);
  992. if (state) {
  993. state = StSameBuf->BindExpr(CE, LCtx,
  994. svalBuilder.makeZeroVal(CE->getType()));
  995. C.addTransition(state);
  996. }
  997. }
  998. // If the two arguments might be different buffers, we have to check the
  999. // size of both of them.
  1000. if (StNotSameBuf) {
  1001. state = StNotSameBuf;
  1002. state = CheckBufferAccess(C, state, Size, Left, Right);
  1003. if (state) {
  1004. // The return value is the comparison result, which we don't know.
  1005. SVal CmpV = svalBuilder.conjureSymbolVal(nullptr, CE, LCtx,
  1006. C.blockCount());
  1007. state = state->BindExpr(CE, LCtx, CmpV);
  1008. C.addTransition(state);
  1009. }
  1010. }
  1011. }
  1012. }
  1013. void CStringChecker::evalstrLength(CheckerContext &C,
  1014. const CallExpr *CE) const {
  1015. if (CE->getNumArgs() < 1)
  1016. return;
  1017. // size_t strlen(const char *s);
  1018. evalstrLengthCommon(C, CE, /* IsStrnlen = */ false);
  1019. }
  1020. void CStringChecker::evalstrnLength(CheckerContext &C,
  1021. const CallExpr *CE) const {
  1022. if (CE->getNumArgs() < 2)
  1023. return;
  1024. // size_t strnlen(const char *s, size_t maxlen);
  1025. evalstrLengthCommon(C, CE, /* IsStrnlen = */ true);
  1026. }
  1027. void CStringChecker::evalstrLengthCommon(CheckerContext &C, const CallExpr *CE,
  1028. bool IsStrnlen) const {
  1029. CurrentFunctionDescription = "string length function";
  1030. ProgramStateRef state = C.getState();
  1031. const LocationContext *LCtx = C.getLocationContext();
  1032. if (IsStrnlen) {
  1033. const Expr *maxlenExpr = CE->getArg(1);
  1034. SVal maxlenVal = state->getSVal(maxlenExpr, LCtx);
  1035. ProgramStateRef stateZeroSize, stateNonZeroSize;
  1036. std::tie(stateZeroSize, stateNonZeroSize) =
  1037. assumeZero(C, state, maxlenVal, maxlenExpr->getType());
  1038. // If the size can be zero, the result will be 0 in that case, and we don't
  1039. // have to check the string itself.
  1040. if (stateZeroSize) {
  1041. SVal zero = C.getSValBuilder().makeZeroVal(CE->getType());
  1042. stateZeroSize = stateZeroSize->BindExpr(CE, LCtx, zero);
  1043. C.addTransition(stateZeroSize);
  1044. }
  1045. // If the size is GUARANTEED to be zero, we're done!
  1046. if (!stateNonZeroSize)
  1047. return;
  1048. // Otherwise, record the assumption that the size is nonzero.
  1049. state = stateNonZeroSize;
  1050. }
  1051. // Check that the string argument is non-null.
  1052. const Expr *Arg = CE->getArg(0);
  1053. SVal ArgVal = state->getSVal(Arg, LCtx);
  1054. state = checkNonNull(C, state, Arg, ArgVal);
  1055. if (!state)
  1056. return;
  1057. SVal strLength = getCStringLength(C, state, Arg, ArgVal);
  1058. // If the argument isn't a valid C string, there's no valid state to
  1059. // transition to.
  1060. if (strLength.isUndef())
  1061. return;
  1062. DefinedOrUnknownSVal result = UnknownVal();
  1063. // If the check is for strnlen() then bind the return value to no more than
  1064. // the maxlen value.
  1065. if (IsStrnlen) {
  1066. QualType cmpTy = C.getSValBuilder().getConditionType();
  1067. // It's a little unfortunate to be getting this again,
  1068. // but it's not that expensive...
  1069. const Expr *maxlenExpr = CE->getArg(1);
  1070. SVal maxlenVal = state->getSVal(maxlenExpr, LCtx);
  1071. Optional<NonLoc> strLengthNL = strLength.getAs<NonLoc>();
  1072. Optional<NonLoc> maxlenValNL = maxlenVal.getAs<NonLoc>();
  1073. if (strLengthNL && maxlenValNL) {
  1074. ProgramStateRef stateStringTooLong, stateStringNotTooLong;
  1075. // Check if the strLength is greater than the maxlen.
  1076. std::tie(stateStringTooLong, stateStringNotTooLong) = state->assume(
  1077. C.getSValBuilder()
  1078. .evalBinOpNN(state, BO_GT, *strLengthNL, *maxlenValNL, cmpTy)
  1079. .castAs<DefinedOrUnknownSVal>());
  1080. if (stateStringTooLong && !stateStringNotTooLong) {
  1081. // If the string is longer than maxlen, return maxlen.
  1082. result = *maxlenValNL;
  1083. } else if (stateStringNotTooLong && !stateStringTooLong) {
  1084. // If the string is shorter than maxlen, return its length.
  1085. result = *strLengthNL;
  1086. }
  1087. }
  1088. if (result.isUnknown()) {
  1089. // If we don't have enough information for a comparison, there's
  1090. // no guarantee the full string length will actually be returned.
  1091. // All we know is the return value is the min of the string length
  1092. // and the limit. This is better than nothing.
  1093. result = C.getSValBuilder().conjureSymbolVal(nullptr, CE, LCtx,
  1094. C.blockCount());
  1095. NonLoc resultNL = result.castAs<NonLoc>();
  1096. if (strLengthNL) {
  1097. state = state->assume(C.getSValBuilder().evalBinOpNN(
  1098. state, BO_LE, resultNL, *strLengthNL, cmpTy)
  1099. .castAs<DefinedOrUnknownSVal>(), true);
  1100. }
  1101. if (maxlenValNL) {
  1102. state = state->assume(C.getSValBuilder().evalBinOpNN(
  1103. state, BO_LE, resultNL, *maxlenValNL, cmpTy)
  1104. .castAs<DefinedOrUnknownSVal>(), true);
  1105. }
  1106. }
  1107. } else {
  1108. // This is a plain strlen(), not strnlen().
  1109. result = strLength.castAs<DefinedOrUnknownSVal>();
  1110. // If we don't know the length of the string, conjure a return
  1111. // value, so it can be used in constraints, at least.
  1112. if (result.isUnknown()) {
  1113. result = C.getSValBuilder().conjureSymbolVal(nullptr, CE, LCtx,
  1114. C.blockCount());
  1115. }
  1116. }
  1117. // Bind the return value.
  1118. assert(!result.isUnknown() && "Should have conjured a value by now");
  1119. state = state->BindExpr(CE, LCtx, result);
  1120. C.addTransition(state);
  1121. }
  1122. void CStringChecker::evalStrcpy(CheckerContext &C, const CallExpr *CE) const {
  1123. if (CE->getNumArgs() < 2)
  1124. return;
  1125. // char *strcpy(char *restrict dst, const char *restrict src);
  1126. evalStrcpyCommon(C, CE,
  1127. /* returnEnd = */ false,
  1128. /* isBounded = */ false,
  1129. /* isAppending = */ false);
  1130. }
  1131. void CStringChecker::evalStrncpy(CheckerContext &C, const CallExpr *CE) const {
  1132. if (CE->getNumArgs() < 3)
  1133. return;
  1134. // char *strncpy(char *restrict dst, const char *restrict src, size_t n);
  1135. evalStrcpyCommon(C, CE,
  1136. /* returnEnd = */ false,
  1137. /* isBounded = */ true,
  1138. /* isAppending = */ false);
  1139. }
  1140. void CStringChecker::evalStpcpy(CheckerContext &C, const CallExpr *CE) const {
  1141. if (CE->getNumArgs() < 2)
  1142. return;
  1143. // char *stpcpy(char *restrict dst, const char *restrict src);
  1144. evalStrcpyCommon(C, CE,
  1145. /* returnEnd = */ true,
  1146. /* isBounded = */ false,
  1147. /* isAppending = */ false);
  1148. }
  1149. void CStringChecker::evalStrcat(CheckerContext &C, const CallExpr *CE) const {
  1150. if (CE->getNumArgs() < 2)
  1151. return;
  1152. //char *strcat(char *restrict s1, const char *restrict s2);
  1153. evalStrcpyCommon(C, CE,
  1154. /* returnEnd = */ false,
  1155. /* isBounded = */ false,
  1156. /* isAppending = */ true);
  1157. }
  1158. void CStringChecker::evalStrncat(CheckerContext &C, const CallExpr *CE) const {
  1159. if (CE->getNumArgs() < 3)
  1160. return;
  1161. //char *strncat(char *restrict s1, const char *restrict s2, size_t n);
  1162. evalStrcpyCommon(C, CE,
  1163. /* returnEnd = */ false,
  1164. /* isBounded = */ true,
  1165. /* isAppending = */ true);
  1166. }
  1167. void CStringChecker::evalStrcpyCommon(CheckerContext &C, const CallExpr *CE,
  1168. bool returnEnd, bool isBounded,
  1169. bool isAppending) const {
  1170. CurrentFunctionDescription = "string copy function";
  1171. ProgramStateRef state = C.getState();
  1172. const LocationContext *LCtx = C.getLocationContext();
  1173. // Check that the destination is non-null.
  1174. const Expr *Dst = CE->getArg(0);
  1175. SVal DstVal = state->getSVal(Dst, LCtx);
  1176. state = checkNonNull(C, state, Dst, DstVal);
  1177. if (!state)
  1178. return;
  1179. // Check that the source is non-null.
  1180. const Expr *srcExpr = CE->getArg(1);
  1181. SVal srcVal = state->getSVal(srcExpr, LCtx);
  1182. state = checkNonNull(C, state, srcExpr, srcVal);
  1183. if (!state)
  1184. return;
  1185. // Get the string length of the source.
  1186. SVal strLength = getCStringLength(C, state, srcExpr, srcVal);
  1187. // If the source isn't a valid C string, give up.
  1188. if (strLength.isUndef())
  1189. return;
  1190. SValBuilder &svalBuilder = C.getSValBuilder();
  1191. QualType cmpTy = svalBuilder.getConditionType();
  1192. QualType sizeTy = svalBuilder.getContext().getSizeType();
  1193. // These two values allow checking two kinds of errors:
  1194. // - actual overflows caused by a source that doesn't fit in the destination
  1195. // - potential overflows caused by a bound that could exceed the destination
  1196. SVal amountCopied = UnknownVal();
  1197. SVal maxLastElementIndex = UnknownVal();
  1198. const char *boundWarning = nullptr;
  1199. // If the function is strncpy, strncat, etc... it is bounded.
  1200. if (isBounded) {
  1201. // Get the max number of characters to copy.
  1202. const Expr *lenExpr = CE->getArg(2);
  1203. SVal lenVal = state->getSVal(lenExpr, LCtx);
  1204. // Protect against misdeclared strncpy().
  1205. lenVal = svalBuilder.evalCast(lenVal, sizeTy, lenExpr->getType());
  1206. Optional<NonLoc> strLengthNL = strLength.getAs<NonLoc>();
  1207. Optional<NonLoc> lenValNL = lenVal.getAs<NonLoc>();
  1208. // If we know both values, we might be able to figure out how much
  1209. // we're copying.
  1210. if (strLengthNL && lenValNL) {
  1211. ProgramStateRef stateSourceTooLong, stateSourceNotTooLong;
  1212. // Check if the max number to copy is less than the length of the src.
  1213. // If the bound is equal to the source length, strncpy won't null-
  1214. // terminate the result!
  1215. std::tie(stateSourceTooLong, stateSourceNotTooLong) = state->assume(
  1216. svalBuilder.evalBinOpNN(state, BO_GE, *strLengthNL, *lenValNL, cmpTy)
  1217. .castAs<DefinedOrUnknownSVal>());
  1218. if (stateSourceTooLong && !stateSourceNotTooLong) {
  1219. // Max number to copy is less than the length of the src, so the actual
  1220. // strLength copied is the max number arg.
  1221. state = stateSourceTooLong;
  1222. amountCopied = lenVal;
  1223. } else if (!stateSourceTooLong && stateSourceNotTooLong) {
  1224. // The source buffer entirely fits in the bound.
  1225. state = stateSourceNotTooLong;
  1226. amountCopied = strLength;
  1227. }
  1228. }
  1229. // We still want to know if the bound is known to be too large.
  1230. if (lenValNL) {
  1231. if (isAppending) {
  1232. // For strncat, the check is strlen(dst) + lenVal < sizeof(dst)
  1233. // Get the string length of the destination. If the destination is
  1234. // memory that can't have a string length, we shouldn't be copying
  1235. // into it anyway.
  1236. SVal dstStrLength = getCStringLength(C, state, Dst, DstVal);
  1237. if (dstStrLength.isUndef())
  1238. return;
  1239. if (Optional<NonLoc> dstStrLengthNL = dstStrLength.getAs<NonLoc>()) {
  1240. maxLastElementIndex = svalBuilder.evalBinOpNN(state, BO_Add,
  1241. *lenValNL,
  1242. *dstStrLengthNL,
  1243. sizeTy);
  1244. boundWarning = "Size argument is greater than the free space in the "
  1245. "destination buffer";
  1246. }
  1247. } else {
  1248. // For strncpy, this is just checking that lenVal <= sizeof(dst)
  1249. // (Yes, strncpy and strncat differ in how they treat termination.
  1250. // strncat ALWAYS terminates, but strncpy doesn't.)
  1251. // We need a special case for when the copy size is zero, in which
  1252. // case strncpy will do no work at all. Our bounds check uses n-1
  1253. // as the last element accessed, so n == 0 is problematic.
  1254. ProgramStateRef StateZeroSize, StateNonZeroSize;
  1255. std::tie(StateZeroSize, StateNonZeroSize) =
  1256. assumeZero(C, state, *lenValNL, sizeTy);
  1257. // If the size is known to be zero, we're done.
  1258. if (StateZeroSize && !StateNonZeroSize) {
  1259. StateZeroSize = StateZeroSize->BindExpr(CE, LCtx, DstVal);
  1260. C.addTransition(StateZeroSize);
  1261. return;
  1262. }
  1263. // Otherwise, go ahead and figure out the last element we'll touch.
  1264. // We don't record the non-zero assumption here because we can't
  1265. // be sure. We won't warn on a possible zero.
  1266. NonLoc one = svalBuilder.makeIntVal(1, sizeTy).castAs<NonLoc>();
  1267. maxLastElementIndex = svalBuilder.evalBinOpNN(state, BO_Sub, *lenValNL,
  1268. one, sizeTy);
  1269. boundWarning = "Size argument is greater than the length of the "
  1270. "destination buffer";
  1271. }
  1272. }
  1273. // If we couldn't pin down the copy length, at least bound it.
  1274. // FIXME: We should actually run this code path for append as well, but
  1275. // right now it creates problems with constraints (since we can end up
  1276. // trying to pass constraints from symbol to symbol).
  1277. if (amountCopied.isUnknown() && !isAppending) {
  1278. // Try to get a "hypothetical" string length symbol, which we can later
  1279. // set as a real value if that turns out to be the case.
  1280. amountCopied = getCStringLength(C, state, lenExpr, srcVal, true);
  1281. assert(!amountCopied.isUndef());
  1282. if (Optional<NonLoc> amountCopiedNL = amountCopied.getAs<NonLoc>()) {
  1283. if (lenValNL) {
  1284. // amountCopied <= lenVal
  1285. SVal copiedLessThanBound = svalBuilder.evalBinOpNN(state, BO_LE,
  1286. *amountCopiedNL,
  1287. *lenValNL,
  1288. cmpTy);
  1289. state = state->assume(
  1290. copiedLessThanBound.castAs<DefinedOrUnknownSVal>(), true);
  1291. if (!state)
  1292. return;
  1293. }
  1294. if (strLengthNL) {
  1295. // amountCopied <= strlen(source)
  1296. SVal copiedLessThanSrc = svalBuilder.evalBinOpNN(state, BO_LE,
  1297. *amountCopiedNL,
  1298. *strLengthNL,
  1299. cmpTy);
  1300. state = state->assume(
  1301. copiedLessThanSrc.castAs<DefinedOrUnknownSVal>(), true);
  1302. if (!state)
  1303. return;
  1304. }
  1305. }
  1306. }
  1307. } else {
  1308. // The function isn't bounded. The amount copied should match the length
  1309. // of the source buffer.
  1310. amountCopied = strLength;
  1311. }
  1312. assert(state);
  1313. // This represents the number of characters copied into the destination
  1314. // buffer. (It may not actually be the strlen if the destination buffer
  1315. // is not terminated.)
  1316. SVal finalStrLength = UnknownVal();
  1317. // If this is an appending function (strcat, strncat...) then set the
  1318. // string length to strlen(src) + strlen(dst) since the buffer will
  1319. // ultimately contain both.
  1320. if (isAppending) {
  1321. // Get the string length of the destination. If the destination is memory
  1322. // that can't have a string length, we shouldn't be copying into it anyway.
  1323. SVal dstStrLength = getCStringLength(C, state, Dst, DstVal);
  1324. if (dstStrLength.isUndef())
  1325. return;
  1326. Optional<NonLoc> srcStrLengthNL = amountCopied.getAs<NonLoc>();
  1327. Optional<NonLoc> dstStrLengthNL = dstStrLength.getAs<NonLoc>();
  1328. // If we know both string lengths, we might know the final string length.
  1329. if (srcStrLengthNL && dstStrLengthNL) {
  1330. // Make sure the two lengths together don't overflow a size_t.
  1331. state = checkAdditionOverflow(C, state, *srcStrLengthNL, *dstStrLengthNL);
  1332. if (!state)
  1333. return;
  1334. finalStrLength = svalBuilder.evalBinOpNN(state, BO_Add, *srcStrLengthNL,
  1335. *dstStrLengthNL, sizeTy);
  1336. }
  1337. // If we couldn't get a single value for the final string length,
  1338. // we can at least bound it by the individual lengths.
  1339. if (finalStrLength.isUnknown()) {
  1340. // Try to get a "hypothetical" string length symbol, which we can later
  1341. // set as a real value if that turns out to be the case.
  1342. finalStrLength = getCStringLength(C, state, CE, DstVal, true);
  1343. assert(!finalStrLength.isUndef());
  1344. if (Optional<NonLoc> finalStrLengthNL = finalStrLength.getAs<NonLoc>()) {
  1345. if (srcStrLengthNL) {
  1346. // finalStrLength >= srcStrLength
  1347. SVal sourceInResult = svalBuilder.evalBinOpNN(state, BO_GE,
  1348. *finalStrLengthNL,
  1349. *srcStrLengthNL,
  1350. cmpTy);
  1351. state = state->assume(sourceInResult.castAs<DefinedOrUnknownSVal>(),
  1352. true);
  1353. if (!state)
  1354. return;
  1355. }
  1356. if (dstStrLengthNL) {
  1357. // finalStrLength >= dstStrLength
  1358. SVal destInResult = svalBuilder.evalBinOpNN(state, BO_GE,
  1359. *finalStrLengthNL,
  1360. *dstStrLengthNL,
  1361. cmpTy);
  1362. state =
  1363. state->assume(destInResult.castAs<DefinedOrUnknownSVal>(), true);
  1364. if (!state)
  1365. return;
  1366. }
  1367. }
  1368. }
  1369. } else {
  1370. // Otherwise, this is a copy-over function (strcpy, strncpy, ...), and
  1371. // the final string length will match the input string length.
  1372. finalStrLength = amountCopied;
  1373. }
  1374. // The final result of the function will either be a pointer past the last
  1375. // copied element, or a pointer to the start of the destination buffer.
  1376. SVal Result = (returnEnd ? UnknownVal() : DstVal);
  1377. assert(state);
  1378. // If the destination is a MemRegion, try to check for a buffer overflow and
  1379. // record the new string length.
  1380. if (Optional<loc::MemRegionVal> dstRegVal =
  1381. DstVal.getAs<loc::MemRegionVal>()) {
  1382. QualType ptrTy = Dst->getType();
  1383. // If we have an exact value on a bounded copy, use that to check for
  1384. // overflows, rather than our estimate about how much is actually copied.
  1385. if (boundWarning) {
  1386. if (Optional<NonLoc> maxLastNL = maxLastElementIndex.getAs<NonLoc>()) {
  1387. SVal maxLastElement = svalBuilder.evalBinOpLN(state, BO_Add, *dstRegVal,
  1388. *maxLastNL, ptrTy);
  1389. state = CheckLocation(C, state, CE->getArg(2), maxLastElement,
  1390. boundWarning);
  1391. if (!state)
  1392. return;
  1393. }
  1394. }
  1395. // Then, if the final length is known...
  1396. if (Optional<NonLoc> knownStrLength = finalStrLength.getAs<NonLoc>()) {
  1397. SVal lastElement = svalBuilder.evalBinOpLN(state, BO_Add, *dstRegVal,
  1398. *knownStrLength, ptrTy);
  1399. // ...and we haven't checked the bound, we'll check the actual copy.
  1400. if (!boundWarning) {
  1401. const char * const warningMsg =
  1402. "String copy function overflows destination buffer";
  1403. state = CheckLocation(C, state, Dst, lastElement, warningMsg);
  1404. if (!state)
  1405. return;
  1406. }
  1407. // If this is a stpcpy-style copy, the last element is the return value.
  1408. if (returnEnd)
  1409. Result = lastElement;
  1410. }
  1411. // Invalidate the destination (regular invalidation without pointer-escaping
  1412. // the address of the top-level region). This must happen before we set the
  1413. // C string length because invalidation will clear the length.
  1414. // FIXME: Even if we can't perfectly model the copy, we should see if we
  1415. // can use LazyCompoundVals to copy the source values into the destination.
  1416. // This would probably remove any existing bindings past the end of the
  1417. // string, but that's still an improvement over blank invalidation.
  1418. state = InvalidateBuffer(C, state, Dst, *dstRegVal,
  1419. /*IsSourceBuffer*/false, nullptr);
  1420. // Invalidate the source (const-invalidation without const-pointer-escaping
  1421. // the address of the top-level region).
  1422. state = InvalidateBuffer(C, state, srcExpr, srcVal, /*IsSourceBuffer*/true,
  1423. nullptr);
  1424. // Set the C string length of the destination, if we know it.
  1425. if (isBounded && !isAppending) {
  1426. // strncpy is annoying in that it doesn't guarantee to null-terminate
  1427. // the result string. If the original string didn't fit entirely inside
  1428. // the bound (including the null-terminator), we don't know how long the
  1429. // result is.
  1430. if (amountCopied != strLength)
  1431. finalStrLength = UnknownVal();
  1432. }
  1433. state = setCStringLength(state, dstRegVal->getRegion(), finalStrLength);
  1434. }
  1435. assert(state);
  1436. // If this is a stpcpy-style copy, but we were unable to check for a buffer
  1437. // overflow, we still need a result. Conjure a return value.
  1438. if (returnEnd && Result.isUnknown()) {
  1439. Result = svalBuilder.conjureSymbolVal(nullptr, CE, LCtx, C.blockCount());
  1440. }
  1441. // Set the return value.
  1442. state = state->BindExpr(CE, LCtx, Result);
  1443. C.addTransition(state);
  1444. }
  1445. void CStringChecker::evalStrcmp(CheckerContext &C, const CallExpr *CE) const {
  1446. if (CE->getNumArgs() < 2)
  1447. return;
  1448. //int strcmp(const char *s1, const char *s2);
  1449. evalStrcmpCommon(C, CE, /* isBounded = */ false, /* ignoreCase = */ false);
  1450. }
  1451. void CStringChecker::evalStrncmp(CheckerContext &C, const CallExpr *CE) const {
  1452. if (CE->getNumArgs() < 3)
  1453. return;
  1454. //int strncmp(const char *s1, const char *s2, size_t n);
  1455. evalStrcmpCommon(C, CE, /* isBounded = */ true, /* ignoreCase = */ false);
  1456. }
  1457. void CStringChecker::evalStrcasecmp(CheckerContext &C,
  1458. const CallExpr *CE) const {
  1459. if (CE->getNumArgs() < 2)
  1460. return;
  1461. //int strcasecmp(const char *s1, const char *s2);
  1462. evalStrcmpCommon(C, CE, /* isBounded = */ false, /* ignoreCase = */ true);
  1463. }
  1464. void CStringChecker::evalStrncasecmp(CheckerContext &C,
  1465. const CallExpr *CE) const {
  1466. if (CE->getNumArgs() < 3)
  1467. return;
  1468. //int strncasecmp(const char *s1, const char *s2, size_t n);
  1469. evalStrcmpCommon(C, CE, /* isBounded = */ true, /* ignoreCase = */ true);
  1470. }
  1471. void CStringChecker::evalStrcmpCommon(CheckerContext &C, const CallExpr *CE,
  1472. bool isBounded, bool ignoreCase) const {
  1473. CurrentFunctionDescription = "string comparison function";
  1474. ProgramStateRef state = C.getState();
  1475. const LocationContext *LCtx = C.getLocationContext();
  1476. // Check that the first string is non-null
  1477. const Expr *s1 = CE->getArg(0);
  1478. SVal s1Val = state->getSVal(s1, LCtx);
  1479. state = checkNonNull(C, state, s1, s1Val);
  1480. if (!state)
  1481. return;
  1482. // Check that the second string is non-null.
  1483. const Expr *s2 = CE->getArg(1);
  1484. SVal s2Val = state->getSVal(s2, LCtx);
  1485. state = checkNonNull(C, state, s2, s2Val);
  1486. if (!state)
  1487. return;
  1488. // Get the string length of the first string or give up.
  1489. SVal s1Length = getCStringLength(C, state, s1, s1Val);
  1490. if (s1Length.isUndef())
  1491. return;
  1492. // Get the string length of the second string or give up.
  1493. SVal s2Length = getCStringLength(C, state, s2, s2Val);
  1494. if (s2Length.isUndef())
  1495. return;
  1496. // If we know the two buffers are the same, we know the result is 0.
  1497. // First, get the two buffers' addresses. Another checker will have already
  1498. // made sure they're not undefined.
  1499. DefinedOrUnknownSVal LV = s1Val.castAs<DefinedOrUnknownSVal>();
  1500. DefinedOrUnknownSVal RV = s2Val.castAs<DefinedOrUnknownSVal>();
  1501. // See if they are the same.
  1502. SValBuilder &svalBuilder = C.getSValBuilder();
  1503. DefinedOrUnknownSVal SameBuf = svalBuilder.evalEQ(state, LV, RV);
  1504. ProgramStateRef StSameBuf, StNotSameBuf;
  1505. std::tie(StSameBuf, StNotSameBuf) = state->assume(SameBuf);
  1506. // If the two arguments might be the same buffer, we know the result is 0,
  1507. // and we only need to check one size.
  1508. if (StSameBuf) {
  1509. StSameBuf = StSameBuf->BindExpr(CE, LCtx,
  1510. svalBuilder.makeZeroVal(CE->getType()));
  1511. C.addTransition(StSameBuf);
  1512. // If the two arguments are GUARANTEED to be the same, we're done!
  1513. if (!StNotSameBuf)
  1514. return;
  1515. }
  1516. assert(StNotSameBuf);
  1517. state = StNotSameBuf;
  1518. // At this point we can go about comparing the two buffers.
  1519. // For now, we only do this if they're both known string literals.
  1520. // Attempt to extract string literals from both expressions.
  1521. const StringLiteral *s1StrLiteral = getCStringLiteral(C, state, s1, s1Val);
  1522. const StringLiteral *s2StrLiteral = getCStringLiteral(C, state, s2, s2Val);
  1523. bool canComputeResult = false;
  1524. SVal resultVal = svalBuilder.conjureSymbolVal(nullptr, CE, LCtx,
  1525. C.blockCount());
  1526. if (s1StrLiteral && s2StrLiteral) {
  1527. StringRef s1StrRef = s1StrLiteral->getString();
  1528. StringRef s2StrRef = s2StrLiteral->getString();
  1529. if (isBounded) {
  1530. // Get the max number of characters to compare.
  1531. const Expr *lenExpr = CE->getArg(2);
  1532. SVal lenVal = state->getSVal(lenExpr, LCtx);
  1533. // If the length is known, we can get the right substrings.
  1534. if (const llvm::APSInt *len = svalBuilder.getKnownValue(state, lenVal)) {
  1535. // Create substrings of each to compare the prefix.
  1536. s1StrRef = s1StrRef.substr(0, (size_t)len->getZExtValue());
  1537. s2StrRef = s2StrRef.substr(0, (size_t)len->getZExtValue());
  1538. canComputeResult = true;
  1539. }
  1540. } else {
  1541. // This is a normal, unbounded strcmp.
  1542. canComputeResult = true;
  1543. }
  1544. if (canComputeResult) {
  1545. // Real strcmp stops at null characters.
  1546. size_t s1Term = s1StrRef.find('\0');
  1547. if (s1Term != StringRef::npos)
  1548. s1StrRef = s1StrRef.substr(0, s1Term);
  1549. size_t s2Term = s2StrRef.find('\0');
  1550. if (s2Term != StringRef::npos)
  1551. s2StrRef = s2StrRef.substr(0, s2Term);
  1552. // Use StringRef's comparison methods to compute the actual result.
  1553. int compareRes = ignoreCase ? s1StrRef.compare_lower(s2StrRef)
  1554. : s1StrRef.compare(s2StrRef);
  1555. // The strcmp function returns an integer greater than, equal to, or less
  1556. // than zero, [c11, p7.24.4.2].
  1557. if (compareRes == 0) {
  1558. resultVal = svalBuilder.makeIntVal(compareRes, CE->getType());
  1559. }
  1560. else {
  1561. DefinedSVal zeroVal = svalBuilder.makeIntVal(0, CE->getType());
  1562. // Constrain strcmp's result range based on the result of StringRef's
  1563. // comparison methods.
  1564. BinaryOperatorKind op = (compareRes == 1) ? BO_GT : BO_LT;
  1565. SVal compareWithZero =
  1566. svalBuilder.evalBinOp(state, op, resultVal, zeroVal,
  1567. svalBuilder.getConditionType());
  1568. DefinedSVal compareWithZeroVal = compareWithZero.castAs<DefinedSVal>();
  1569. state = state->assume(compareWithZeroVal, true);
  1570. }
  1571. }
  1572. }
  1573. state = state->BindExpr(CE, LCtx, resultVal);
  1574. // Record this as a possible path.
  1575. C.addTransition(state);
  1576. }
  1577. void CStringChecker::evalStrsep(CheckerContext &C, const CallExpr *CE) const {
  1578. //char *strsep(char **stringp, const char *delim);
  1579. if (CE->getNumArgs() < 2)
  1580. return;
  1581. // Sanity: does the search string parameter match the return type?
  1582. const Expr *SearchStrPtr = CE->getArg(0);
  1583. QualType CharPtrTy = SearchStrPtr->getType()->getPointeeType();
  1584. if (CharPtrTy.isNull() ||
  1585. CE->getType().getUnqualifiedType() != CharPtrTy.getUnqualifiedType())
  1586. return;
  1587. CurrentFunctionDescription = "strsep()";
  1588. ProgramStateRef State = C.getState();
  1589. const LocationContext *LCtx = C.getLocationContext();
  1590. // Check that the search string pointer is non-null (though it may point to
  1591. // a null string).
  1592. SVal SearchStrVal = State->getSVal(SearchStrPtr, LCtx);
  1593. State = checkNonNull(C, State, SearchStrPtr, SearchStrVal);
  1594. if (!State)
  1595. return;
  1596. // Check that the delimiter string is non-null.
  1597. const Expr *DelimStr = CE->getArg(1);
  1598. SVal DelimStrVal = State->getSVal(DelimStr, LCtx);
  1599. State = checkNonNull(C, State, DelimStr, DelimStrVal);
  1600. if (!State)
  1601. return;
  1602. SValBuilder &SVB = C.getSValBuilder();
  1603. SVal Result;
  1604. if (Optional<Loc> SearchStrLoc = SearchStrVal.getAs<Loc>()) {
  1605. // Get the current value of the search string pointer, as a char*.
  1606. Result = State->getSVal(*SearchStrLoc, CharPtrTy);
  1607. // Invalidate the search string, representing the change of one delimiter
  1608. // character to NUL.
  1609. State = InvalidateBuffer(C, State, SearchStrPtr, Result,
  1610. /*IsSourceBuffer*/false, nullptr);
  1611. // Overwrite the search string pointer. The new value is either an address
  1612. // further along in the same string, or NULL if there are no more tokens.
  1613. State = State->bindLoc(*SearchStrLoc,
  1614. SVB.conjureSymbolVal(getTag(),
  1615. CE,
  1616. LCtx,
  1617. CharPtrTy,
  1618. C.blockCount()),
  1619. LCtx);
  1620. } else {
  1621. assert(SearchStrVal.isUnknown());
  1622. // Conjure a symbolic value. It's the best we can do.
  1623. Result = SVB.conjureSymbolVal(nullptr, CE, LCtx, C.blockCount());
  1624. }
  1625. // Set the return value, and finish.
  1626. State = State->BindExpr(CE, LCtx, Result);
  1627. C.addTransition(State);
  1628. }
  1629. // These should probably be moved into a C++ standard library checker.
  1630. void CStringChecker::evalStdCopy(CheckerContext &C, const CallExpr *CE) const {
  1631. evalStdCopyCommon(C, CE);
  1632. }
  1633. void CStringChecker::evalStdCopyBackward(CheckerContext &C,
  1634. const CallExpr *CE) const {
  1635. evalStdCopyCommon(C, CE);
  1636. }
  1637. void CStringChecker::evalStdCopyCommon(CheckerContext &C,
  1638. const CallExpr *CE) const {
  1639. if (CE->getNumArgs() < 3)
  1640. return;
  1641. ProgramStateRef State = C.getState();
  1642. const LocationContext *LCtx = C.getLocationContext();
  1643. // template <class _InputIterator, class _OutputIterator>
  1644. // _OutputIterator
  1645. // copy(_InputIterator __first, _InputIterator __last,
  1646. // _OutputIterator __result)
  1647. // Invalidate the destination buffer
  1648. const Expr *Dst = CE->getArg(2);
  1649. SVal DstVal = State->getSVal(Dst, LCtx);
  1650. State = InvalidateBuffer(C, State, Dst, DstVal, /*IsSource=*/false,
  1651. /*Size=*/nullptr);
  1652. SValBuilder &SVB = C.getSValBuilder();
  1653. SVal ResultVal = SVB.conjureSymbolVal(nullptr, CE, LCtx, C.blockCount());
  1654. State = State->BindExpr(CE, LCtx, ResultVal);
  1655. C.addTransition(State);
  1656. }
  1657. void CStringChecker::evalMemset(CheckerContext &C, const CallExpr *CE) const {
  1658. if (CE->getNumArgs() != 3)
  1659. return;
  1660. CurrentFunctionDescription = "memory set function";
  1661. const Expr *Mem = CE->getArg(0);
  1662. const Expr *Size = CE->getArg(2);
  1663. ProgramStateRef State = C.getState();
  1664. // See if the size argument is zero.
  1665. const LocationContext *LCtx = C.getLocationContext();
  1666. SVal SizeVal = State->getSVal(Size, LCtx);
  1667. QualType SizeTy = Size->getType();
  1668. ProgramStateRef StateZeroSize, StateNonZeroSize;
  1669. std::tie(StateZeroSize, StateNonZeroSize) =
  1670. assumeZero(C, State, SizeVal, SizeTy);
  1671. // Get the value of the memory area.
  1672. SVal MemVal = State->getSVal(Mem, LCtx);
  1673. // If the size is zero, there won't be any actual memory access, so
  1674. // just bind the return value to the Mem buffer and return.
  1675. if (StateZeroSize && !StateNonZeroSize) {
  1676. StateZeroSize = StateZeroSize->BindExpr(CE, LCtx, MemVal);
  1677. C.addTransition(StateZeroSize);
  1678. return;
  1679. }
  1680. // Ensure the memory area is not null.
  1681. // If it is NULL there will be a NULL pointer dereference.
  1682. State = checkNonNull(C, StateNonZeroSize, Mem, MemVal);
  1683. if (!State)
  1684. return;
  1685. State = CheckBufferAccess(C, State, Size, Mem);
  1686. if (!State)
  1687. return;
  1688. State = InvalidateBuffer(C, State, Mem, C.getSVal(Mem),
  1689. /*IsSourceBuffer*/false, Size);
  1690. if (!State)
  1691. return;
  1692. State = State->BindExpr(CE, LCtx, MemVal);
  1693. C.addTransition(State);
  1694. }
  1695. static bool isCPPStdLibraryFunction(const FunctionDecl *FD, StringRef Name) {
  1696. IdentifierInfo *II = FD->getIdentifier();
  1697. if (!II)
  1698. return false;
  1699. if (!AnalysisDeclContext::isInStdNamespace(FD))
  1700. return false;
  1701. if (II->getName().equals(Name))
  1702. return true;
  1703. return false;
  1704. }
  1705. //===----------------------------------------------------------------------===//
  1706. // The driver method, and other Checker callbacks.
  1707. //===----------------------------------------------------------------------===//
  1708. bool CStringChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
  1709. const FunctionDecl *FDecl = C.getCalleeDecl(CE);
  1710. if (!FDecl)
  1711. return false;
  1712. // FIXME: Poorly-factored string switches are slow.
  1713. FnCheck evalFunction = nullptr;
  1714. if (C.isCLibraryFunction(FDecl, "memcpy"))
  1715. evalFunction = &CStringChecker::evalMemcpy;
  1716. else if (C.isCLibraryFunction(FDecl, "mempcpy"))
  1717. evalFunction = &CStringChecker::evalMempcpy;
  1718. else if (C.isCLibraryFunction(FDecl, "memcmp"))
  1719. evalFunction = &CStringChecker::evalMemcmp;
  1720. else if (C.isCLibraryFunction(FDecl, "memmove"))
  1721. evalFunction = &CStringChecker::evalMemmove;
  1722. else if (C.isCLibraryFunction(FDecl, "memset"))
  1723. evalFunction = &CStringChecker::evalMemset;
  1724. else if (C.isCLibraryFunction(FDecl, "strcpy"))
  1725. evalFunction = &CStringChecker::evalStrcpy;
  1726. else if (C.isCLibraryFunction(FDecl, "strncpy"))
  1727. evalFunction = &CStringChecker::evalStrncpy;
  1728. else if (C.isCLibraryFunction(FDecl, "stpcpy"))
  1729. evalFunction = &CStringChecker::evalStpcpy;
  1730. else if (C.isCLibraryFunction(FDecl, "strcat"))
  1731. evalFunction = &CStringChecker::evalStrcat;
  1732. else if (C.isCLibraryFunction(FDecl, "strncat"))
  1733. evalFunction = &CStringChecker::evalStrncat;
  1734. else if (C.isCLibraryFunction(FDecl, "strlen"))
  1735. evalFunction = &CStringChecker::evalstrLength;
  1736. else if (C.isCLibraryFunction(FDecl, "strnlen"))
  1737. evalFunction = &CStringChecker::evalstrnLength;
  1738. else if (C.isCLibraryFunction(FDecl, "strcmp"))
  1739. evalFunction = &CStringChecker::evalStrcmp;
  1740. else if (C.isCLibraryFunction(FDecl, "strncmp"))
  1741. evalFunction = &CStringChecker::evalStrncmp;
  1742. else if (C.isCLibraryFunction(FDecl, "strcasecmp"))
  1743. evalFunction = &CStringChecker::evalStrcasecmp;
  1744. else if (C.isCLibraryFunction(FDecl, "strncasecmp"))
  1745. evalFunction = &CStringChecker::evalStrncasecmp;
  1746. else if (C.isCLibraryFunction(FDecl, "strsep"))
  1747. evalFunction = &CStringChecker::evalStrsep;
  1748. else if (C.isCLibraryFunction(FDecl, "bcopy"))
  1749. evalFunction = &CStringChecker::evalBcopy;
  1750. else if (C.isCLibraryFunction(FDecl, "bcmp"))
  1751. evalFunction = &CStringChecker::evalMemcmp;
  1752. else if (isCPPStdLibraryFunction(FDecl, "copy"))
  1753. evalFunction = &CStringChecker::evalStdCopy;
  1754. else if (isCPPStdLibraryFunction(FDecl, "copy_backward"))
  1755. evalFunction = &CStringChecker::evalStdCopyBackward;
  1756. // If the callee isn't a string function, let another checker handle it.
  1757. if (!evalFunction)
  1758. return false;
  1759. // Check and evaluate the call.
  1760. (this->*evalFunction)(C, CE);
  1761. // If the evaluate call resulted in no change, chain to the next eval call
  1762. // handler.
  1763. // Note, the custom CString evaluation calls assume that basic safety
  1764. // properties are held. However, if the user chooses to turn off some of these
  1765. // checks, we ignore the issues and leave the call evaluation to a generic
  1766. // handler.
  1767. return C.isDifferent();
  1768. }
  1769. void CStringChecker::checkPreStmt(const DeclStmt *DS, CheckerContext &C) const {
  1770. // Record string length for char a[] = "abc";
  1771. ProgramStateRef state = C.getState();
  1772. for (const auto *I : DS->decls()) {
  1773. const VarDecl *D = dyn_cast<VarDecl>(I);
  1774. if (!D)
  1775. continue;
  1776. // FIXME: Handle array fields of structs.
  1777. if (!D->getType()->isArrayType())
  1778. continue;
  1779. const Expr *Init = D->getInit();
  1780. if (!Init)
  1781. continue;
  1782. if (!isa<StringLiteral>(Init))
  1783. continue;
  1784. Loc VarLoc = state->getLValue(D, C.getLocationContext());
  1785. const MemRegion *MR = VarLoc.getAsRegion();
  1786. if (!MR)
  1787. continue;
  1788. SVal StrVal = C.getSVal(Init);
  1789. assert(StrVal.isValid() && "Initializer string is unknown or undefined");
  1790. DefinedOrUnknownSVal strLength =
  1791. getCStringLength(C, state, Init, StrVal).castAs<DefinedOrUnknownSVal>();
  1792. state = state->set<CStringLength>(MR, strLength);
  1793. }
  1794. C.addTransition(state);
  1795. }
  1796. ProgramStateRef
  1797. CStringChecker::checkRegionChanges(ProgramStateRef state,
  1798. const InvalidatedSymbols *,
  1799. ArrayRef<const MemRegion *> ExplicitRegions,
  1800. ArrayRef<const MemRegion *> Regions,
  1801. const LocationContext *LCtx,
  1802. const CallEvent *Call) const {
  1803. CStringLengthTy Entries = state->get<CStringLength>();
  1804. if (Entries.isEmpty())
  1805. return state;
  1806. llvm::SmallPtrSet<const MemRegion *, 8> Invalidated;
  1807. llvm::SmallPtrSet<const MemRegion *, 32> SuperRegions;
  1808. // First build sets for the changed regions and their super-regions.
  1809. for (ArrayRef<const MemRegion *>::iterator
  1810. I = Regions.begin(), E = Regions.end(); I != E; ++I) {
  1811. const MemRegion *MR = *I;
  1812. Invalidated.insert(MR);
  1813. SuperRegions.insert(MR);
  1814. while (const SubRegion *SR = dyn_cast<SubRegion>(MR)) {
  1815. MR = SR->getSuperRegion();
  1816. SuperRegions.insert(MR);
  1817. }
  1818. }
  1819. CStringLengthTy::Factory &F = state->get_context<CStringLength>();
  1820. // Then loop over the entries in the current state.
  1821. for (CStringLengthTy::iterator I = Entries.begin(),
  1822. E = Entries.end(); I != E; ++I) {
  1823. const MemRegion *MR = I.getKey();
  1824. // Is this entry for a super-region of a changed region?
  1825. if (SuperRegions.count(MR)) {
  1826. Entries = F.remove(Entries, MR);
  1827. continue;
  1828. }
  1829. // Is this entry for a sub-region of a changed region?
  1830. const MemRegion *Super = MR;
  1831. while (const SubRegion *SR = dyn_cast<SubRegion>(Super)) {
  1832. Super = SR->getSuperRegion();
  1833. if (Invalidated.count(Super)) {
  1834. Entries = F.remove(Entries, MR);
  1835. break;
  1836. }
  1837. }
  1838. }
  1839. return state->set<CStringLength>(Entries);
  1840. }
  1841. void CStringChecker::checkLiveSymbols(ProgramStateRef state,
  1842. SymbolReaper &SR) const {
  1843. // Mark all symbols in our string length map as valid.
  1844. CStringLengthTy Entries = state->get<CStringLength>();
  1845. for (CStringLengthTy::iterator I = Entries.begin(), E = Entries.end();
  1846. I != E; ++I) {
  1847. SVal Len = I.getData();
  1848. for (SymExpr::symbol_iterator si = Len.symbol_begin(),
  1849. se = Len.symbol_end(); si != se; ++si)
  1850. SR.markInUse(*si);
  1851. }
  1852. }
  1853. void CStringChecker::checkDeadSymbols(SymbolReaper &SR,
  1854. CheckerContext &C) const {
  1855. if (!SR.hasDeadSymbols())
  1856. return;
  1857. ProgramStateRef state = C.getState();
  1858. CStringLengthTy Entries = state->get<CStringLength>();
  1859. if (Entries.isEmpty())
  1860. return;
  1861. CStringLengthTy::Factory &F = state->get_context<CStringLength>();
  1862. for (CStringLengthTy::iterator I = Entries.begin(), E = Entries.end();
  1863. I != E; ++I) {
  1864. SVal Len = I.getData();
  1865. if (SymbolRef Sym = Len.getAsSymbol()) {
  1866. if (SR.isDead(Sym))
  1867. Entries = F.remove(Entries, I.getKey());
  1868. }
  1869. }
  1870. state = state->set<CStringLength>(Entries);
  1871. C.addTransition(state);
  1872. }
  1873. #define REGISTER_CHECKER(name) \
  1874. void ento::register##name(CheckerManager &mgr) { \
  1875. CStringChecker *checker = mgr.registerChecker<CStringChecker>(); \
  1876. checker->Filter.Check##name = true; \
  1877. checker->Filter.CheckName##name = mgr.getCurrentCheckName(); \
  1878. }
  1879. REGISTER_CHECKER(CStringNullArg)
  1880. REGISTER_CHECKER(CStringOutOfBounds)
  1881. REGISTER_CHECKER(CStringBufferOverlap)
  1882. REGISTER_CHECKER(CStringNotNullTerm)
  1883. void ento::registerCStringCheckerBasic(CheckerManager &Mgr) {
  1884. registerCStringNullArg(Mgr);
  1885. }