CStringChecker.cpp 85 KB

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