CStringChecker.cpp 77 KB

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