CStringChecker.cpp 69 KB

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