CStringChecker.cpp 83 KB

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