CStringChecker.cpp 72 KB

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