CStringChecker.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712
  1. //= CStringChecker.h - 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 "GRExprEngineExperimentalChecks.h"
  15. #include "clang/Checker/BugReporter/BugType.h"
  16. #include "clang/Checker/PathSensitive/CheckerVisitor.h"
  17. #include "llvm/ADT/StringSwitch.h"
  18. using namespace clang;
  19. namespace {
  20. class CStringChecker : public CheckerVisitor<CStringChecker> {
  21. BugType *BT_Null, *BT_Bounds, *BT_Overlap, *BT_NotCString;
  22. public:
  23. CStringChecker()
  24. : BT_Null(0), BT_Bounds(0), BT_Overlap(0), BT_NotCString(0) {}
  25. static void *getTag() { static int tag; return &tag; }
  26. bool EvalCallExpr(CheckerContext &C, const CallExpr *CE);
  27. typedef void (CStringChecker::*FnCheck)(CheckerContext &, const CallExpr *);
  28. void EvalMemcpy(CheckerContext &C, const CallExpr *CE);
  29. void EvalMemmove(CheckerContext &C, const CallExpr *CE);
  30. void EvalBcopy(CheckerContext &C, const CallExpr *CE);
  31. void EvalCopyCommon(CheckerContext &C, const GRState *state,
  32. const Expr *Size, const Expr *Source, const Expr *Dest,
  33. bool Restricted = false);
  34. void EvalMemcmp(CheckerContext &C, const CallExpr *CE);
  35. void EvalStrlen(CheckerContext &C, const CallExpr *CE);
  36. // Utility methods
  37. std::pair<const GRState*, const GRState*>
  38. AssumeZero(CheckerContext &C, const GRState *state, SVal V, QualType Ty);
  39. SVal GetCStringLength(CheckerContext &C, const GRState *state,
  40. const Expr *Ex, SVal Buf);
  41. bool SummarizeRegion(llvm::raw_ostream& os, ASTContext& Ctx,
  42. const MemRegion *MR);
  43. // Re-usable checks
  44. const GRState *CheckNonNull(CheckerContext &C, const GRState *state,
  45. const Expr *S, SVal l);
  46. const GRState *CheckLocation(CheckerContext &C, const GRState *state,
  47. const Expr *S, SVal l);
  48. const GRState *CheckBufferAccess(CheckerContext &C, const GRState *state,
  49. const Expr *Size,
  50. const Expr *FirstBuf,
  51. const Expr *SecondBuf = NULL);
  52. const GRState *CheckOverlap(CheckerContext &C, const GRState *state,
  53. const Expr *Size, const Expr *First,
  54. const Expr *Second);
  55. void EmitOverlapBug(CheckerContext &C, const GRState *state,
  56. const Stmt *First, const Stmt *Second);
  57. };
  58. } //end anonymous namespace
  59. void clang::RegisterCStringChecker(GRExprEngine &Eng) {
  60. Eng.registerCheck(new CStringChecker());
  61. }
  62. //===----------------------------------------------------------------------===//
  63. // Individual checks and utility methods.
  64. //===----------------------------------------------------------------------===//
  65. std::pair<const GRState*, const GRState*>
  66. CStringChecker::AssumeZero(CheckerContext &C, const GRState *state, SVal V,
  67. QualType Ty) {
  68. DefinedSVal *Val = dyn_cast<DefinedSVal>(&V);
  69. if (!Val)
  70. return std::pair<const GRState*, const GRState *>(state, state);
  71. ValueManager &ValMgr = C.getValueManager();
  72. SValuator &SV = ValMgr.getSValuator();
  73. DefinedOrUnknownSVal Zero = ValMgr.makeZeroVal(Ty);
  74. DefinedOrUnknownSVal ValIsZero = SV.EvalEQ(state, *Val, Zero);
  75. return state->Assume(ValIsZero);
  76. }
  77. const GRState *CStringChecker::CheckNonNull(CheckerContext &C,
  78. const GRState *state,
  79. const Expr *S, SVal l) {
  80. // If a previous check has failed, propagate the failure.
  81. if (!state)
  82. return NULL;
  83. const GRState *stateNull, *stateNonNull;
  84. llvm::tie(stateNull, stateNonNull) = AssumeZero(C, state, l, S->getType());
  85. if (stateNull && !stateNonNull) {
  86. ExplodedNode *N = C.GenerateSink(stateNull);
  87. if (!N)
  88. return NULL;
  89. if (!BT_Null)
  90. BT_Null = new BuiltinBug("API",
  91. "Null pointer argument in call to byte string function");
  92. // Generate a report for this bug.
  93. BuiltinBug *BT = static_cast<BuiltinBug*>(BT_Null);
  94. EnhancedBugReport *report = new EnhancedBugReport(*BT,
  95. BT->getDescription(), N);
  96. report->addRange(S->getSourceRange());
  97. report->addVisitorCreator(bugreporter::registerTrackNullOrUndefValue, S);
  98. C.EmitReport(report);
  99. return NULL;
  100. }
  101. // From here on, assume that the value is non-null.
  102. assert(stateNonNull);
  103. return stateNonNull;
  104. }
  105. // FIXME: This was originally copied from ArrayBoundChecker.cpp. Refactor?
  106. const GRState *CStringChecker::CheckLocation(CheckerContext &C,
  107. const GRState *state,
  108. const Expr *S, SVal l) {
  109. // If a previous check has failed, propagate the failure.
  110. if (!state)
  111. return NULL;
  112. // Check for out of bound array element access.
  113. const MemRegion *R = l.getAsRegion();
  114. if (!R)
  115. return state;
  116. const ElementRegion *ER = dyn_cast<ElementRegion>(R);
  117. if (!ER)
  118. return state;
  119. assert(ER->getValueType() == C.getASTContext().CharTy &&
  120. "CheckLocation should only be called with char* ElementRegions");
  121. // Get the size of the array.
  122. const SubRegion *Super = cast<SubRegion>(ER->getSuperRegion());
  123. ValueManager &ValMgr = C.getValueManager();
  124. SVal Extent = ValMgr.convertToArrayIndex(Super->getExtent(ValMgr));
  125. DefinedOrUnknownSVal Size = cast<DefinedOrUnknownSVal>(Extent);
  126. // Get the index of the accessed element.
  127. DefinedOrUnknownSVal &Idx = cast<DefinedOrUnknownSVal>(ER->getIndex());
  128. const GRState *StInBound = state->AssumeInBound(Idx, Size, true);
  129. const GRState *StOutBound = state->AssumeInBound(Idx, Size, false);
  130. if (StOutBound && !StInBound) {
  131. ExplodedNode *N = C.GenerateSink(StOutBound);
  132. if (!N)
  133. return NULL;
  134. if (!BT_Bounds)
  135. BT_Bounds = new BuiltinBug("Out-of-bound array access",
  136. "Byte string function accesses out-of-bound array element "
  137. "(buffer overflow)");
  138. // FIXME: It would be nice to eventually make this diagnostic more clear,
  139. // e.g., by referencing the original declaration or by saying *why* this
  140. // reference is outside the range.
  141. // Generate a report for this bug.
  142. BuiltinBug *BT = static_cast<BuiltinBug*>(BT_Bounds);
  143. RangedBugReport *report = new RangedBugReport(*BT, BT->getDescription(), N);
  144. report->addRange(S->getSourceRange());
  145. C.EmitReport(report);
  146. return NULL;
  147. }
  148. // Array bound check succeeded. From this point forward the array bound
  149. // should always succeed.
  150. return StInBound;
  151. }
  152. const GRState *CStringChecker::CheckBufferAccess(CheckerContext &C,
  153. const GRState *state,
  154. const Expr *Size,
  155. const Expr *FirstBuf,
  156. const Expr *SecondBuf) {
  157. // If a previous check has failed, propagate the failure.
  158. if (!state)
  159. return NULL;
  160. ValueManager &VM = C.getValueManager();
  161. SValuator &SV = VM.getSValuator();
  162. ASTContext &Ctx = C.getASTContext();
  163. QualType SizeTy = Ctx.getSizeType();
  164. QualType PtrTy = Ctx.getPointerType(Ctx.CharTy);
  165. // Check that the first buffer is non-null.
  166. SVal BufVal = state->getSVal(FirstBuf);
  167. state = CheckNonNull(C, state, FirstBuf, BufVal);
  168. if (!state)
  169. return NULL;
  170. // Get the access length and make sure it is known.
  171. SVal LengthVal = state->getSVal(Size);
  172. NonLoc *Length = dyn_cast<NonLoc>(&LengthVal);
  173. if (!Length)
  174. return state;
  175. // Compute the offset of the last element to be accessed: size-1.
  176. NonLoc One = cast<NonLoc>(VM.makeIntVal(1, SizeTy));
  177. NonLoc LastOffset = cast<NonLoc>(SV.EvalBinOpNN(state, BinaryOperator::Sub,
  178. *Length, One, SizeTy));
  179. // Check that the first buffer is sufficently long.
  180. SVal BufStart = SV.EvalCast(BufVal, PtrTy, FirstBuf->getType());
  181. if (Loc *BufLoc = dyn_cast<Loc>(&BufStart)) {
  182. SVal BufEnd = SV.EvalBinOpLN(state, BinaryOperator::Add, *BufLoc,
  183. LastOffset, PtrTy);
  184. state = CheckLocation(C, state, FirstBuf, BufEnd);
  185. // If the buffer isn't large enough, abort.
  186. if (!state)
  187. return NULL;
  188. }
  189. // If there's a second buffer, check it as well.
  190. if (SecondBuf) {
  191. BufVal = state->getSVal(SecondBuf);
  192. state = CheckNonNull(C, state, SecondBuf, BufVal);
  193. if (!state)
  194. return NULL;
  195. BufStart = SV.EvalCast(BufVal, PtrTy, SecondBuf->getType());
  196. if (Loc *BufLoc = dyn_cast<Loc>(&BufStart)) {
  197. SVal BufEnd = SV.EvalBinOpLN(state, BinaryOperator::Add, *BufLoc,
  198. LastOffset, PtrTy);
  199. state = CheckLocation(C, state, SecondBuf, BufEnd);
  200. }
  201. }
  202. // Large enough or not, return this state!
  203. return state;
  204. }
  205. const GRState *CStringChecker::CheckOverlap(CheckerContext &C,
  206. const GRState *state,
  207. const Expr *Size,
  208. const Expr *First,
  209. const Expr *Second) {
  210. // Do a simple check for overlap: if the two arguments are from the same
  211. // buffer, see if the end of the first is greater than the start of the second
  212. // or vice versa.
  213. // If a previous check has failed, propagate the failure.
  214. if (!state)
  215. return NULL;
  216. ValueManager &VM = state->getStateManager().getValueManager();
  217. SValuator &SV = VM.getSValuator();
  218. ASTContext &Ctx = VM.getContext();
  219. const GRState *stateTrue, *stateFalse;
  220. // Get the buffer values and make sure they're known locations.
  221. SVal FirstVal = state->getSVal(First);
  222. SVal SecondVal = state->getSVal(Second);
  223. Loc *FirstLoc = dyn_cast<Loc>(&FirstVal);
  224. if (!FirstLoc)
  225. return state;
  226. Loc *SecondLoc = dyn_cast<Loc>(&SecondVal);
  227. if (!SecondLoc)
  228. return state;
  229. // Are the two values the same?
  230. DefinedOrUnknownSVal EqualTest = SV.EvalEQ(state, *FirstLoc, *SecondLoc);
  231. llvm::tie(stateTrue, stateFalse) = state->Assume(EqualTest);
  232. if (stateTrue && !stateFalse) {
  233. // If the values are known to be equal, that's automatically an overlap.
  234. EmitOverlapBug(C, stateTrue, First, Second);
  235. return NULL;
  236. }
  237. // Assume the two expressions are not equal.
  238. assert(stateFalse);
  239. state = stateFalse;
  240. // Which value comes first?
  241. QualType CmpTy = Ctx.IntTy;
  242. SVal Reverse = SV.EvalBinOpLL(state, BinaryOperator::GT,
  243. *FirstLoc, *SecondLoc, CmpTy);
  244. DefinedOrUnknownSVal *ReverseTest = dyn_cast<DefinedOrUnknownSVal>(&Reverse);
  245. if (!ReverseTest)
  246. return state;
  247. llvm::tie(stateTrue, stateFalse) = state->Assume(*ReverseTest);
  248. if (stateTrue) {
  249. if (stateFalse) {
  250. // If we don't know which one comes first, we can't perform this test.
  251. return state;
  252. } else {
  253. // Switch the values so that FirstVal is before SecondVal.
  254. Loc *tmpLoc = FirstLoc;
  255. FirstLoc = SecondLoc;
  256. SecondLoc = tmpLoc;
  257. // Switch the Exprs as well, so that they still correspond.
  258. const Expr *tmpExpr = First;
  259. First = Second;
  260. Second = tmpExpr;
  261. }
  262. }
  263. // Get the length, and make sure it too is known.
  264. SVal LengthVal = state->getSVal(Size);
  265. NonLoc *Length = dyn_cast<NonLoc>(&LengthVal);
  266. if (!Length)
  267. return state;
  268. // Convert the first buffer's start address to char*.
  269. // Bail out if the cast fails.
  270. QualType CharPtrTy = Ctx.getPointerType(Ctx.CharTy);
  271. SVal FirstStart = SV.EvalCast(*FirstLoc, CharPtrTy, First->getType());
  272. Loc *FirstStartLoc = dyn_cast<Loc>(&FirstStart);
  273. if (!FirstStartLoc)
  274. return state;
  275. // Compute the end of the first buffer. Bail out if THAT fails.
  276. SVal FirstEnd = SV.EvalBinOpLN(state, BinaryOperator::Add,
  277. *FirstStartLoc, *Length, CharPtrTy);
  278. Loc *FirstEndLoc = dyn_cast<Loc>(&FirstEnd);
  279. if (!FirstEndLoc)
  280. return state;
  281. // Is the end of the first buffer past the start of the second buffer?
  282. SVal Overlap = SV.EvalBinOpLL(state, BinaryOperator::GT,
  283. *FirstEndLoc, *SecondLoc, CmpTy);
  284. DefinedOrUnknownSVal *OverlapTest = dyn_cast<DefinedOrUnknownSVal>(&Overlap);
  285. if (!OverlapTest)
  286. return state;
  287. llvm::tie(stateTrue, stateFalse) = state->Assume(*OverlapTest);
  288. if (stateTrue && !stateFalse) {
  289. // Overlap!
  290. EmitOverlapBug(C, stateTrue, First, Second);
  291. return NULL;
  292. }
  293. // Assume the two expressions don't overlap.
  294. assert(stateFalse);
  295. return stateFalse;
  296. }
  297. void CStringChecker::EmitOverlapBug(CheckerContext &C, const GRState *state,
  298. const Stmt *First, const Stmt *Second) {
  299. ExplodedNode *N = C.GenerateSink(state);
  300. if (!N)
  301. return;
  302. if (!BT_Overlap)
  303. BT_Overlap = new BugType("Unix API", "Improper arguments");
  304. // Generate a report for this bug.
  305. RangedBugReport *report =
  306. new RangedBugReport(*BT_Overlap,
  307. "Arguments must not be overlapping buffers", N);
  308. report->addRange(First->getSourceRange());
  309. report->addRange(Second->getSourceRange());
  310. C.EmitReport(report);
  311. }
  312. SVal CStringChecker::GetCStringLength(CheckerContext &C, const GRState *state,
  313. const Expr *Ex, SVal Buf) {
  314. const MemRegion *MR = Buf.getAsRegion();
  315. if (!MR) {
  316. // If we can't get a region, see if it's something we /know/ isn't a
  317. // C string. In the context of locations, the only time we can issue such
  318. // a warning is for labels.
  319. if (loc::GotoLabel *Label = dyn_cast<loc::GotoLabel>(&Buf)) {
  320. ExplodedNode *N = C.GenerateSink(state);
  321. if (N) {
  322. if (!BT_NotCString)
  323. BT_NotCString = new BuiltinBug("API",
  324. "Argument is not a null-terminated string.");
  325. llvm::SmallString<120> buf;
  326. llvm::raw_svector_ostream os(buf);
  327. os << "Argument to byte string function is the address of the label '"
  328. << Label->getLabel()->getID()->getName()
  329. << "', which is not a null-terminated string";
  330. // Generate a report for this bug.
  331. EnhancedBugReport *report = new EnhancedBugReport(*BT_NotCString,
  332. os.str(), N);
  333. report->addRange(Ex->getSourceRange());
  334. C.EmitReport(report);
  335. }
  336. return UndefinedVal();
  337. }
  338. // If it's not a region and not a label, it may be a constant location,
  339. // or it may be unknown. Just conjure a value as usual (see end of method).
  340. } else {
  341. // If we have a region, strip casts from it and see if we can figure out
  342. // its length. For anything we can't figure out, just conjure a value as
  343. // usual (see end of method).
  344. MR = MR->StripCasts();
  345. switch (MR->getKind()) {
  346. case MemRegion::StringRegionKind: {
  347. ValueManager &ValMgr = C.getValueManager();
  348. ASTContext &Ctx = ValMgr.getContext();
  349. const StringLiteral *Str = cast<StringRegion>(MR)->getStringLiteral();
  350. // Non-constant string literals may have been changed, so only return a
  351. // known value if we know the literal is constant.
  352. if (Str->getType().isConstant(Ctx)) {
  353. QualType SizeTy = Ctx.getSizeType();
  354. return ValMgr.makeIntVal(Str->getByteLength(), SizeTy);
  355. }
  356. // FIXME: Handle the non-constant case. For now, just treat it like any
  357. // other initialized region.
  358. // FALL-THROUGH
  359. }
  360. case MemRegion::SymbolicRegionKind:
  361. case MemRegion::AllocaRegionKind:
  362. case MemRegion::VarRegionKind:
  363. case MemRegion::FieldRegionKind:
  364. case MemRegion::ObjCIvarRegionKind:
  365. // FIXME: These need to be tracked!
  366. break;
  367. case MemRegion::CompoundLiteralRegionKind:
  368. // FIXME: Can we track this? Is it necessary?
  369. break;
  370. case MemRegion::ElementRegionKind:
  371. // FIXME: How can we handle this? It's not good enough to subtract the
  372. // offset from the base string length; consider "123\x00567" and &a[5].
  373. break;
  374. default: {
  375. // Other regions (mostly non-data) can't have a reliable C string length.
  376. // In this case, an error is emitted and UndefinedVal is returned.
  377. // The caller should always be prepared to handle this case.
  378. ExplodedNode *N = C.GenerateSink(state);
  379. if (N) {
  380. if (!BT_NotCString)
  381. BT_NotCString = new BuiltinBug("API",
  382. "Argument is not a null-terminated string.");
  383. llvm::SmallString<120> buf;
  384. llvm::raw_svector_ostream os(buf);
  385. os << "Argument to byte string function is ";
  386. if (SummarizeRegion(os, C.getASTContext(), MR)) {
  387. os << ", which is not a null-terminated string";
  388. } else {
  389. os << "not a null-terminated string";
  390. }
  391. // Generate a report for this bug.
  392. EnhancedBugReport *report = new EnhancedBugReport(*BT_NotCString,
  393. os.str(), N);
  394. report->addRange(Ex->getSourceRange());
  395. C.EmitReport(report);
  396. }
  397. return UndefinedVal();
  398. }
  399. }
  400. }
  401. // If we can't track a certain region's C string length, or if we can't get a
  402. // region from the SVal, conjure a value, for use in later constraints.
  403. unsigned Count = C.getNodeBuilder().getCurrentBlockCount();
  404. ValueManager &ValMgr = C.getValueManager();
  405. QualType SizeTy = ValMgr.getContext().getSizeType();
  406. return ValMgr.getConjuredSymbolVal(getTag(), Ex, SizeTy, Count);
  407. }
  408. bool CStringChecker::SummarizeRegion(llvm::raw_ostream& os, ASTContext& Ctx,
  409. const MemRegion *MR) {
  410. const TypedRegion *TR = dyn_cast<TypedRegion>(MR);
  411. if (!TR)
  412. return false;
  413. switch (TR->getKind()) {
  414. case MemRegion::FunctionTextRegionKind: {
  415. const FunctionDecl *FD = cast<FunctionTextRegion>(TR)->getDecl();
  416. if (FD)
  417. os << "the address of the function '" << FD << "'";
  418. else
  419. os << "the address of a function";
  420. return true;
  421. }
  422. case MemRegion::BlockTextRegionKind:
  423. os << "block text";
  424. return true;
  425. case MemRegion::BlockDataRegionKind:
  426. os << "a block";
  427. return true;
  428. case MemRegion::CXXThisRegionKind:
  429. case MemRegion::CXXObjectRegionKind:
  430. os << "a C++ object of type " << TR->getValueType().getAsString();
  431. return true;
  432. case MemRegion::VarRegionKind:
  433. os << "a variable of type" << TR->getValueType().getAsString();
  434. return true;
  435. case MemRegion::FieldRegionKind:
  436. os << "a field of type " << TR->getValueType().getAsString();
  437. return true;
  438. case MemRegion::ObjCIvarRegionKind:
  439. os << "an instance variable of type " << TR->getValueType().getAsString();
  440. return true;
  441. default:
  442. return false;
  443. }
  444. }
  445. //===----------------------------------------------------------------------===//
  446. // Evaluation of individual function calls.
  447. //===----------------------------------------------------------------------===//
  448. void CStringChecker::EvalCopyCommon(CheckerContext &C, const GRState *state,
  449. const Expr *Size, const Expr *Dest,
  450. const Expr *Source, bool Restricted) {
  451. // See if the size argument is zero.
  452. SVal SizeVal = state->getSVal(Size);
  453. QualType SizeTy = Size->getType();
  454. const GRState *StZeroSize, *StNonZeroSize;
  455. llvm::tie(StZeroSize, StNonZeroSize) = AssumeZero(C, state, SizeVal, SizeTy);
  456. // If the size is zero, there won't be any actual memory access.
  457. if (StZeroSize)
  458. C.addTransition(StZeroSize);
  459. // If the size can be nonzero, we have to check the other arguments.
  460. if (StNonZeroSize) {
  461. state = StNonZeroSize;
  462. state = CheckBufferAccess(C, state, Size, Dest, Source);
  463. if (Restricted)
  464. state = CheckOverlap(C, state, Size, Dest, Source);
  465. if (state)
  466. C.addTransition(state);
  467. }
  468. }
  469. void CStringChecker::EvalMemcpy(CheckerContext &C, const CallExpr *CE) {
  470. // void *memcpy(void *restrict dst, const void *restrict src, size_t n);
  471. // The return value is the address of the destination buffer.
  472. const Expr *Dest = CE->getArg(0);
  473. const GRState *state = C.getState();
  474. state = state->BindExpr(CE, state->getSVal(Dest));
  475. EvalCopyCommon(C, state, CE->getArg(2), Dest, CE->getArg(1), true);
  476. }
  477. void CStringChecker::EvalMemmove(CheckerContext &C, const CallExpr *CE) {
  478. // void *memmove(void *dst, const void *src, size_t n);
  479. // The return value is the address of the destination buffer.
  480. const Expr *Dest = CE->getArg(0);
  481. const GRState *state = C.getState();
  482. state = state->BindExpr(CE, state->getSVal(Dest));
  483. EvalCopyCommon(C, state, CE->getArg(2), Dest, CE->getArg(1));
  484. }
  485. void CStringChecker::EvalBcopy(CheckerContext &C, const CallExpr *CE) {
  486. // void bcopy(const void *src, void *dst, size_t n);
  487. EvalCopyCommon(C, C.getState(), CE->getArg(2), CE->getArg(1), CE->getArg(0));
  488. }
  489. void CStringChecker::EvalMemcmp(CheckerContext &C, const CallExpr *CE) {
  490. // int memcmp(const void *s1, const void *s2, size_t n);
  491. const Expr *Left = CE->getArg(0);
  492. const Expr *Right = CE->getArg(1);
  493. const Expr *Size = CE->getArg(2);
  494. const GRState *state = C.getState();
  495. ValueManager &ValMgr = C.getValueManager();
  496. SValuator &SV = ValMgr.getSValuator();
  497. // See if the size argument is zero.
  498. SVal SizeVal = state->getSVal(Size);
  499. QualType SizeTy = Size->getType();
  500. const GRState *StZeroSize, *StNonZeroSize;
  501. llvm::tie(StZeroSize, StNonZeroSize) = AssumeZero(C, state, SizeVal, SizeTy);
  502. // If the size can be zero, the result will be 0 in that case, and we don't
  503. // have to check either of the buffers.
  504. if (StZeroSize) {
  505. state = StZeroSize;
  506. state = state->BindExpr(CE, ValMgr.makeZeroVal(CE->getType()));
  507. C.addTransition(state);
  508. }
  509. // If the size can be nonzero, we have to check the other arguments.
  510. if (StNonZeroSize) {
  511. state = StNonZeroSize;
  512. // If we know the two buffers are the same, we know the result is 0.
  513. // First, get the two buffers' addresses. Another checker will have already
  514. // made sure they're not undefined.
  515. DefinedOrUnknownSVal LV = cast<DefinedOrUnknownSVal>(state->getSVal(Left));
  516. DefinedOrUnknownSVal RV = cast<DefinedOrUnknownSVal>(state->getSVal(Right));
  517. // See if they are the same.
  518. DefinedOrUnknownSVal SameBuf = SV.EvalEQ(state, LV, RV);
  519. const GRState *StSameBuf, *StNotSameBuf;
  520. llvm::tie(StSameBuf, StNotSameBuf) = state->Assume(SameBuf);
  521. // If the two arguments might be the same buffer, we know the result is zero,
  522. // and we only need to check one size.
  523. if (StSameBuf) {
  524. state = StSameBuf;
  525. state = CheckBufferAccess(C, state, Size, Left);
  526. if (state) {
  527. state = StSameBuf->BindExpr(CE, ValMgr.makeZeroVal(CE->getType()));
  528. C.addTransition(state);
  529. }
  530. }
  531. // If the two arguments might be different buffers, we have to check the
  532. // size of both of them.
  533. if (StNotSameBuf) {
  534. state = StNotSameBuf;
  535. state = CheckBufferAccess(C, state, Size, Left, Right);
  536. if (state) {
  537. // The return value is the comparison result, which we don't know.
  538. unsigned Count = C.getNodeBuilder().getCurrentBlockCount();
  539. SVal CmpV = ValMgr.getConjuredSymbolVal(NULL, CE, CE->getType(), Count);
  540. state = state->BindExpr(CE, CmpV);
  541. C.addTransition(state);
  542. }
  543. }
  544. }
  545. }
  546. void CStringChecker::EvalStrlen(CheckerContext &C, const CallExpr *CE) {
  547. // size_t strlen(const char *s);
  548. const GRState *state = C.getState();
  549. const Expr *Arg = CE->getArg(0);
  550. SVal ArgVal = state->getSVal(Arg);
  551. // Check that the argument is non-null.
  552. state = CheckNonNull(C, state, Arg, ArgVal);
  553. if (state) {
  554. // Figure out what the length is, making sure the argument is a C string
  555. // (or something similar to a C string). If the argument is valid, the
  556. // length will be defined, and we can then set the return value.
  557. SVal StrLen = GetCStringLength(C, state, Arg, ArgVal);
  558. if (!StrLen.isUndef()) {
  559. state = state->BindExpr(CE, StrLen);
  560. C.addTransition(state);
  561. }
  562. }
  563. }
  564. //===----------------------------------------------------------------------===//
  565. // The driver method.
  566. //===----------------------------------------------------------------------===//
  567. bool CStringChecker::EvalCallExpr(CheckerContext &C, const CallExpr *CE) {
  568. // Get the callee. All the functions we care about are C functions
  569. // with simple identifiers.
  570. const GRState *state = C.getState();
  571. const Expr *Callee = CE->getCallee();
  572. const FunctionDecl *FD = state->getSVal(Callee).getAsFunctionDecl();
  573. if (!FD)
  574. return false;
  575. // Get the name of the callee. If it's a builtin, strip off the prefix.
  576. llvm::StringRef Name = FD->getName();
  577. if (Name.startswith("__builtin_"))
  578. Name = Name.substr(10);
  579. FnCheck EvalFunction = llvm::StringSwitch<FnCheck>(Name)
  580. .Cases("memcpy", "__memcpy_chk", &CStringChecker::EvalMemcpy)
  581. .Cases("memcmp", "bcmp", &CStringChecker::EvalMemcmp)
  582. .Cases("memmove", "__memmove_chk", &CStringChecker::EvalMemmove)
  583. .Case("strlen", &CStringChecker::EvalStrlen)
  584. .Case("bcopy", &CStringChecker::EvalBcopy)
  585. .Default(NULL);
  586. // If the callee isn't a string function, let another checker handle it.
  587. if (!EvalFunction)
  588. return false;
  589. // Check and evaluate the call.
  590. (this->*EvalFunction)(C, CE);
  591. return true;
  592. }