CStringChecker.cpp 73 KB

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