CStringChecker.cpp 69 KB

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