CStringChecker.cpp 85 KB

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