CStringChecker.cpp 83 KB

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