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