CStringChecker.cpp 69 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839
  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 "clang/StaticAnalyzer/Core/Checker.h"
  16. #include "clang/StaticAnalyzer/Core/CheckerManager.h"
  17. #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
  18. #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
  19. #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
  20. #include "llvm/ADT/StringSwitch.h"
  21. using namespace clang;
  22. using namespace ento;
  23. namespace {
  24. class CStringChecker : public Checker< eval::Call,
  25. check::PreStmt<DeclStmt>,
  26. check::LiveSymbols,
  27. check::DeadSymbols,
  28. check::RegionChanges
  29. > {
  30. mutable llvm::OwningPtr<BugType> BT_Null, BT_Bounds,
  31. BT_Overlap, BT_NotCString,
  32. BT_AdditionOverflow;
  33. mutable const char *CurrentFunctionDescription;
  34. public:
  35. static void *getTag() { static int tag; return &tag; }
  36. bool evalCall(const CallExpr *CE, CheckerContext &C) const;
  37. void checkPreStmt(const DeclStmt *DS, CheckerContext &C) const;
  38. void checkLiveSymbols(const ProgramState *state, SymbolReaper &SR) const;
  39. void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const;
  40. bool wantsRegionChangeUpdate(const ProgramState *state) const;
  41. const ProgramState *
  42. checkRegionChanges(const ProgramState *state,
  43. const StoreManager::InvalidatedSymbols *,
  44. ArrayRef<const MemRegion *> ExplicitRegions,
  45. ArrayRef<const MemRegion *> Regions) const;
  46. typedef void (CStringChecker::*FnCheck)(CheckerContext &,
  47. const CallExpr *) const;
  48. void evalMemcpy(CheckerContext &C, const CallExpr *CE) const;
  49. void evalMempcpy(CheckerContext &C, const CallExpr *CE) const;
  50. void evalMemmove(CheckerContext &C, const CallExpr *CE) const;
  51. void evalBcopy(CheckerContext &C, const CallExpr *CE) const;
  52. void evalCopyCommon(CheckerContext &C, const CallExpr *CE,
  53. const ProgramState *state,
  54. const Expr *Size,
  55. const Expr *Source,
  56. const Expr *Dest,
  57. bool Restricted = false,
  58. bool IsMempcpy = false) const;
  59. void evalMemcmp(CheckerContext &C, const CallExpr *CE) const;
  60. void evalstrLength(CheckerContext &C, const CallExpr *CE) const;
  61. void evalstrnLength(CheckerContext &C, const CallExpr *CE) const;
  62. void evalstrLengthCommon(CheckerContext &C,
  63. const CallExpr *CE,
  64. bool IsStrnlen = false) const;
  65. void evalStrcpy(CheckerContext &C, const CallExpr *CE) const;
  66. void evalStrncpy(CheckerContext &C, const CallExpr *CE) const;
  67. void evalStpcpy(CheckerContext &C, const CallExpr *CE) const;
  68. void evalStrcpyCommon(CheckerContext &C,
  69. const CallExpr *CE,
  70. bool returnEnd,
  71. bool isBounded,
  72. bool isAppending) const;
  73. void evalStrcat(CheckerContext &C, const CallExpr *CE) const;
  74. void evalStrncat(CheckerContext &C, const CallExpr *CE) const;
  75. void evalStrcmp(CheckerContext &C, const CallExpr *CE) const;
  76. void evalStrncmp(CheckerContext &C, const CallExpr *CE) const;
  77. void evalStrcasecmp(CheckerContext &C, const CallExpr *CE) const;
  78. void evalStrncasecmp(CheckerContext &C, const CallExpr *CE) const;
  79. void evalStrcmpCommon(CheckerContext &C,
  80. const CallExpr *CE,
  81. bool isBounded = false,
  82. bool ignoreCase = false) const;
  83. // Utility methods
  84. std::pair<const ProgramState*, const ProgramState*>
  85. static assumeZero(CheckerContext &C,
  86. const ProgramState *state, SVal V, QualType Ty);
  87. static const ProgramState *setCStringLength(const ProgramState *state,
  88. const MemRegion *MR,
  89. SVal strLength);
  90. static SVal getCStringLengthForRegion(CheckerContext &C,
  91. const ProgramState *&state,
  92. const Expr *Ex,
  93. const MemRegion *MR,
  94. bool hypothetical);
  95. SVal getCStringLength(CheckerContext &C,
  96. const ProgramState *&state,
  97. const Expr *Ex,
  98. SVal Buf,
  99. bool hypothetical = false) const;
  100. const StringLiteral *getCStringLiteral(CheckerContext &C,
  101. const ProgramState *&state,
  102. const Expr *expr,
  103. SVal val) const;
  104. static const ProgramState *InvalidateBuffer(CheckerContext &C,
  105. const ProgramState *state,
  106. const Expr *Ex, SVal V);
  107. static bool SummarizeRegion(raw_ostream &os, ASTContext &Ctx,
  108. const MemRegion *MR);
  109. // Re-usable checks
  110. const ProgramState *checkNonNull(CheckerContext &C,
  111. const ProgramState *state,
  112. const Expr *S,
  113. SVal l) const;
  114. const ProgramState *CheckLocation(CheckerContext &C,
  115. const ProgramState *state,
  116. const Expr *S,
  117. SVal l,
  118. const char *message = NULL) const;
  119. const ProgramState *CheckBufferAccess(CheckerContext &C,
  120. const ProgramState *state,
  121. const Expr *Size,
  122. const Expr *FirstBuf,
  123. const Expr *SecondBuf,
  124. const char *firstMessage = NULL,
  125. const char *secondMessage = NULL,
  126. bool WarnAboutSize = false) const;
  127. const ProgramState *CheckBufferAccess(CheckerContext &C,
  128. const ProgramState *state,
  129. const Expr *Size,
  130. const Expr *Buf,
  131. const char *message = NULL,
  132. bool WarnAboutSize = false) const {
  133. // This is a convenience override.
  134. return CheckBufferAccess(C, state, Size, Buf, NULL, message, NULL,
  135. WarnAboutSize);
  136. }
  137. const ProgramState *CheckOverlap(CheckerContext &C,
  138. const ProgramState *state,
  139. const Expr *Size,
  140. const Expr *First,
  141. const Expr *Second) const;
  142. void emitOverlapBug(CheckerContext &C,
  143. const ProgramState *state,
  144. const Stmt *First,
  145. const Stmt *Second) const;
  146. const ProgramState *checkAdditionOverflow(CheckerContext &C,
  147. const ProgramState *state,
  148. NonLoc left,
  149. NonLoc right) const;
  150. };
  151. class CStringLength {
  152. public:
  153. typedef llvm::ImmutableMap<const MemRegion *, SVal> EntryMap;
  154. };
  155. } //end anonymous namespace
  156. namespace clang {
  157. namespace ento {
  158. template <>
  159. struct ProgramStateTrait<CStringLength>
  160. : public ProgramStatePartialTrait<CStringLength::EntryMap> {
  161. static void *GDMIndex() { return CStringChecker::getTag(); }
  162. };
  163. }
  164. }
  165. //===----------------------------------------------------------------------===//
  166. // Individual checks and utility methods.
  167. //===----------------------------------------------------------------------===//
  168. std::pair<const ProgramState*, const ProgramState*>
  169. CStringChecker::assumeZero(CheckerContext &C, const ProgramState *state, SVal V,
  170. QualType Ty) {
  171. DefinedSVal *val = dyn_cast<DefinedSVal>(&V);
  172. if (!val)
  173. return std::pair<const ProgramState*, const ProgramState *>(state, state);
  174. SValBuilder &svalBuilder = C.getSValBuilder();
  175. DefinedOrUnknownSVal zero = svalBuilder.makeZeroVal(Ty);
  176. return state->assume(svalBuilder.evalEQ(state, *val, zero));
  177. }
  178. const ProgramState *CStringChecker::checkNonNull(CheckerContext &C,
  179. const ProgramState *state,
  180. const Expr *S, SVal l) const {
  181. // If a previous check has failed, propagate the failure.
  182. if (!state)
  183. return NULL;
  184. const ProgramState *stateNull, *stateNonNull;
  185. llvm::tie(stateNull, stateNonNull) = assumeZero(C, state, l, S->getType());
  186. if (stateNull && !stateNonNull) {
  187. ExplodedNode *N = C.generateSink(stateNull);
  188. if (!N)
  189. return NULL;
  190. if (!BT_Null)
  191. BT_Null.reset(new BuiltinBug("API",
  192. "Null pointer argument in call to byte string function"));
  193. llvm::SmallString<80> buf;
  194. llvm::raw_svector_ostream os(buf);
  195. assert(CurrentFunctionDescription);
  196. os << "Null pointer argument in call to " << CurrentFunctionDescription;
  197. // Generate a report for this bug.
  198. BuiltinBug *BT = static_cast<BuiltinBug*>(BT_Null.get());
  199. BugReport *report = new BugReport(*BT, os.str(), N);
  200. report->addRange(S->getSourceRange());
  201. report->addVisitor(bugreporter::getTrackNullOrUndefValueVisitor(N, S));
  202. C.EmitReport(report);
  203. return NULL;
  204. }
  205. // From here on, assume that the value is non-null.
  206. assert(stateNonNull);
  207. return stateNonNull;
  208. }
  209. // FIXME: This was originally copied from ArrayBoundChecker.cpp. Refactor?
  210. const ProgramState *CStringChecker::CheckLocation(CheckerContext &C,
  211. const ProgramState *state,
  212. const Expr *S, SVal l,
  213. const char *warningMsg) const {
  214. // If a previous check has failed, propagate the failure.
  215. if (!state)
  216. return NULL;
  217. // Check for out of bound array element access.
  218. const MemRegion *R = l.getAsRegion();
  219. if (!R)
  220. return state;
  221. const ElementRegion *ER = dyn_cast<ElementRegion>(R);
  222. if (!ER)
  223. return state;
  224. assert(ER->getValueType() == C.getASTContext().CharTy &&
  225. "CheckLocation should only be called with char* ElementRegions");
  226. // Get the size of the array.
  227. const SubRegion *superReg = cast<SubRegion>(ER->getSuperRegion());
  228. SValBuilder &svalBuilder = C.getSValBuilder();
  229. SVal Extent =
  230. svalBuilder.convertToArrayIndex(superReg->getExtent(svalBuilder));
  231. DefinedOrUnknownSVal Size = cast<DefinedOrUnknownSVal>(Extent);
  232. // Get the index of the accessed element.
  233. DefinedOrUnknownSVal Idx = cast<DefinedOrUnknownSVal>(ER->getIndex());
  234. const ProgramState *StInBound = state->assumeInBound(Idx, Size, true);
  235. const ProgramState *StOutBound = state->assumeInBound(Idx, Size, false);
  236. if (StOutBound && !StInBound) {
  237. ExplodedNode *N = C.generateSink(StOutBound);
  238. if (!N)
  239. return NULL;
  240. if (!BT_Bounds) {
  241. BT_Bounds.reset(new BuiltinBug("Out-of-bound array access",
  242. "Byte string function accesses out-of-bound array element"));
  243. }
  244. BuiltinBug *BT = static_cast<BuiltinBug*>(BT_Bounds.get());
  245. // Generate a report for this bug.
  246. BugReport *report;
  247. if (warningMsg) {
  248. report = new BugReport(*BT, warningMsg, N);
  249. } else {
  250. assert(CurrentFunctionDescription);
  251. assert(CurrentFunctionDescription[0] != '\0');
  252. llvm::SmallString<80> buf;
  253. llvm::raw_svector_ostream os(buf);
  254. os << (char)toupper(CurrentFunctionDescription[0])
  255. << &CurrentFunctionDescription[1]
  256. << " accesses out-of-bound array element";
  257. report = new BugReport(*BT, os.str(), N);
  258. }
  259. // FIXME: It would be nice to eventually make this diagnostic more clear,
  260. // e.g., by referencing the original declaration or by saying *why* this
  261. // reference is outside the range.
  262. report->addRange(S->getSourceRange());
  263. C.EmitReport(report);
  264. return NULL;
  265. }
  266. // Array bound check succeeded. From this point forward the array bound
  267. // should always succeed.
  268. return StInBound;
  269. }
  270. const ProgramState *CStringChecker::CheckBufferAccess(CheckerContext &C,
  271. const ProgramState *state,
  272. const Expr *Size,
  273. const Expr *FirstBuf,
  274. const Expr *SecondBuf,
  275. const char *firstMessage,
  276. const char *secondMessage,
  277. bool WarnAboutSize) const {
  278. // If a previous check has failed, propagate the failure.
  279. if (!state)
  280. return NULL;
  281. SValBuilder &svalBuilder = C.getSValBuilder();
  282. ASTContext &Ctx = svalBuilder.getContext();
  283. QualType sizeTy = Size->getType();
  284. QualType PtrTy = Ctx.getPointerType(Ctx.CharTy);
  285. // Check that the first buffer is non-null.
  286. SVal BufVal = state->getSVal(FirstBuf);
  287. state = checkNonNull(C, state, FirstBuf, BufVal);
  288. if (!state)
  289. return NULL;
  290. // Get the access length and make sure it is known.
  291. // FIXME: This assumes the caller has already checked that the access length
  292. // is positive. And that it's unsigned.
  293. SVal LengthVal = state->getSVal(Size);
  294. NonLoc *Length = dyn_cast<NonLoc>(&LengthVal);
  295. if (!Length)
  296. return state;
  297. // Compute the offset of the last element to be accessed: size-1.
  298. NonLoc One = cast<NonLoc>(svalBuilder.makeIntVal(1, sizeTy));
  299. NonLoc LastOffset = cast<NonLoc>(svalBuilder.evalBinOpNN(state, BO_Sub,
  300. *Length, One, sizeTy));
  301. // Check that the first buffer is sufficiently long.
  302. SVal BufStart = svalBuilder.evalCast(BufVal, PtrTy, FirstBuf->getType());
  303. if (Loc *BufLoc = dyn_cast<Loc>(&BufStart)) {
  304. const Expr *warningExpr = (WarnAboutSize ? Size : FirstBuf);
  305. SVal BufEnd = svalBuilder.evalBinOpLN(state, BO_Add, *BufLoc,
  306. LastOffset, PtrTy);
  307. state = CheckLocation(C, state, warningExpr, BufEnd, firstMessage);
  308. // If the buffer isn't large enough, abort.
  309. if (!state)
  310. return NULL;
  311. }
  312. // If there's a second buffer, check it as well.
  313. if (SecondBuf) {
  314. BufVal = state->getSVal(SecondBuf);
  315. state = checkNonNull(C, state, SecondBuf, BufVal);
  316. if (!state)
  317. return NULL;
  318. BufStart = svalBuilder.evalCast(BufVal, PtrTy, SecondBuf->getType());
  319. if (Loc *BufLoc = dyn_cast<Loc>(&BufStart)) {
  320. const Expr *warningExpr = (WarnAboutSize ? Size : SecondBuf);
  321. SVal BufEnd = svalBuilder.evalBinOpLN(state, BO_Add, *BufLoc,
  322. LastOffset, PtrTy);
  323. state = CheckLocation(C, state, warningExpr, BufEnd, secondMessage);
  324. }
  325. }
  326. // Large enough or not, return this state!
  327. return state;
  328. }
  329. const ProgramState *CStringChecker::CheckOverlap(CheckerContext &C,
  330. const ProgramState *state,
  331. const Expr *Size,
  332. const Expr *First,
  333. const Expr *Second) const {
  334. // Do a simple check for overlap: if the two arguments are from the same
  335. // buffer, see if the end of the first is greater than the start of the second
  336. // or vice versa.
  337. // If a previous check has failed, propagate the failure.
  338. if (!state)
  339. return NULL;
  340. const ProgramState *stateTrue, *stateFalse;
  341. // Get the buffer values and make sure they're known locations.
  342. SVal firstVal = state->getSVal(First);
  343. SVal secondVal = state->getSVal(Second);
  344. Loc *firstLoc = dyn_cast<Loc>(&firstVal);
  345. if (!firstLoc)
  346. return state;
  347. Loc *secondLoc = dyn_cast<Loc>(&secondVal);
  348. if (!secondLoc)
  349. return state;
  350. // Are the two values the same?
  351. SValBuilder &svalBuilder = C.getSValBuilder();
  352. llvm::tie(stateTrue, stateFalse) =
  353. state->assume(svalBuilder.evalEQ(state, *firstLoc, *secondLoc));
  354. if (stateTrue && !stateFalse) {
  355. // If the values are known to be equal, that's automatically an overlap.
  356. emitOverlapBug(C, stateTrue, First, Second);
  357. return NULL;
  358. }
  359. // assume the two expressions are not equal.
  360. assert(stateFalse);
  361. state = stateFalse;
  362. // Which value comes first?
  363. QualType cmpTy = svalBuilder.getConditionType();
  364. SVal reverse = svalBuilder.evalBinOpLL(state, BO_GT,
  365. *firstLoc, *secondLoc, cmpTy);
  366. DefinedOrUnknownSVal *reverseTest = dyn_cast<DefinedOrUnknownSVal>(&reverse);
  367. if (!reverseTest)
  368. return state;
  369. llvm::tie(stateTrue, stateFalse) = state->assume(*reverseTest);
  370. if (stateTrue) {
  371. if (stateFalse) {
  372. // If we don't know which one comes first, we can't perform this test.
  373. return state;
  374. } else {
  375. // Switch the values so that firstVal is before secondVal.
  376. Loc *tmpLoc = firstLoc;
  377. firstLoc = secondLoc;
  378. secondLoc = tmpLoc;
  379. // Switch the Exprs as well, so that they still correspond.
  380. const Expr *tmpExpr = First;
  381. First = Second;
  382. Second = tmpExpr;
  383. }
  384. }
  385. // Get the length, and make sure it too is known.
  386. SVal LengthVal = state->getSVal(Size);
  387. NonLoc *Length = dyn_cast<NonLoc>(&LengthVal);
  388. if (!Length)
  389. return state;
  390. // Convert the first buffer's start address to char*.
  391. // Bail out if the cast fails.
  392. ASTContext &Ctx = svalBuilder.getContext();
  393. QualType CharPtrTy = Ctx.getPointerType(Ctx.CharTy);
  394. SVal FirstStart = svalBuilder.evalCast(*firstLoc, CharPtrTy,
  395. First->getType());
  396. Loc *FirstStartLoc = dyn_cast<Loc>(&FirstStart);
  397. if (!FirstStartLoc)
  398. return state;
  399. // Compute the end of the first buffer. Bail out if THAT fails.
  400. SVal FirstEnd = svalBuilder.evalBinOpLN(state, BO_Add,
  401. *FirstStartLoc, *Length, CharPtrTy);
  402. Loc *FirstEndLoc = dyn_cast<Loc>(&FirstEnd);
  403. if (!FirstEndLoc)
  404. return state;
  405. // Is the end of the first buffer past the start of the second buffer?
  406. SVal Overlap = svalBuilder.evalBinOpLL(state, BO_GT,
  407. *FirstEndLoc, *secondLoc, cmpTy);
  408. DefinedOrUnknownSVal *OverlapTest = dyn_cast<DefinedOrUnknownSVal>(&Overlap);
  409. if (!OverlapTest)
  410. return state;
  411. llvm::tie(stateTrue, stateFalse) = state->assume(*OverlapTest);
  412. if (stateTrue && !stateFalse) {
  413. // Overlap!
  414. emitOverlapBug(C, stateTrue, First, Second);
  415. return NULL;
  416. }
  417. // assume the two expressions don't overlap.
  418. assert(stateFalse);
  419. return stateFalse;
  420. }
  421. void CStringChecker::emitOverlapBug(CheckerContext &C, const ProgramState *state,
  422. const Stmt *First, const Stmt *Second) const {
  423. ExplodedNode *N = C.generateSink(state);
  424. if (!N)
  425. return;
  426. if (!BT_Overlap)
  427. BT_Overlap.reset(new BugType("Unix API", "Improper arguments"));
  428. // Generate a report for this bug.
  429. BugReport *report =
  430. new BugReport(*BT_Overlap,
  431. "Arguments must not be overlapping buffers", N);
  432. report->addRange(First->getSourceRange());
  433. report->addRange(Second->getSourceRange());
  434. C.EmitReport(report);
  435. }
  436. const ProgramState *CStringChecker::checkAdditionOverflow(CheckerContext &C,
  437. const ProgramState *state,
  438. NonLoc left,
  439. NonLoc right) const {
  440. // If a previous check has failed, propagate the failure.
  441. if (!state)
  442. return NULL;
  443. SValBuilder &svalBuilder = C.getSValBuilder();
  444. BasicValueFactory &BVF = svalBuilder.getBasicValueFactory();
  445. QualType sizeTy = svalBuilder.getContext().getSizeType();
  446. const llvm::APSInt &maxValInt = BVF.getMaxValue(sizeTy);
  447. NonLoc maxVal = svalBuilder.makeIntVal(maxValInt);
  448. SVal maxMinusRight = svalBuilder.evalBinOpNN(state, BO_Sub, maxVal, right,
  449. sizeTy);
  450. if (maxMinusRight.isUnknownOrUndef()) {
  451. // Try switching the operands. (The order of these two assignments is
  452. // important!)
  453. maxMinusRight = svalBuilder.evalBinOpNN(state, BO_Sub, maxVal, left,
  454. sizeTy);
  455. left = right;
  456. }
  457. if (NonLoc *maxMinusRightNL = dyn_cast<NonLoc>(&maxMinusRight)) {
  458. QualType cmpTy = svalBuilder.getConditionType();
  459. // If left > max - right, we have an overflow.
  460. SVal willOverflow = svalBuilder.evalBinOpNN(state, BO_GT, left,
  461. *maxMinusRightNL, cmpTy);
  462. const ProgramState *stateOverflow, *stateOkay;
  463. llvm::tie(stateOverflow, stateOkay) =
  464. state->assume(cast<DefinedOrUnknownSVal>(willOverflow));
  465. if (stateOverflow && !stateOkay) {
  466. // We have an overflow. Emit a bug report.
  467. ExplodedNode *N = C.generateSink(stateOverflow);
  468. if (!N)
  469. return NULL;
  470. if (!BT_AdditionOverflow)
  471. BT_AdditionOverflow.reset(new BuiltinBug("API",
  472. "Sum of expressions causes overflow"));
  473. // This isn't a great error message, but this should never occur in real
  474. // code anyway -- you'd have to create a buffer longer than a size_t can
  475. // represent, which is sort of a contradiction.
  476. const char *warning =
  477. "This expression will create a string whose length is too big to "
  478. "be represented as a size_t";
  479. // Generate a report for this bug.
  480. BugReport *report = new BugReport(*BT_AdditionOverflow, warning, N);
  481. C.EmitReport(report);
  482. return NULL;
  483. }
  484. // From now on, assume an overflow didn't occur.
  485. assert(stateOkay);
  486. state = stateOkay;
  487. }
  488. return state;
  489. }
  490. const ProgramState *CStringChecker::setCStringLength(const ProgramState *state,
  491. const MemRegion *MR,
  492. SVal strLength) {
  493. assert(!strLength.isUndef() && "Attempt to set an undefined string length");
  494. MR = MR->StripCasts();
  495. switch (MR->getKind()) {
  496. case MemRegion::StringRegionKind:
  497. // FIXME: This can happen if we strcpy() into a string region. This is
  498. // undefined [C99 6.4.5p6], but we should still warn about it.
  499. return state;
  500. case MemRegion::SymbolicRegionKind:
  501. case MemRegion::AllocaRegionKind:
  502. case MemRegion::VarRegionKind:
  503. case MemRegion::FieldRegionKind:
  504. case MemRegion::ObjCIvarRegionKind:
  505. // These are the types we can currently track string lengths for.
  506. break;
  507. case MemRegion::ElementRegionKind:
  508. // FIXME: Handle element regions by upper-bounding the parent region's
  509. // string length.
  510. return state;
  511. default:
  512. // Other regions (mostly non-data) can't have a reliable C string length.
  513. // For now, just ignore the change.
  514. // FIXME: These are rare but not impossible. We should output some kind of
  515. // warning for things like strcpy((char[]){'a', 0}, "b");
  516. return state;
  517. }
  518. if (strLength.isUnknown())
  519. return state->remove<CStringLength>(MR);
  520. return state->set<CStringLength>(MR, strLength);
  521. }
  522. SVal CStringChecker::getCStringLengthForRegion(CheckerContext &C,
  523. const ProgramState *&state,
  524. const Expr *Ex,
  525. const MemRegion *MR,
  526. bool hypothetical) {
  527. if (!hypothetical) {
  528. // If there's a recorded length, go ahead and return it.
  529. const SVal *Recorded = state->get<CStringLength>(MR);
  530. if (Recorded)
  531. return *Recorded;
  532. }
  533. // Otherwise, get a new symbol and update the state.
  534. unsigned Count = C.getCurrentBlockCount();
  535. SValBuilder &svalBuilder = C.getSValBuilder();
  536. QualType sizeTy = svalBuilder.getContext().getSizeType();
  537. SVal strLength = svalBuilder.getMetadataSymbolVal(CStringChecker::getTag(),
  538. MR, Ex, sizeTy, Count);
  539. if (!hypothetical)
  540. state = state->set<CStringLength>(MR, strLength);
  541. return strLength;
  542. }
  543. SVal CStringChecker::getCStringLength(CheckerContext &C, const ProgramState *&state,
  544. const Expr *Ex, SVal Buf,
  545. bool hypothetical) const {
  546. const MemRegion *MR = Buf.getAsRegion();
  547. if (!MR) {
  548. // If we can't get a region, see if it's something we /know/ isn't a
  549. // C string. In the context of locations, the only time we can issue such
  550. // a warning is for labels.
  551. if (loc::GotoLabel *Label = dyn_cast<loc::GotoLabel>(&Buf)) {
  552. if (ExplodedNode *N = C.addTransition(state)) {
  553. if (!BT_NotCString)
  554. BT_NotCString.reset(new BuiltinBug("API",
  555. "Argument is not a null-terminated string."));
  556. llvm::SmallString<120> buf;
  557. llvm::raw_svector_ostream os(buf);
  558. assert(CurrentFunctionDescription);
  559. os << "Argument to " << CurrentFunctionDescription
  560. << " is the address of the label '" << Label->getLabel()->getName()
  561. << "', which is not a null-terminated string";
  562. // Generate a report for this bug.
  563. BugReport *report = new BugReport(*BT_NotCString,
  564. os.str(), N);
  565. report->addRange(Ex->getSourceRange());
  566. C.EmitReport(report);
  567. }
  568. return UndefinedVal();
  569. }
  570. // If it's not a region and not a label, give up.
  571. return UnknownVal();
  572. }
  573. // If we have a region, strip casts from it and see if we can figure out
  574. // its length. For anything we can't figure out, just return UnknownVal.
  575. MR = MR->StripCasts();
  576. switch (MR->getKind()) {
  577. case MemRegion::StringRegionKind: {
  578. // Modifying the contents of string regions is undefined [C99 6.4.5p6],
  579. // so we can assume that the byte length is the correct C string length.
  580. SValBuilder &svalBuilder = C.getSValBuilder();
  581. QualType sizeTy = svalBuilder.getContext().getSizeType();
  582. const StringLiteral *strLit = cast<StringRegion>(MR)->getStringLiteral();
  583. return svalBuilder.makeIntVal(strLit->getByteLength(), sizeTy);
  584. }
  585. case MemRegion::SymbolicRegionKind:
  586. case MemRegion::AllocaRegionKind:
  587. case MemRegion::VarRegionKind:
  588. case MemRegion::FieldRegionKind:
  589. case MemRegion::ObjCIvarRegionKind:
  590. return getCStringLengthForRegion(C, state, Ex, MR, hypothetical);
  591. case MemRegion::CompoundLiteralRegionKind:
  592. // FIXME: Can we track this? Is it necessary?
  593. return UnknownVal();
  594. case MemRegion::ElementRegionKind:
  595. // FIXME: How can we handle this? It's not good enough to subtract the
  596. // offset from the base string length; consider "123\x00567" and &a[5].
  597. return UnknownVal();
  598. default:
  599. // Other regions (mostly non-data) can't have a reliable C string length.
  600. // In this case, an error is emitted and UndefinedVal is returned.
  601. // The caller should always be prepared to handle this case.
  602. if (ExplodedNode *N = C.addTransition(state)) {
  603. if (!BT_NotCString)
  604. BT_NotCString.reset(new BuiltinBug("API",
  605. "Argument is not a null-terminated string."));
  606. llvm::SmallString<120> buf;
  607. llvm::raw_svector_ostream os(buf);
  608. assert(CurrentFunctionDescription);
  609. os << "Argument to " << CurrentFunctionDescription << " is ";
  610. if (SummarizeRegion(os, C.getASTContext(), MR))
  611. os << ", which is not a null-terminated string";
  612. else
  613. os << "not a null-terminated string";
  614. // Generate a report for this bug.
  615. BugReport *report = new BugReport(*BT_NotCString,
  616. os.str(), N);
  617. report->addRange(Ex->getSourceRange());
  618. C.EmitReport(report);
  619. }
  620. return UndefinedVal();
  621. }
  622. }
  623. const StringLiteral *CStringChecker::getCStringLiteral(CheckerContext &C,
  624. const ProgramState *&state, const Expr *expr, SVal val) const {
  625. // Get the memory region pointed to by the val.
  626. const MemRegion *bufRegion = val.getAsRegion();
  627. if (!bufRegion)
  628. return NULL;
  629. // Strip casts off the memory region.
  630. bufRegion = bufRegion->StripCasts();
  631. // Cast the memory region to a string region.
  632. const StringRegion *strRegion= dyn_cast<StringRegion>(bufRegion);
  633. if (!strRegion)
  634. return NULL;
  635. // Return the actual string in the string region.
  636. return strRegion->getStringLiteral();
  637. }
  638. const ProgramState *CStringChecker::InvalidateBuffer(CheckerContext &C,
  639. const ProgramState *state,
  640. const Expr *E, SVal V) {
  641. Loc *L = dyn_cast<Loc>(&V);
  642. if (!L)
  643. return state;
  644. // FIXME: This is a simplified version of what's in CFRefCount.cpp -- it makes
  645. // some assumptions about the value that CFRefCount can't. Even so, it should
  646. // probably be refactored.
  647. if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(L)) {
  648. const MemRegion *R = MR->getRegion()->StripCasts();
  649. // Are we dealing with an ElementRegion? If so, we should be invalidating
  650. // the super-region.
  651. if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
  652. R = ER->getSuperRegion();
  653. // FIXME: What about layers of ElementRegions?
  654. }
  655. // Invalidate this region.
  656. unsigned Count = C.getCurrentBlockCount();
  657. return state->invalidateRegions(R, E, Count);
  658. }
  659. // If we have a non-region value by chance, just remove the binding.
  660. // FIXME: is this necessary or correct? This handles the non-Region
  661. // cases. Is it ever valid to store to these?
  662. return state->unbindLoc(*L);
  663. }
  664. bool CStringChecker::SummarizeRegion(raw_ostream &os, ASTContext &Ctx,
  665. const MemRegion *MR) {
  666. const TypedValueRegion *TVR = dyn_cast<TypedValueRegion>(MR);
  667. switch (MR->getKind()) {
  668. case MemRegion::FunctionTextRegionKind: {
  669. const FunctionDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
  670. if (FD)
  671. os << "the address of the function '" << *FD << '\'';
  672. else
  673. os << "the address of a function";
  674. return true;
  675. }
  676. case MemRegion::BlockTextRegionKind:
  677. os << "block text";
  678. return true;
  679. case MemRegion::BlockDataRegionKind:
  680. os << "a block";
  681. return true;
  682. case MemRegion::CXXThisRegionKind:
  683. case MemRegion::CXXTempObjectRegionKind:
  684. os << "a C++ temp object of type " << TVR->getValueType().getAsString();
  685. return true;
  686. case MemRegion::VarRegionKind:
  687. os << "a variable of type" << TVR->getValueType().getAsString();
  688. return true;
  689. case MemRegion::FieldRegionKind:
  690. os << "a field of type " << TVR->getValueType().getAsString();
  691. return true;
  692. case MemRegion::ObjCIvarRegionKind:
  693. os << "an instance variable of type " << TVR->getValueType().getAsString();
  694. return true;
  695. default:
  696. return false;
  697. }
  698. }
  699. //===----------------------------------------------------------------------===//
  700. // evaluation of individual function calls.
  701. //===----------------------------------------------------------------------===//
  702. void CStringChecker::evalCopyCommon(CheckerContext &C,
  703. const CallExpr *CE,
  704. const ProgramState *state,
  705. const Expr *Size, const Expr *Dest,
  706. const Expr *Source, bool Restricted,
  707. bool IsMempcpy) const {
  708. CurrentFunctionDescription = "memory copy function";
  709. // See if the size argument is zero.
  710. SVal sizeVal = state->getSVal(Size);
  711. QualType sizeTy = Size->getType();
  712. const ProgramState *stateZeroSize, *stateNonZeroSize;
  713. llvm::tie(stateZeroSize, stateNonZeroSize) =
  714. assumeZero(C, state, sizeVal, sizeTy);
  715. // Get the value of the Dest.
  716. SVal destVal = state->getSVal(Dest);
  717. // If the size is zero, there won't be any actual memory access, so
  718. // just bind the return value to the destination buffer and return.
  719. if (stateZeroSize) {
  720. stateZeroSize = stateZeroSize->BindExpr(CE, destVal);
  721. C.addTransition(stateZeroSize);
  722. }
  723. // If the size can be nonzero, we have to check the other arguments.
  724. if (stateNonZeroSize) {
  725. state = stateNonZeroSize;
  726. // Ensure the destination is not null. If it is NULL there will be a
  727. // NULL pointer dereference.
  728. state = checkNonNull(C, state, Dest, destVal);
  729. if (!state)
  730. return;
  731. // Get the value of the Src.
  732. SVal srcVal = state->getSVal(Source);
  733. // Ensure the source is not null. If it is NULL there will be a
  734. // NULL pointer dereference.
  735. state = checkNonNull(C, state, Source, srcVal);
  736. if (!state)
  737. return;
  738. // Ensure the accesses are valid and that the buffers do not overlap.
  739. const char * const writeWarning =
  740. "Memory copy function overflows destination buffer";
  741. state = CheckBufferAccess(C, state, Size, Dest, Source,
  742. writeWarning, /* sourceWarning = */ NULL);
  743. if (Restricted)
  744. state = CheckOverlap(C, state, Size, Dest, Source);
  745. if (!state)
  746. return;
  747. // If this is mempcpy, get the byte after the last byte copied and
  748. // bind the expr.
  749. if (IsMempcpy) {
  750. loc::MemRegionVal *destRegVal = dyn_cast<loc::MemRegionVal>(&destVal);
  751. assert(destRegVal && "Destination should be a known MemRegionVal here");
  752. // Get the length to copy.
  753. NonLoc *lenValNonLoc = dyn_cast<NonLoc>(&sizeVal);
  754. if (lenValNonLoc) {
  755. // Get the byte after the last byte copied.
  756. SVal lastElement = C.getSValBuilder().evalBinOpLN(state, BO_Add,
  757. *destRegVal,
  758. *lenValNonLoc,
  759. Dest->getType());
  760. // The byte after the last byte copied is the return value.
  761. state = state->BindExpr(CE, lastElement);
  762. } else {
  763. // If we don't know how much we copied, we can at least
  764. // conjure a return value for later.
  765. unsigned Count = C.getCurrentBlockCount();
  766. SVal result =
  767. C.getSValBuilder().getConjuredSymbolVal(NULL, CE, Count);
  768. state = state->BindExpr(CE, result);
  769. }
  770. } else {
  771. // All other copies return the destination buffer.
  772. // (Well, bcopy() has a void return type, but this won't hurt.)
  773. state = state->BindExpr(CE, destVal);
  774. }
  775. // Invalidate the destination.
  776. // FIXME: Even if we can't perfectly model the copy, we should see if we
  777. // can use LazyCompoundVals to copy the source values into the destination.
  778. // This would probably remove any existing bindings past the end of the
  779. // copied region, but that's still an improvement over blank invalidation.
  780. state = InvalidateBuffer(C, state, Dest, state->getSVal(Dest));
  781. C.addTransition(state);
  782. }
  783. }
  784. void CStringChecker::evalMemcpy(CheckerContext &C, const CallExpr *CE) const {
  785. // void *memcpy(void *restrict dst, const void *restrict src, size_t n);
  786. // The return value is the address of the destination buffer.
  787. const Expr *Dest = CE->getArg(0);
  788. const ProgramState *state = C.getState();
  789. evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1), true);
  790. }
  791. void CStringChecker::evalMempcpy(CheckerContext &C, const CallExpr *CE) const {
  792. // void *mempcpy(void *restrict dst, const void *restrict src, size_t n);
  793. // The return value is a pointer to the byte following the last written byte.
  794. const Expr *Dest = CE->getArg(0);
  795. const ProgramState *state = C.getState();
  796. evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1), true, true);
  797. }
  798. void CStringChecker::evalMemmove(CheckerContext &C, const CallExpr *CE) const {
  799. // void *memmove(void *dst, const void *src, size_t n);
  800. // The return value is the address of the destination buffer.
  801. const Expr *Dest = CE->getArg(0);
  802. const ProgramState *state = C.getState();
  803. evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1));
  804. }
  805. void CStringChecker::evalBcopy(CheckerContext &C, const CallExpr *CE) const {
  806. // void bcopy(const void *src, void *dst, size_t n);
  807. evalCopyCommon(C, CE, C.getState(),
  808. CE->getArg(2), CE->getArg(1), CE->getArg(0));
  809. }
  810. void CStringChecker::evalMemcmp(CheckerContext &C, const CallExpr *CE) const {
  811. // int memcmp(const void *s1, const void *s2, size_t n);
  812. CurrentFunctionDescription = "memory comparison function";
  813. const Expr *Left = CE->getArg(0);
  814. const Expr *Right = CE->getArg(1);
  815. const Expr *Size = CE->getArg(2);
  816. const ProgramState *state = C.getState();
  817. SValBuilder &svalBuilder = C.getSValBuilder();
  818. // See if the size argument is zero.
  819. SVal sizeVal = state->getSVal(Size);
  820. QualType sizeTy = Size->getType();
  821. const ProgramState *stateZeroSize, *stateNonZeroSize;
  822. llvm::tie(stateZeroSize, stateNonZeroSize) =
  823. assumeZero(C, state, sizeVal, sizeTy);
  824. // If the size can be zero, the result will be 0 in that case, and we don't
  825. // have to check either of the buffers.
  826. if (stateZeroSize) {
  827. state = stateZeroSize;
  828. state = state->BindExpr(CE, svalBuilder.makeZeroVal(CE->getType()));
  829. C.addTransition(state);
  830. }
  831. // If the size can be nonzero, we have to check the other arguments.
  832. if (stateNonZeroSize) {
  833. state = stateNonZeroSize;
  834. // If we know the two buffers are the same, we know the result is 0.
  835. // First, get the two buffers' addresses. Another checker will have already
  836. // made sure they're not undefined.
  837. DefinedOrUnknownSVal LV = cast<DefinedOrUnknownSVal>(state->getSVal(Left));
  838. DefinedOrUnknownSVal RV = cast<DefinedOrUnknownSVal>(state->getSVal(Right));
  839. // See if they are the same.
  840. DefinedOrUnknownSVal SameBuf = svalBuilder.evalEQ(state, LV, RV);
  841. const ProgramState *StSameBuf, *StNotSameBuf;
  842. llvm::tie(StSameBuf, StNotSameBuf) = state->assume(SameBuf);
  843. // If the two arguments might be the same buffer, we know the result is 0,
  844. // and we only need to check one size.
  845. if (StSameBuf) {
  846. state = StSameBuf;
  847. state = CheckBufferAccess(C, state, Size, Left);
  848. if (state) {
  849. state = StSameBuf->BindExpr(CE, svalBuilder.makeZeroVal(CE->getType()));
  850. C.addTransition(state);
  851. }
  852. }
  853. // If the two arguments might be different buffers, we have to check the
  854. // size of both of them.
  855. if (StNotSameBuf) {
  856. state = StNotSameBuf;
  857. state = CheckBufferAccess(C, state, Size, Left, Right);
  858. if (state) {
  859. // The return value is the comparison result, which we don't know.
  860. unsigned Count = C.getCurrentBlockCount();
  861. SVal CmpV = svalBuilder.getConjuredSymbolVal(NULL, CE, Count);
  862. state = state->BindExpr(CE, CmpV);
  863. C.addTransition(state);
  864. }
  865. }
  866. }
  867. }
  868. void CStringChecker::evalstrLength(CheckerContext &C,
  869. const CallExpr *CE) const {
  870. // size_t strlen(const char *s);
  871. evalstrLengthCommon(C, CE, /* IsStrnlen = */ false);
  872. }
  873. void CStringChecker::evalstrnLength(CheckerContext &C,
  874. const CallExpr *CE) const {
  875. // size_t strnlen(const char *s, size_t maxlen);
  876. evalstrLengthCommon(C, CE, /* IsStrnlen = */ true);
  877. }
  878. void CStringChecker::evalstrLengthCommon(CheckerContext &C, const CallExpr *CE,
  879. bool IsStrnlen) const {
  880. CurrentFunctionDescription = "string length function";
  881. const ProgramState *state = C.getState();
  882. if (IsStrnlen) {
  883. const Expr *maxlenExpr = CE->getArg(1);
  884. SVal maxlenVal = state->getSVal(maxlenExpr);
  885. const ProgramState *stateZeroSize, *stateNonZeroSize;
  886. llvm::tie(stateZeroSize, stateNonZeroSize) =
  887. assumeZero(C, state, maxlenVal, maxlenExpr->getType());
  888. // If the size can be zero, the result will be 0 in that case, and we don't
  889. // have to check the string itself.
  890. if (stateZeroSize) {
  891. SVal zero = C.getSValBuilder().makeZeroVal(CE->getType());
  892. stateZeroSize = stateZeroSize->BindExpr(CE, zero);
  893. C.addTransition(stateZeroSize);
  894. }
  895. // If the size is GUARANTEED to be zero, we're done!
  896. if (!stateNonZeroSize)
  897. return;
  898. // Otherwise, record the assumption that the size is nonzero.
  899. state = stateNonZeroSize;
  900. }
  901. // Check that the string argument is non-null.
  902. const Expr *Arg = CE->getArg(0);
  903. SVal ArgVal = state->getSVal(Arg);
  904. state = checkNonNull(C, state, Arg, ArgVal);
  905. if (!state)
  906. return;
  907. SVal strLength = getCStringLength(C, state, Arg, ArgVal);
  908. // If the argument isn't a valid C string, there's no valid state to
  909. // transition to.
  910. if (strLength.isUndef())
  911. return;
  912. DefinedOrUnknownSVal result = UnknownVal();
  913. // If the check is for strnlen() then bind the return value to no more than
  914. // the maxlen value.
  915. if (IsStrnlen) {
  916. QualType cmpTy = C.getSValBuilder().getConditionType();
  917. // It's a little unfortunate to be getting this again,
  918. // but it's not that expensive...
  919. const Expr *maxlenExpr = CE->getArg(1);
  920. SVal maxlenVal = state->getSVal(maxlenExpr);
  921. NonLoc *strLengthNL = dyn_cast<NonLoc>(&strLength);
  922. NonLoc *maxlenValNL = dyn_cast<NonLoc>(&maxlenVal);
  923. if (strLengthNL && maxlenValNL) {
  924. const ProgramState *stateStringTooLong, *stateStringNotTooLong;
  925. // Check if the strLength is greater than the maxlen.
  926. llvm::tie(stateStringTooLong, stateStringNotTooLong) =
  927. state->assume(cast<DefinedOrUnknownSVal>
  928. (C.getSValBuilder().evalBinOpNN(state, BO_GT,
  929. *strLengthNL,
  930. *maxlenValNL,
  931. cmpTy)));
  932. if (stateStringTooLong && !stateStringNotTooLong) {
  933. // If the string is longer than maxlen, return maxlen.
  934. result = *maxlenValNL;
  935. } else if (stateStringNotTooLong && !stateStringTooLong) {
  936. // If the string is shorter than maxlen, return its length.
  937. result = *strLengthNL;
  938. }
  939. }
  940. if (result.isUnknown()) {
  941. // If we don't have enough information for a comparison, there's
  942. // no guarantee the full string length will actually be returned.
  943. // All we know is the return value is the min of the string length
  944. // and the limit. This is better than nothing.
  945. unsigned Count = C.getCurrentBlockCount();
  946. result = C.getSValBuilder().getConjuredSymbolVal(NULL, CE, Count);
  947. NonLoc *resultNL = cast<NonLoc>(&result);
  948. if (strLengthNL) {
  949. state = state->assume(cast<DefinedOrUnknownSVal>
  950. (C.getSValBuilder().evalBinOpNN(state, BO_LE,
  951. *resultNL,
  952. *strLengthNL,
  953. cmpTy)), true);
  954. }
  955. if (maxlenValNL) {
  956. state = state->assume(cast<DefinedOrUnknownSVal>
  957. (C.getSValBuilder().evalBinOpNN(state, BO_LE,
  958. *resultNL,
  959. *maxlenValNL,
  960. cmpTy)), true);
  961. }
  962. }
  963. } else {
  964. // This is a plain strlen(), not strnlen().
  965. result = cast<DefinedOrUnknownSVal>(strLength);
  966. // If we don't know the length of the string, conjure a return
  967. // value, so it can be used in constraints, at least.
  968. if (result.isUnknown()) {
  969. unsigned Count = C.getCurrentBlockCount();
  970. result = C.getSValBuilder().getConjuredSymbolVal(NULL, CE, Count);
  971. }
  972. }
  973. // Bind the return value.
  974. assert(!result.isUnknown() && "Should have conjured a value by now");
  975. state = state->BindExpr(CE, result);
  976. C.addTransition(state);
  977. }
  978. void CStringChecker::evalStrcpy(CheckerContext &C, const CallExpr *CE) const {
  979. // char *strcpy(char *restrict dst, const char *restrict src);
  980. evalStrcpyCommon(C, CE,
  981. /* returnEnd = */ false,
  982. /* isBounded = */ false,
  983. /* isAppending = */ false);
  984. }
  985. void CStringChecker::evalStrncpy(CheckerContext &C, const CallExpr *CE) const {
  986. // char *strncpy(char *restrict dst, const char *restrict src, size_t n);
  987. evalStrcpyCommon(C, CE,
  988. /* returnEnd = */ false,
  989. /* isBounded = */ true,
  990. /* isAppending = */ false);
  991. }
  992. void CStringChecker::evalStpcpy(CheckerContext &C, const CallExpr *CE) const {
  993. // char *stpcpy(char *restrict dst, const char *restrict src);
  994. evalStrcpyCommon(C, CE,
  995. /* returnEnd = */ true,
  996. /* isBounded = */ false,
  997. /* isAppending = */ false);
  998. }
  999. void CStringChecker::evalStrcat(CheckerContext &C, const CallExpr *CE) const {
  1000. //char *strcat(char *restrict s1, const char *restrict s2);
  1001. evalStrcpyCommon(C, CE,
  1002. /* returnEnd = */ false,
  1003. /* isBounded = */ false,
  1004. /* isAppending = */ true);
  1005. }
  1006. void CStringChecker::evalStrncat(CheckerContext &C, const CallExpr *CE) const {
  1007. //char *strncat(char *restrict s1, const char *restrict s2, size_t n);
  1008. evalStrcpyCommon(C, CE,
  1009. /* returnEnd = */ false,
  1010. /* isBounded = */ true,
  1011. /* isAppending = */ true);
  1012. }
  1013. void CStringChecker::evalStrcpyCommon(CheckerContext &C, const CallExpr *CE,
  1014. bool returnEnd, bool isBounded,
  1015. bool isAppending) const {
  1016. CurrentFunctionDescription = "string copy function";
  1017. const ProgramState *state = C.getState();
  1018. // Check that the destination is non-null.
  1019. const Expr *Dst = CE->getArg(0);
  1020. SVal DstVal = state->getSVal(Dst);
  1021. state = checkNonNull(C, state, Dst, DstVal);
  1022. if (!state)
  1023. return;
  1024. // Check that the source is non-null.
  1025. const Expr *srcExpr = CE->getArg(1);
  1026. SVal srcVal = state->getSVal(srcExpr);
  1027. state = checkNonNull(C, state, srcExpr, srcVal);
  1028. if (!state)
  1029. return;
  1030. // Get the string length of the source.
  1031. SVal strLength = getCStringLength(C, state, srcExpr, srcVal);
  1032. // If the source isn't a valid C string, give up.
  1033. if (strLength.isUndef())
  1034. return;
  1035. SValBuilder &svalBuilder = C.getSValBuilder();
  1036. QualType cmpTy = svalBuilder.getConditionType();
  1037. QualType sizeTy = svalBuilder.getContext().getSizeType();
  1038. // These two values allow checking two kinds of errors:
  1039. // - actual overflows caused by a source that doesn't fit in the destination
  1040. // - potential overflows caused by a bound that could exceed the destination
  1041. SVal amountCopied = UnknownVal();
  1042. SVal maxLastElementIndex = UnknownVal();
  1043. const char *boundWarning = NULL;
  1044. // If the function is strncpy, strncat, etc... it is bounded.
  1045. if (isBounded) {
  1046. // Get the max number of characters to copy.
  1047. const Expr *lenExpr = CE->getArg(2);
  1048. SVal lenVal = state->getSVal(lenExpr);
  1049. // Protect against misdeclared strncpy().
  1050. lenVal = svalBuilder.evalCast(lenVal, sizeTy, lenExpr->getType());
  1051. NonLoc *strLengthNL = dyn_cast<NonLoc>(&strLength);
  1052. NonLoc *lenValNL = dyn_cast<NonLoc>(&lenVal);
  1053. // If we know both values, we might be able to figure out how much
  1054. // we're copying.
  1055. if (strLengthNL && lenValNL) {
  1056. const ProgramState *stateSourceTooLong, *stateSourceNotTooLong;
  1057. // Check if the max number to copy is less than the length of the src.
  1058. // If the bound is equal to the source length, strncpy won't null-
  1059. // terminate the result!
  1060. llvm::tie(stateSourceTooLong, stateSourceNotTooLong) =
  1061. state->assume(cast<DefinedOrUnknownSVal>
  1062. (svalBuilder.evalBinOpNN(state, BO_GE, *strLengthNL,
  1063. *lenValNL, cmpTy)));
  1064. if (stateSourceTooLong && !stateSourceNotTooLong) {
  1065. // Max number to copy is less than the length of the src, so the actual
  1066. // strLength copied is the max number arg.
  1067. state = stateSourceTooLong;
  1068. amountCopied = lenVal;
  1069. } else if (!stateSourceTooLong && stateSourceNotTooLong) {
  1070. // The source buffer entirely fits in the bound.
  1071. state = stateSourceNotTooLong;
  1072. amountCopied = strLength;
  1073. }
  1074. }
  1075. // We still want to know if the bound is known to be too large.
  1076. if (lenValNL) {
  1077. if (isAppending) {
  1078. // For strncat, the check is strlen(dst) + lenVal < sizeof(dst)
  1079. // Get the string length of the destination. If the destination is
  1080. // memory that can't have a string length, we shouldn't be copying
  1081. // into it anyway.
  1082. SVal dstStrLength = getCStringLength(C, state, Dst, DstVal);
  1083. if (dstStrLength.isUndef())
  1084. return;
  1085. if (NonLoc *dstStrLengthNL = dyn_cast<NonLoc>(&dstStrLength)) {
  1086. maxLastElementIndex = svalBuilder.evalBinOpNN(state, BO_Add,
  1087. *lenValNL,
  1088. *dstStrLengthNL,
  1089. sizeTy);
  1090. boundWarning = "Size argument is greater than the free space in the "
  1091. "destination buffer";
  1092. }
  1093. } else {
  1094. // For strncpy, this is just checking that lenVal <= sizeof(dst)
  1095. // (Yes, strncpy and strncat differ in how they treat termination.
  1096. // strncat ALWAYS terminates, but strncpy doesn't.)
  1097. NonLoc one = cast<NonLoc>(svalBuilder.makeIntVal(1, sizeTy));
  1098. maxLastElementIndex = svalBuilder.evalBinOpNN(state, BO_Sub, *lenValNL,
  1099. one, sizeTy);
  1100. boundWarning = "Size argument is greater than the length of the "
  1101. "destination buffer";
  1102. }
  1103. }
  1104. // If we couldn't pin down the copy length, at least bound it.
  1105. // FIXME: We should actually run this code path for append as well, but
  1106. // right now it creates problems with constraints (since we can end up
  1107. // trying to pass constraints from symbol to symbol).
  1108. if (amountCopied.isUnknown() && !isAppending) {
  1109. // Try to get a "hypothetical" string length symbol, which we can later
  1110. // set as a real value if that turns out to be the case.
  1111. amountCopied = getCStringLength(C, state, lenExpr, srcVal, true);
  1112. assert(!amountCopied.isUndef());
  1113. if (NonLoc *amountCopiedNL = dyn_cast<NonLoc>(&amountCopied)) {
  1114. if (lenValNL) {
  1115. // amountCopied <= lenVal
  1116. SVal copiedLessThanBound = svalBuilder.evalBinOpNN(state, BO_LE,
  1117. *amountCopiedNL,
  1118. *lenValNL,
  1119. cmpTy);
  1120. state = state->assume(cast<DefinedOrUnknownSVal>(copiedLessThanBound),
  1121. true);
  1122. if (!state)
  1123. return;
  1124. }
  1125. if (strLengthNL) {
  1126. // amountCopied <= strlen(source)
  1127. SVal copiedLessThanSrc = svalBuilder.evalBinOpNN(state, BO_LE,
  1128. *amountCopiedNL,
  1129. *strLengthNL,
  1130. cmpTy);
  1131. state = state->assume(cast<DefinedOrUnknownSVal>(copiedLessThanSrc),
  1132. true);
  1133. if (!state)
  1134. return;
  1135. }
  1136. }
  1137. }
  1138. } else {
  1139. // The function isn't bounded. The amount copied should match the length
  1140. // of the source buffer.
  1141. amountCopied = strLength;
  1142. }
  1143. assert(state);
  1144. // This represents the number of characters copied into the destination
  1145. // buffer. (It may not actually be the strlen if the destination buffer
  1146. // is not terminated.)
  1147. SVal finalStrLength = UnknownVal();
  1148. // If this is an appending function (strcat, strncat...) then set the
  1149. // string length to strlen(src) + strlen(dst) since the buffer will
  1150. // ultimately contain both.
  1151. if (isAppending) {
  1152. // Get the string length of the destination. If the destination is memory
  1153. // that can't have a string length, we shouldn't be copying into it anyway.
  1154. SVal dstStrLength = getCStringLength(C, state, Dst, DstVal);
  1155. if (dstStrLength.isUndef())
  1156. return;
  1157. NonLoc *srcStrLengthNL = dyn_cast<NonLoc>(&amountCopied);
  1158. NonLoc *dstStrLengthNL = dyn_cast<NonLoc>(&dstStrLength);
  1159. // If we know both string lengths, we might know the final string length.
  1160. if (srcStrLengthNL && dstStrLengthNL) {
  1161. // Make sure the two lengths together don't overflow a size_t.
  1162. state = checkAdditionOverflow(C, state, *srcStrLengthNL, *dstStrLengthNL);
  1163. if (!state)
  1164. return;
  1165. finalStrLength = svalBuilder.evalBinOpNN(state, BO_Add, *srcStrLengthNL,
  1166. *dstStrLengthNL, sizeTy);
  1167. }
  1168. // If we couldn't get a single value for the final string length,
  1169. // we can at least bound it by the individual lengths.
  1170. if (finalStrLength.isUnknown()) {
  1171. // Try to get a "hypothetical" string length symbol, which we can later
  1172. // set as a real value if that turns out to be the case.
  1173. finalStrLength = getCStringLength(C, state, CE, DstVal, true);
  1174. assert(!finalStrLength.isUndef());
  1175. if (NonLoc *finalStrLengthNL = dyn_cast<NonLoc>(&finalStrLength)) {
  1176. if (srcStrLengthNL) {
  1177. // finalStrLength >= srcStrLength
  1178. SVal sourceInResult = svalBuilder.evalBinOpNN(state, BO_GE,
  1179. *finalStrLengthNL,
  1180. *srcStrLengthNL,
  1181. cmpTy);
  1182. state = state->assume(cast<DefinedOrUnknownSVal>(sourceInResult),
  1183. true);
  1184. if (!state)
  1185. return;
  1186. }
  1187. if (dstStrLengthNL) {
  1188. // finalStrLength >= dstStrLength
  1189. SVal destInResult = svalBuilder.evalBinOpNN(state, BO_GE,
  1190. *finalStrLengthNL,
  1191. *dstStrLengthNL,
  1192. cmpTy);
  1193. state = state->assume(cast<DefinedOrUnknownSVal>(destInResult),
  1194. true);
  1195. if (!state)
  1196. return;
  1197. }
  1198. }
  1199. }
  1200. } else {
  1201. // Otherwise, this is a copy-over function (strcpy, strncpy, ...), and
  1202. // the final string length will match the input string length.
  1203. finalStrLength = amountCopied;
  1204. }
  1205. // The final result of the function will either be a pointer past the last
  1206. // copied element, or a pointer to the start of the destination buffer.
  1207. SVal Result = (returnEnd ? UnknownVal() : DstVal);
  1208. assert(state);
  1209. // If the destination is a MemRegion, try to check for a buffer overflow and
  1210. // record the new string length.
  1211. if (loc::MemRegionVal *dstRegVal = dyn_cast<loc::MemRegionVal>(&DstVal)) {
  1212. QualType ptrTy = Dst->getType();
  1213. // If we have an exact value on a bounded copy, use that to check for
  1214. // overflows, rather than our estimate about how much is actually copied.
  1215. if (boundWarning) {
  1216. if (NonLoc *maxLastNL = dyn_cast<NonLoc>(&maxLastElementIndex)) {
  1217. SVal maxLastElement = svalBuilder.evalBinOpLN(state, BO_Add, *dstRegVal,
  1218. *maxLastNL, ptrTy);
  1219. state = CheckLocation(C, state, CE->getArg(2), maxLastElement,
  1220. boundWarning);
  1221. if (!state)
  1222. return;
  1223. }
  1224. }
  1225. // Then, if the final length is known...
  1226. if (NonLoc *knownStrLength = dyn_cast<NonLoc>(&finalStrLength)) {
  1227. SVal lastElement = svalBuilder.evalBinOpLN(state, BO_Add, *dstRegVal,
  1228. *knownStrLength, ptrTy);
  1229. // ...and we haven't checked the bound, we'll check the actual copy.
  1230. if (!boundWarning) {
  1231. const char * const warningMsg =
  1232. "String copy function overflows destination buffer";
  1233. state = CheckLocation(C, state, Dst, lastElement, warningMsg);
  1234. if (!state)
  1235. return;
  1236. }
  1237. // If this is a stpcpy-style copy, the last element is the return value.
  1238. if (returnEnd)
  1239. Result = lastElement;
  1240. }
  1241. // Invalidate the destination. This must happen before we set the C string
  1242. // length because invalidation will clear the length.
  1243. // FIXME: Even if we can't perfectly model the copy, we should see if we
  1244. // can use LazyCompoundVals to copy the source values into the destination.
  1245. // This would probably remove any existing bindings past the end of the
  1246. // string, but that's still an improvement over blank invalidation.
  1247. state = InvalidateBuffer(C, state, Dst, *dstRegVal);
  1248. // Set the C string length of the destination, if we know it.
  1249. if (isBounded && !isAppending) {
  1250. // strncpy is annoying in that it doesn't guarantee to null-terminate
  1251. // the result string. If the original string didn't fit entirely inside
  1252. // the bound (including the null-terminator), we don't know how long the
  1253. // result is.
  1254. if (amountCopied != strLength)
  1255. finalStrLength = UnknownVal();
  1256. }
  1257. state = setCStringLength(state, dstRegVal->getRegion(), finalStrLength);
  1258. }
  1259. assert(state);
  1260. // If this is a stpcpy-style copy, but we were unable to check for a buffer
  1261. // overflow, we still need a result. Conjure a return value.
  1262. if (returnEnd && Result.isUnknown()) {
  1263. unsigned Count = C.getCurrentBlockCount();
  1264. Result = svalBuilder.getConjuredSymbolVal(NULL, CE, Count);
  1265. }
  1266. // Set the return value.
  1267. state = state->BindExpr(CE, Result);
  1268. C.addTransition(state);
  1269. }
  1270. void CStringChecker::evalStrcmp(CheckerContext &C, const CallExpr *CE) const {
  1271. //int strcmp(const char *s1, const char *s2);
  1272. evalStrcmpCommon(C, CE, /* isBounded = */ false, /* ignoreCase = */ false);
  1273. }
  1274. void CStringChecker::evalStrncmp(CheckerContext &C, const CallExpr *CE) const {
  1275. //int strncmp(const char *s1, const char *s2, size_t n);
  1276. evalStrcmpCommon(C, CE, /* isBounded = */ true, /* ignoreCase = */ false);
  1277. }
  1278. void CStringChecker::evalStrcasecmp(CheckerContext &C,
  1279. const CallExpr *CE) const {
  1280. //int strcasecmp(const char *s1, const char *s2);
  1281. evalStrcmpCommon(C, CE, /* isBounded = */ false, /* ignoreCase = */ true);
  1282. }
  1283. void CStringChecker::evalStrncasecmp(CheckerContext &C,
  1284. const CallExpr *CE) const {
  1285. //int strncasecmp(const char *s1, const char *s2, size_t n);
  1286. evalStrcmpCommon(C, CE, /* isBounded = */ true, /* ignoreCase = */ true);
  1287. }
  1288. void CStringChecker::evalStrcmpCommon(CheckerContext &C, const CallExpr *CE,
  1289. bool isBounded, bool ignoreCase) const {
  1290. CurrentFunctionDescription = "string comparison function";
  1291. const ProgramState *state = C.getState();
  1292. // Check that the first string is non-null
  1293. const Expr *s1 = CE->getArg(0);
  1294. SVal s1Val = state->getSVal(s1);
  1295. state = checkNonNull(C, state, s1, s1Val);
  1296. if (!state)
  1297. return;
  1298. // Check that the second string is non-null.
  1299. const Expr *s2 = CE->getArg(1);
  1300. SVal s2Val = state->getSVal(s2);
  1301. state = checkNonNull(C, state, s2, s2Val);
  1302. if (!state)
  1303. return;
  1304. // Get the string length of the first string or give up.
  1305. SVal s1Length = getCStringLength(C, state, s1, s1Val);
  1306. if (s1Length.isUndef())
  1307. return;
  1308. // Get the string length of the second string or give up.
  1309. SVal s2Length = getCStringLength(C, state, s2, s2Val);
  1310. if (s2Length.isUndef())
  1311. return;
  1312. // If we know the two buffers are the same, we know the result is 0.
  1313. // First, get the two buffers' addresses. Another checker will have already
  1314. // made sure they're not undefined.
  1315. DefinedOrUnknownSVal LV = cast<DefinedOrUnknownSVal>(s1Val);
  1316. DefinedOrUnknownSVal RV = cast<DefinedOrUnknownSVal>(s2Val);
  1317. // See if they are the same.
  1318. SValBuilder &svalBuilder = C.getSValBuilder();
  1319. DefinedOrUnknownSVal SameBuf = svalBuilder.evalEQ(state, LV, RV);
  1320. const ProgramState *StSameBuf, *StNotSameBuf;
  1321. llvm::tie(StSameBuf, StNotSameBuf) = state->assume(SameBuf);
  1322. // If the two arguments might be the same buffer, we know the result is 0,
  1323. // and we only need to check one size.
  1324. if (StSameBuf) {
  1325. StSameBuf = StSameBuf->BindExpr(CE, svalBuilder.makeZeroVal(CE->getType()));
  1326. C.addTransition(StSameBuf);
  1327. // If the two arguments are GUARANTEED to be the same, we're done!
  1328. if (!StNotSameBuf)
  1329. return;
  1330. }
  1331. assert(StNotSameBuf);
  1332. state = StNotSameBuf;
  1333. // At this point we can go about comparing the two buffers.
  1334. // For now, we only do this if they're both known string literals.
  1335. // Attempt to extract string literals from both expressions.
  1336. const StringLiteral *s1StrLiteral = getCStringLiteral(C, state, s1, s1Val);
  1337. const StringLiteral *s2StrLiteral = getCStringLiteral(C, state, s2, s2Val);
  1338. bool canComputeResult = false;
  1339. if (s1StrLiteral && s2StrLiteral) {
  1340. StringRef s1StrRef = s1StrLiteral->getString();
  1341. StringRef s2StrRef = s2StrLiteral->getString();
  1342. if (isBounded) {
  1343. // Get the max number of characters to compare.
  1344. const Expr *lenExpr = CE->getArg(2);
  1345. SVal lenVal = state->getSVal(lenExpr);
  1346. // If the length is known, we can get the right substrings.
  1347. if (const llvm::APSInt *len = svalBuilder.getKnownValue(state, lenVal)) {
  1348. // Create substrings of each to compare the prefix.
  1349. s1StrRef = s1StrRef.substr(0, (size_t)len->getZExtValue());
  1350. s2StrRef = s2StrRef.substr(0, (size_t)len->getZExtValue());
  1351. canComputeResult = true;
  1352. }
  1353. } else {
  1354. // This is a normal, unbounded strcmp.
  1355. canComputeResult = true;
  1356. }
  1357. if (canComputeResult) {
  1358. // Real strcmp stops at null characters.
  1359. size_t s1Term = s1StrRef.find('\0');
  1360. if (s1Term != StringRef::npos)
  1361. s1StrRef = s1StrRef.substr(0, s1Term);
  1362. size_t s2Term = s2StrRef.find('\0');
  1363. if (s2Term != StringRef::npos)
  1364. s2StrRef = s2StrRef.substr(0, s2Term);
  1365. // Use StringRef's comparison methods to compute the actual result.
  1366. int result;
  1367. if (ignoreCase) {
  1368. // Compare string 1 to string 2 the same way strcasecmp() does.
  1369. result = s1StrRef.compare_lower(s2StrRef);
  1370. } else {
  1371. // Compare string 1 to string 2 the same way strcmp() does.
  1372. result = s1StrRef.compare(s2StrRef);
  1373. }
  1374. // Build the SVal of the comparison and bind the return value.
  1375. SVal resultVal = svalBuilder.makeIntVal(result, CE->getType());
  1376. state = state->BindExpr(CE, resultVal);
  1377. }
  1378. }
  1379. if (!canComputeResult) {
  1380. // Conjure a symbolic value. It's the best we can do.
  1381. unsigned Count = C.getCurrentBlockCount();
  1382. SVal resultVal = svalBuilder.getConjuredSymbolVal(NULL, CE, Count);
  1383. state = state->BindExpr(CE, resultVal);
  1384. }
  1385. // Record this as a possible path.
  1386. C.addTransition(state);
  1387. }
  1388. //===----------------------------------------------------------------------===//
  1389. // The driver method, and other Checker callbacks.
  1390. //===----------------------------------------------------------------------===//
  1391. bool CStringChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
  1392. StringRef Name = C.getCalleeName(CE);
  1393. if (Name.empty())
  1394. return false;
  1395. if (Name.startswith("__builtin_"))
  1396. Name = Name.substr(10);
  1397. FnCheck evalFunction = llvm::StringSwitch<FnCheck>(Name)
  1398. .Cases("memcpy", "__memcpy_chk", &CStringChecker::evalMemcpy)
  1399. .Cases("mempcpy", "__mempcpy_chk", &CStringChecker::evalMempcpy)
  1400. .Cases("memcmp", "bcmp", &CStringChecker::evalMemcmp)
  1401. .Cases("memmove", "__memmove_chk", &CStringChecker::evalMemmove)
  1402. .Cases("strcpy", "__strcpy_chk", &CStringChecker::evalStrcpy)
  1403. .Cases("strncpy", "__strncpy_chk", &CStringChecker::evalStrncpy)
  1404. .Cases("stpcpy", "__stpcpy_chk", &CStringChecker::evalStpcpy)
  1405. .Cases("strcat", "__strcat_chk", &CStringChecker::evalStrcat)
  1406. .Cases("strncat", "__strncat_chk", &CStringChecker::evalStrncat)
  1407. .Case("strlen", &CStringChecker::evalstrLength)
  1408. .Case("strnlen", &CStringChecker::evalstrnLength)
  1409. .Case("strcmp", &CStringChecker::evalStrcmp)
  1410. .Case("strncmp", &CStringChecker::evalStrncmp)
  1411. .Case("strcasecmp", &CStringChecker::evalStrcasecmp)
  1412. .Case("strncasecmp", &CStringChecker::evalStrncasecmp)
  1413. .Case("bcopy", &CStringChecker::evalBcopy)
  1414. .Default(NULL);
  1415. // If the callee isn't a string function, let another checker handle it.
  1416. if (!evalFunction)
  1417. return false;
  1418. // Make sure each function sets its own description.
  1419. // (But don't bother in a release build.)
  1420. assert(!(CurrentFunctionDescription = NULL));
  1421. // Check and evaluate the call.
  1422. (this->*evalFunction)(C, CE);
  1423. return true;
  1424. }
  1425. void CStringChecker::checkPreStmt(const DeclStmt *DS, CheckerContext &C) const {
  1426. // Record string length for char a[] = "abc";
  1427. const ProgramState *state = C.getState();
  1428. for (DeclStmt::const_decl_iterator I = DS->decl_begin(), E = DS->decl_end();
  1429. I != E; ++I) {
  1430. const VarDecl *D = dyn_cast<VarDecl>(*I);
  1431. if (!D)
  1432. continue;
  1433. // FIXME: Handle array fields of structs.
  1434. if (!D->getType()->isArrayType())
  1435. continue;
  1436. const Expr *Init = D->getInit();
  1437. if (!Init)
  1438. continue;
  1439. if (!isa<StringLiteral>(Init))
  1440. continue;
  1441. Loc VarLoc = state->getLValue(D, C.getLocationContext());
  1442. const MemRegion *MR = VarLoc.getAsRegion();
  1443. if (!MR)
  1444. continue;
  1445. SVal StrVal = state->getSVal(Init);
  1446. assert(StrVal.isValid() && "Initializer string is unknown or undefined");
  1447. DefinedOrUnknownSVal strLength
  1448. = cast<DefinedOrUnknownSVal>(getCStringLength(C, state, Init, StrVal));
  1449. state = state->set<CStringLength>(MR, strLength);
  1450. }
  1451. C.addTransition(state);
  1452. }
  1453. bool CStringChecker::wantsRegionChangeUpdate(const ProgramState *state) const {
  1454. CStringLength::EntryMap Entries = state->get<CStringLength>();
  1455. return !Entries.isEmpty();
  1456. }
  1457. const ProgramState *
  1458. CStringChecker::checkRegionChanges(const ProgramState *state,
  1459. const StoreManager::InvalidatedSymbols *,
  1460. ArrayRef<const MemRegion *> ExplicitRegions,
  1461. ArrayRef<const MemRegion *> Regions) const {
  1462. CStringLength::EntryMap Entries = state->get<CStringLength>();
  1463. if (Entries.isEmpty())
  1464. return state;
  1465. llvm::SmallPtrSet<const MemRegion *, 8> Invalidated;
  1466. llvm::SmallPtrSet<const MemRegion *, 32> SuperRegions;
  1467. // First build sets for the changed regions and their super-regions.
  1468. for (ArrayRef<const MemRegion *>::iterator
  1469. I = Regions.begin(), E = Regions.end(); I != E; ++I) {
  1470. const MemRegion *MR = *I;
  1471. Invalidated.insert(MR);
  1472. SuperRegions.insert(MR);
  1473. while (const SubRegion *SR = dyn_cast<SubRegion>(MR)) {
  1474. MR = SR->getSuperRegion();
  1475. SuperRegions.insert(MR);
  1476. }
  1477. }
  1478. CStringLength::EntryMap::Factory &F = state->get_context<CStringLength>();
  1479. // Then loop over the entries in the current state.
  1480. for (CStringLength::EntryMap::iterator I = Entries.begin(),
  1481. E = Entries.end(); I != E; ++I) {
  1482. const MemRegion *MR = I.getKey();
  1483. // Is this entry for a super-region of a changed region?
  1484. if (SuperRegions.count(MR)) {
  1485. Entries = F.remove(Entries, MR);
  1486. continue;
  1487. }
  1488. // Is this entry for a sub-region of a changed region?
  1489. const MemRegion *Super = MR;
  1490. while (const SubRegion *SR = dyn_cast<SubRegion>(Super)) {
  1491. Super = SR->getSuperRegion();
  1492. if (Invalidated.count(Super)) {
  1493. Entries = F.remove(Entries, MR);
  1494. break;
  1495. }
  1496. }
  1497. }
  1498. return state->set<CStringLength>(Entries);
  1499. }
  1500. void CStringChecker::checkLiveSymbols(const ProgramState *state,
  1501. SymbolReaper &SR) const {
  1502. // Mark all symbols in our string length map as valid.
  1503. CStringLength::EntryMap Entries = state->get<CStringLength>();
  1504. for (CStringLength::EntryMap::iterator I = Entries.begin(), E = Entries.end();
  1505. I != E; ++I) {
  1506. SVal Len = I.getData();
  1507. for (SymExpr::symbol_iterator si = Len.symbol_begin(),
  1508. se = Len.symbol_end(); si != se; ++si)
  1509. SR.markInUse(*si);
  1510. }
  1511. }
  1512. void CStringChecker::checkDeadSymbols(SymbolReaper &SR,
  1513. CheckerContext &C) const {
  1514. if (!SR.hasDeadSymbols())
  1515. return;
  1516. const ProgramState *state = C.getState();
  1517. CStringLength::EntryMap Entries = state->get<CStringLength>();
  1518. if (Entries.isEmpty())
  1519. return;
  1520. CStringLength::EntryMap::Factory &F = state->get_context<CStringLength>();
  1521. for (CStringLength::EntryMap::iterator I = Entries.begin(), E = Entries.end();
  1522. I != E; ++I) {
  1523. SVal Len = I.getData();
  1524. if (SymbolRef Sym = Len.getAsSymbol()) {
  1525. if (SR.isDead(Sym))
  1526. Entries = F.remove(Entries, I.getKey());
  1527. }
  1528. }
  1529. state = state->set<CStringLength>(Entries);
  1530. C.addTransition(state);
  1531. }
  1532. void ento::registerCStringChecker(CheckerManager &mgr) {
  1533. mgr.registerChecker<CStringChecker>();
  1534. }