blob: d7c1d943540e20bc2b10b66e3302b33bc175036c [file] [log] [blame]
Anna Zaksc800f682011-10-11 16:49:54 +00001//= CStringChecker.cpp - Checks calls to C string functions --------*- C++ -*-//
Jordy Roseccbf7ee2010-07-06 23:11:01 +00002//
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
Argyrios Kyrtzidisa0decc92011-02-15 21:25:03 +000015#include "ClangSACheckers.h"
Anna Zaksf0dfc9c2012-02-17 22:35:31 +000016#include "InterCheckerAPI.h"
Jordan Rose223f0ff2013-02-09 10:09:43 +000017#include "clang/Basic/CharInfo.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000018#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
Argyrios Kyrtzidisec8605f2011-03-01 01:16:21 +000019#include "clang/StaticAnalyzer/Core/Checker.h"
Argyrios Kyrtzidis695fb502011-02-17 21:39:17 +000020#include "clang/StaticAnalyzer/Core/CheckerManager.h"
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000021#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
Ted Kremenek18c66fd2011-08-15 22:09:50 +000022#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
Benjamin Kramer00bd44d2012-02-04 12:31:12 +000023#include "llvm/ADT/STLExtras.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000024#include "llvm/ADT/SmallString.h"
Jordy Roseccbf7ee2010-07-06 23:11:01 +000025#include "llvm/ADT/StringSwitch.h"
Benjamin Kramera93d0f22012-12-01 17:12:56 +000026#include "llvm/Support/raw_ostream.h"
Jordy Roseccbf7ee2010-07-06 23:11:01 +000027
28using namespace clang;
Ted Kremenek9ef65372010-12-23 07:20:52 +000029using namespace ento;
Jordy Roseccbf7ee2010-07-06 23:11:01 +000030
31namespace {
Argyrios Kyrtzidisec8605f2011-03-01 01:16:21 +000032class CStringChecker : public Checker< eval::Call,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000033 check::PreStmt<DeclStmt>,
34 check::LiveSymbols,
35 check::DeadSymbols,
36 check::RegionChanges
37 > {
Stephen Hines651f13c2014-04-23 16:59:28 -070038 mutable std::unique_ptr<BugType> BT_Null, BT_Bounds, BT_Overlap,
39 BT_NotCString, BT_AdditionOverflow;
Anna Zaks57300762012-02-07 00:56:14 +000040
Jordy Rose9e49d9f2011-06-20 02:06:40 +000041 mutable const char *CurrentFunctionDescription;
42
Jordy Roseccbf7ee2010-07-06 23:11:01 +000043public:
Anna Zaks57300762012-02-07 00:56:14 +000044 /// The filter is used to filter out the diagnostics which are not enabled by
45 /// the user.
46 struct CStringChecksFilter {
47 DefaultBool CheckCStringNullArg;
48 DefaultBool CheckCStringOutOfBounds;
49 DefaultBool CheckCStringBufferOverlap;
50 DefaultBool CheckCStringNotNullTerm;
Stephen Hines651f13c2014-04-23 16:59:28 -070051
52 CheckName CheckNameCStringNullArg;
53 CheckName CheckNameCStringOutOfBounds;
54 CheckName CheckNameCStringBufferOverlap;
55 CheckName CheckNameCStringNotNullTerm;
Anna Zaks57300762012-02-07 00:56:14 +000056 };
57
58 CStringChecksFilter Filter;
59
Jordy Roseccbf7ee2010-07-06 23:11:01 +000060 static void *getTag() { static int tag; return &tag; }
61
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000062 bool evalCall(const CallExpr *CE, CheckerContext &C) const;
63 void checkPreStmt(const DeclStmt *DS, CheckerContext &C) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +000064 void checkLiveSymbols(ProgramStateRef state, SymbolReaper &SR) const;
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000065 void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +000066 bool wantsRegionChangeUpdate(ProgramStateRef state) const;
Jordy Rosea5261542010-08-14 21:02:52 +000067
Ted Kremenek8bef8232012-01-26 21:29:00 +000068 ProgramStateRef
69 checkRegionChanges(ProgramStateRef state,
Anna Zaksbf53dfa2012-12-20 00:38:25 +000070 const InvalidatedSymbols *,
Jordy Rose537716a2011-08-27 22:51:26 +000071 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +000072 ArrayRef<const MemRegion *> Regions,
Jordan Rose740d4902012-07-02 19:27:35 +000073 const CallEvent *Call) const;
Jordy Roseccbf7ee2010-07-06 23:11:01 +000074
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000075 typedef void (CStringChecker::*FnCheck)(CheckerContext &,
76 const CallExpr *) const;
Jordy Roseccbf7ee2010-07-06 23:11:01 +000077
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000078 void evalMemcpy(CheckerContext &C, const CallExpr *CE) const;
Lenny Maioranib8b875b2011-03-31 21:36:53 +000079 void evalMempcpy(CheckerContext &C, const CallExpr *CE) const;
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000080 void evalMemmove(CheckerContext &C, const CallExpr *CE) const;
81 void evalBcopy(CheckerContext &C, const CallExpr *CE) const;
Lenny Maioranib8b875b2011-03-31 21:36:53 +000082 void evalCopyCommon(CheckerContext &C, const CallExpr *CE,
Ted Kremenek8bef8232012-01-26 21:29:00 +000083 ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +000084 const Expr *Size,
85 const Expr *Source,
86 const Expr *Dest,
Lenny Maioranib8b875b2011-03-31 21:36:53 +000087 bool Restricted = false,
88 bool IsMempcpy = false) const;
Jordy Rosed325ffb2010-07-08 23:57:29 +000089
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000090 void evalMemcmp(CheckerContext &C, const CallExpr *CE) const;
Jordy Roseccbf7ee2010-07-06 23:11:01 +000091
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000092 void evalstrLength(CheckerContext &C, const CallExpr *CE) const;
93 void evalstrnLength(CheckerContext &C, const CallExpr *CE) const;
Ted Kremenek18c66fd2011-08-15 22:09:50 +000094 void evalstrLengthCommon(CheckerContext &C,
95 const CallExpr *CE,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000096 bool IsStrnlen = false) const;
Jordy Rose19c5dd12010-07-27 01:37:31 +000097
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000098 void evalStrcpy(CheckerContext &C, const CallExpr *CE) const;
99 void evalStrncpy(CheckerContext &C, const CallExpr *CE) const;
100 void evalStpcpy(CheckerContext &C, const CallExpr *CE) const;
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000101 void evalStrcpyCommon(CheckerContext &C,
102 const CallExpr *CE,
103 bool returnEnd,
104 bool isBounded,
105 bool isAppending) const;
Lenny Maiorani067bbd02011-04-09 15:12:58 +0000106
107 void evalStrcat(CheckerContext &C, const CallExpr *CE) const;
108 void evalStrncat(CheckerContext &C, const CallExpr *CE) const;
Jordy Rosee64f3112010-08-16 07:51:42 +0000109
Lenny Maiorani318dd922011-04-12 17:08:43 +0000110 void evalStrcmp(CheckerContext &C, const CallExpr *CE) const;
Lenny Maiorani357f6ee2011-04-25 22:21:00 +0000111 void evalStrncmp(CheckerContext &C, const CallExpr *CE) const;
Lenny Maioranibd1d16a2011-04-28 15:09:11 +0000112 void evalStrcasecmp(CheckerContext &C, const CallExpr *CE) const;
Lenny Maiorani454fd2d2011-05-02 19:05:49 +0000113 void evalStrncasecmp(CheckerContext &C, const CallExpr *CE) const;
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000114 void evalStrcmpCommon(CheckerContext &C,
115 const CallExpr *CE,
116 bool isBounded = false,
117 bool ignoreCase = false) const;
Lenny Maiorani318dd922011-04-12 17:08:43 +0000118
Jordan Roseaf226212013-04-22 23:18:42 +0000119 void evalStrsep(CheckerContext &C, const CallExpr *CE) const;
120
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000121 // Utility methods
Ted Kremenek8bef8232012-01-26 21:29:00 +0000122 std::pair<ProgramStateRef , ProgramStateRef >
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000123 static assumeZero(CheckerContext &C,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000124 ProgramStateRef state, SVal V, QualType Ty);
Jordy Rosed325ffb2010-07-08 23:57:29 +0000125
Ted Kremenek8bef8232012-01-26 21:29:00 +0000126 static ProgramStateRef setCStringLength(ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000127 const MemRegion *MR,
128 SVal strLength);
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000129 static SVal getCStringLengthForRegion(CheckerContext &C,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000130 ProgramStateRef &state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000131 const Expr *Ex,
132 const MemRegion *MR,
Jordy Rosed5af0e12011-06-15 05:52:56 +0000133 bool hypothetical);
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000134 SVal getCStringLength(CheckerContext &C,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000135 ProgramStateRef &state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000136 const Expr *Ex,
137 SVal Buf,
Jordy Rosed5af0e12011-06-15 05:52:56 +0000138 bool hypothetical = false) const;
Jordy Rose19c5dd12010-07-27 01:37:31 +0000139
Lenny Maiorani318dd922011-04-12 17:08:43 +0000140 const StringLiteral *getCStringLiteral(CheckerContext &C,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000141 ProgramStateRef &state,
Lenny Maiorani318dd922011-04-12 17:08:43 +0000142 const Expr *expr,
143 SVal val) const;
144
Ted Kremenek8bef8232012-01-26 21:29:00 +0000145 static ProgramStateRef InvalidateBuffer(CheckerContext &C,
Anton Yartsevb7a747b2013-11-17 09:18:48 +0000146 ProgramStateRef state,
147 const Expr *Ex, SVal V,
148 bool IsSourceBuffer);
Jordy Rosee64f3112010-08-16 07:51:42 +0000149
Ted Kremenek9c378f72011-08-12 23:37:29 +0000150 static bool SummarizeRegion(raw_ostream &os, ASTContext &Ctx,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000151 const MemRegion *MR);
Jordy Rose19c5dd12010-07-27 01:37:31 +0000152
153 // Re-usable checks
Ted Kremenek8bef8232012-01-26 21:29:00 +0000154 ProgramStateRef checkNonNull(CheckerContext &C,
155 ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000156 const Expr *S,
157 SVal l) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000158 ProgramStateRef CheckLocation(CheckerContext &C,
159 ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000160 const Expr *S,
161 SVal l,
162 const char *message = NULL) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000163 ProgramStateRef CheckBufferAccess(CheckerContext &C,
164 ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000165 const Expr *Size,
166 const Expr *FirstBuf,
167 const Expr *SecondBuf,
168 const char *firstMessage = NULL,
169 const char *secondMessage = NULL,
170 bool WarnAboutSize = false) const;
171
Ted Kremenek8bef8232012-01-26 21:29:00 +0000172 ProgramStateRef CheckBufferAccess(CheckerContext &C,
173 ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000174 const Expr *Size,
175 const Expr *Buf,
176 const char *message = NULL,
177 bool WarnAboutSize = false) const {
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000178 // This is a convenience override.
Jordy Rose5e5f1502011-06-20 03:49:16 +0000179 return CheckBufferAccess(C, state, Size, Buf, NULL, message, NULL,
180 WarnAboutSize);
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000181 }
Ted Kremenek8bef8232012-01-26 21:29:00 +0000182 ProgramStateRef CheckOverlap(CheckerContext &C,
183 ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000184 const Expr *Size,
185 const Expr *First,
186 const Expr *Second) const;
187 void emitOverlapBug(CheckerContext &C,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000188 ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000189 const Stmt *First,
190 const Stmt *Second) const;
191
Ted Kremenek8bef8232012-01-26 21:29:00 +0000192 ProgramStateRef checkAdditionOverflow(CheckerContext &C,
193 ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000194 NonLoc left,
195 NonLoc right) const;
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000196};
Jordy Rosea5261542010-08-14 21:02:52 +0000197
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000198} //end anonymous namespace
199
Jordan Rose166d5022012-11-02 01:54:06 +0000200REGISTER_MAP_WITH_PROGRAMSTATE(CStringLength, const MemRegion *, SVal)
Jordy Rosea5261542010-08-14 21:02:52 +0000201
Jordy Rosed325ffb2010-07-08 23:57:29 +0000202//===----------------------------------------------------------------------===//
203// Individual checks and utility methods.
204//===----------------------------------------------------------------------===//
205
Ted Kremenek8bef8232012-01-26 21:29:00 +0000206std::pair<ProgramStateRef , ProgramStateRef >
207CStringChecker::assumeZero(CheckerContext &C, ProgramStateRef state, SVal V,
Jordy Rosed325ffb2010-07-08 23:57:29 +0000208 QualType Ty) {
David Blaikiedc84cd52013-02-20 22:23:23 +0000209 Optional<DefinedSVal> val = V.getAs<DefinedSVal>();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000210 if (!val)
Ted Kremenek8bef8232012-01-26 21:29:00 +0000211 return std::pair<ProgramStateRef , ProgramStateRef >(state, state);
Jordy Rosea6b808c2010-07-07 07:48:06 +0000212
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000213 SValBuilder &svalBuilder = C.getSValBuilder();
214 DefinedOrUnknownSVal zero = svalBuilder.makeZeroVal(Ty);
215 return state->assume(svalBuilder.evalEQ(state, *val, zero));
Jordy Rosed325ffb2010-07-08 23:57:29 +0000216}
Jordy Rosea6b808c2010-07-07 07:48:06 +0000217
Ted Kremenek8bef8232012-01-26 21:29:00 +0000218ProgramStateRef CStringChecker::checkNonNull(CheckerContext &C,
219 ProgramStateRef state,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000220 const Expr *S, SVal l) const {
Jordy Rosed325ffb2010-07-08 23:57:29 +0000221 // If a previous check has failed, propagate the failure.
222 if (!state)
223 return NULL;
224
Ted Kremenek8bef8232012-01-26 21:29:00 +0000225 ProgramStateRef stateNull, stateNonNull;
Stephen Hines651f13c2014-04-23 16:59:28 -0700226 std::tie(stateNull, stateNonNull) = assumeZero(C, state, l, S->getType());
Jordy Rosed325ffb2010-07-08 23:57:29 +0000227
228 if (stateNull && !stateNonNull) {
Anna Zaks57300762012-02-07 00:56:14 +0000229 if (!Filter.CheckCStringNullArg)
230 return NULL;
231
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000232 ExplodedNode *N = C.generateSink(stateNull);
Jordy Rosea6b808c2010-07-07 07:48:06 +0000233 if (!N)
234 return NULL;
235
Jordy Rosed325ffb2010-07-08 23:57:29 +0000236 if (!BT_Null)
Stephen Hines651f13c2014-04-23 16:59:28 -0700237 BT_Null.reset(new BuiltinBug(
238 Filter.CheckNameCStringNullArg, categories::UnixAPI,
239 "Null pointer argument in call to byte string function"));
Jordy Rosea6b808c2010-07-07 07:48:06 +0000240
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000241 SmallString<80> buf;
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000242 llvm::raw_svector_ostream os(buf);
243 assert(CurrentFunctionDescription);
244 os << "Null pointer argument in call to " << CurrentFunctionDescription;
245
Jordy Rosea6b808c2010-07-07 07:48:06 +0000246 // Generate a report for this bug.
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000247 BuiltinBug *BT = static_cast<BuiltinBug*>(BT_Null.get());
Anna Zakse172e8b2011-08-17 23:00:25 +0000248 BugReport *report = new BugReport(*BT, os.str(), N);
Jordy Rosea6b808c2010-07-07 07:48:06 +0000249
250 report->addRange(S->getSourceRange());
Jordan Rosea1f81bb2012-08-28 00:50:51 +0000251 bugreporter::trackNullOrUndefValue(N, S, *report);
Jordan Rose785950e2012-11-02 01:53:40 +0000252 C.emitReport(report);
Jordy Rosea6b808c2010-07-07 07:48:06 +0000253 return NULL;
254 }
255
256 // From here on, assume that the value is non-null.
Jordy Rosed325ffb2010-07-08 23:57:29 +0000257 assert(stateNonNull);
258 return stateNonNull;
Jordy Rosea6b808c2010-07-07 07:48:06 +0000259}
260
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000261// FIXME: This was originally copied from ArrayBoundChecker.cpp. Refactor?
Ted Kremenek8bef8232012-01-26 21:29:00 +0000262ProgramStateRef CStringChecker::CheckLocation(CheckerContext &C,
263 ProgramStateRef state,
Jordy Rosee64f3112010-08-16 07:51:42 +0000264 const Expr *S, SVal l,
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000265 const char *warningMsg) const {
Jordy Rosed325ffb2010-07-08 23:57:29 +0000266 // If a previous check has failed, propagate the failure.
267 if (!state)
268 return NULL;
269
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000270 // Check for out of bound array element access.
271 const MemRegion *R = l.getAsRegion();
272 if (!R)
273 return state;
274
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000275 const ElementRegion *ER = dyn_cast<ElementRegion>(R);
276 if (!ER)
277 return state;
278
Zhongxing Xu018220c2010-08-11 06:10:55 +0000279 assert(ER->getValueType() == C.getASTContext().CharTy &&
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000280 "CheckLocation should only be called with char* ElementRegions");
281
282 // Get the size of the array.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000283 const SubRegion *superReg = cast<SubRegion>(ER->getSuperRegion());
284 SValBuilder &svalBuilder = C.getSValBuilder();
Jordy Rose1e022412011-06-16 05:51:02 +0000285 SVal Extent =
286 svalBuilder.convertToArrayIndex(superReg->getExtent(svalBuilder));
David Blaikie5251abe2013-02-20 05:52:05 +0000287 DefinedOrUnknownSVal Size = Extent.castAs<DefinedOrUnknownSVal>();
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000288
289 // Get the index of the accessed element.
David Blaikie7a95de62013-02-21 22:23:56 +0000290 DefinedOrUnknownSVal Idx = ER->getIndex().castAs<DefinedOrUnknownSVal>();
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000291
Ted Kremenek8bef8232012-01-26 21:29:00 +0000292 ProgramStateRef StInBound = state->assumeInBound(Idx, Size, true);
293 ProgramStateRef StOutBound = state->assumeInBound(Idx, Size, false);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000294 if (StOutBound && !StInBound) {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000295 ExplodedNode *N = C.generateSink(StOutBound);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000296 if (!N)
297 return NULL;
298
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000299 if (!BT_Bounds) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700300 BT_Bounds.reset(new BuiltinBug(
301 Filter.CheckNameCStringOutOfBounds, "Out-of-bound array access",
302 "Byte string function accesses out-of-bound array element"));
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000303 }
304 BuiltinBug *BT = static_cast<BuiltinBug*>(BT_Bounds.get());
305
306 // Generate a report for this bug.
Anna Zakse172e8b2011-08-17 23:00:25 +0000307 BugReport *report;
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000308 if (warningMsg) {
Anna Zakse172e8b2011-08-17 23:00:25 +0000309 report = new BugReport(*BT, warningMsg, N);
Jordy Rosee64f3112010-08-16 07:51:42 +0000310 } else {
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000311 assert(CurrentFunctionDescription);
312 assert(CurrentFunctionDescription[0] != '\0');
313
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000314 SmallString<80> buf;
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000315 llvm::raw_svector_ostream os(buf);
Jordan Rose223f0ff2013-02-09 10:09:43 +0000316 os << toUppercase(CurrentFunctionDescription[0])
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000317 << &CurrentFunctionDescription[1]
318 << " accesses out-of-bound array element";
Anna Zakse172e8b2011-08-17 23:00:25 +0000319 report = new BugReport(*BT, os.str(), N);
Jordy Rosee64f3112010-08-16 07:51:42 +0000320 }
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000321
322 // FIXME: It would be nice to eventually make this diagnostic more clear,
323 // e.g., by referencing the original declaration or by saying *why* this
324 // reference is outside the range.
325
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000326 report->addRange(S->getSourceRange());
Jordan Rose785950e2012-11-02 01:53:40 +0000327 C.emitReport(report);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000328 return NULL;
329 }
330
331 // Array bound check succeeded. From this point forward the array bound
332 // should always succeed.
333 return StInBound;
334}
335
Ted Kremenek8bef8232012-01-26 21:29:00 +0000336ProgramStateRef CStringChecker::CheckBufferAccess(CheckerContext &C,
337 ProgramStateRef state,
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000338 const Expr *Size,
339 const Expr *FirstBuf,
Jordy Rosee64f3112010-08-16 07:51:42 +0000340 const Expr *SecondBuf,
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000341 const char *firstMessage,
Jordy Rose5e5f1502011-06-20 03:49:16 +0000342 const char *secondMessage,
343 bool WarnAboutSize) const {
Jordy Rosed325ffb2010-07-08 23:57:29 +0000344 // If a previous check has failed, propagate the failure.
345 if (!state)
346 return NULL;
347
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000348 SValBuilder &svalBuilder = C.getSValBuilder();
Jordy Rose1e022412011-06-16 05:51:02 +0000349 ASTContext &Ctx = svalBuilder.getContext();
Ted Kremenek5eca4822012-01-06 22:09:28 +0000350 const LocationContext *LCtx = C.getLocationContext();
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000351
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000352 QualType sizeTy = Size->getType();
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000353 QualType PtrTy = Ctx.getPointerType(Ctx.CharTy);
354
Jordy Rosea6b808c2010-07-07 07:48:06 +0000355 // Check that the first buffer is non-null.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000356 SVal BufVal = state->getSVal(FirstBuf, LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000357 state = checkNonNull(C, state, FirstBuf, BufVal);
Jordy Rosea6b808c2010-07-07 07:48:06 +0000358 if (!state)
359 return NULL;
360
Anna Zaks57300762012-02-07 00:56:14 +0000361 // If out-of-bounds checking is turned off, skip the rest.
362 if (!Filter.CheckCStringOutOfBounds)
363 return state;
364
Jordy Rosed325ffb2010-07-08 23:57:29 +0000365 // Get the access length and make sure it is known.
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000366 // FIXME: This assumes the caller has already checked that the access length
367 // is positive. And that it's unsigned.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000368 SVal LengthVal = state->getSVal(Size, LCtx);
David Blaikiedc84cd52013-02-20 22:23:23 +0000369 Optional<NonLoc> Length = LengthVal.getAs<NonLoc>();
Jordy Rosed325ffb2010-07-08 23:57:29 +0000370 if (!Length)
371 return state;
372
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000373 // Compute the offset of the last element to be accessed: size-1.
David Blaikie5251abe2013-02-20 05:52:05 +0000374 NonLoc One = svalBuilder.makeIntVal(1, sizeTy).castAs<NonLoc>();
375 NonLoc LastOffset = svalBuilder
376 .evalBinOpNN(state, BO_Sub, *Length, One, sizeTy).castAs<NonLoc>();
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000377
Chris Lattnerfc8f0e12011-04-15 05:22:18 +0000378 // Check that the first buffer is sufficiently long.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000379 SVal BufStart = svalBuilder.evalCast(BufVal, PtrTy, FirstBuf->getType());
David Blaikiedc84cd52013-02-20 22:23:23 +0000380 if (Optional<Loc> BufLoc = BufStart.getAs<Loc>()) {
Jordy Rose5e5f1502011-06-20 03:49:16 +0000381 const Expr *warningExpr = (WarnAboutSize ? Size : FirstBuf);
382
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000383 SVal BufEnd = svalBuilder.evalBinOpLN(state, BO_Add, *BufLoc,
384 LastOffset, PtrTy);
Jordy Rose5e5f1502011-06-20 03:49:16 +0000385 state = CheckLocation(C, state, warningExpr, BufEnd, firstMessage);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000386
Jordy Roseb6a40262010-08-05 23:11:30 +0000387 // If the buffer isn't large enough, abort.
388 if (!state)
389 return NULL;
390 }
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000391
392 // If there's a second buffer, check it as well.
393 if (SecondBuf) {
Ted Kremenek5eca4822012-01-06 22:09:28 +0000394 BufVal = state->getSVal(SecondBuf, LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000395 state = checkNonNull(C, state, SecondBuf, BufVal);
Jordy Rosea6b808c2010-07-07 07:48:06 +0000396 if (!state)
397 return NULL;
398
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000399 BufStart = svalBuilder.evalCast(BufVal, PtrTy, SecondBuf->getType());
David Blaikiedc84cd52013-02-20 22:23:23 +0000400 if (Optional<Loc> BufLoc = BufStart.getAs<Loc>()) {
Jordy Rose5e5f1502011-06-20 03:49:16 +0000401 const Expr *warningExpr = (WarnAboutSize ? Size : SecondBuf);
402
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000403 SVal BufEnd = svalBuilder.evalBinOpLN(state, BO_Add, *BufLoc,
404 LastOffset, PtrTy);
Jordy Rose5e5f1502011-06-20 03:49:16 +0000405 state = CheckLocation(C, state, warningExpr, BufEnd, secondMessage);
Jordy Roseb6a40262010-08-05 23:11:30 +0000406 }
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000407 }
408
409 // Large enough or not, return this state!
410 return state;
411}
412
Ted Kremenek8bef8232012-01-26 21:29:00 +0000413ProgramStateRef CStringChecker::CheckOverlap(CheckerContext &C,
414 ProgramStateRef state,
Jordy Rosed325ffb2010-07-08 23:57:29 +0000415 const Expr *Size,
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000416 const Expr *First,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000417 const Expr *Second) const {
Anna Zaks57300762012-02-07 00:56:14 +0000418 if (!Filter.CheckCStringBufferOverlap)
419 return state;
420
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000421 // Do a simple check for overlap: if the two arguments are from the same
422 // buffer, see if the end of the first is greater than the start of the second
423 // or vice versa.
424
Jordy Rosed325ffb2010-07-08 23:57:29 +0000425 // If a previous check has failed, propagate the failure.
426 if (!state)
427 return NULL;
428
Ted Kremenek8bef8232012-01-26 21:29:00 +0000429 ProgramStateRef stateTrue, stateFalse;
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000430
431 // Get the buffer values and make sure they're known locations.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000432 const LocationContext *LCtx = C.getLocationContext();
433 SVal firstVal = state->getSVal(First, LCtx);
434 SVal secondVal = state->getSVal(Second, LCtx);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000435
David Blaikiedc84cd52013-02-20 22:23:23 +0000436 Optional<Loc> firstLoc = firstVal.getAs<Loc>();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000437 if (!firstLoc)
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000438 return state;
439
David Blaikiedc84cd52013-02-20 22:23:23 +0000440 Optional<Loc> secondLoc = secondVal.getAs<Loc>();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000441 if (!secondLoc)
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000442 return state;
443
444 // Are the two values the same?
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000445 SValBuilder &svalBuilder = C.getSValBuilder();
Stephen Hines651f13c2014-04-23 16:59:28 -0700446 std::tie(stateTrue, stateFalse) =
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000447 state->assume(svalBuilder.evalEQ(state, *firstLoc, *secondLoc));
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000448
449 if (stateTrue && !stateFalse) {
450 // If the values are known to be equal, that's automatically an overlap.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000451 emitOverlapBug(C, stateTrue, First, Second);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000452 return NULL;
453 }
454
Ted Kremenek28f47b92010-12-01 22:16:56 +0000455 // assume the two expressions are not equal.
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000456 assert(stateFalse);
457 state = stateFalse;
458
459 // Which value comes first?
Jordy Roseee2fde12011-06-16 05:56:50 +0000460 QualType cmpTy = svalBuilder.getConditionType();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000461 SVal reverse = svalBuilder.evalBinOpLL(state, BO_GT,
462 *firstLoc, *secondLoc, cmpTy);
David Blaikiedc84cd52013-02-20 22:23:23 +0000463 Optional<DefinedOrUnknownSVal> reverseTest =
David Blaikie5251abe2013-02-20 05:52:05 +0000464 reverse.getAs<DefinedOrUnknownSVal>();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000465 if (!reverseTest)
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000466 return state;
467
Stephen Hines651f13c2014-04-23 16:59:28 -0700468 std::tie(stateTrue, stateFalse) = state->assume(*reverseTest);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000469 if (stateTrue) {
470 if (stateFalse) {
471 // If we don't know which one comes first, we can't perform this test.
472 return state;
473 } else {
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000474 // Switch the values so that firstVal is before secondVal.
David Blaikie5251abe2013-02-20 05:52:05 +0000475 std::swap(firstLoc, secondLoc);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000476
477 // Switch the Exprs as well, so that they still correspond.
David Blaikie5251abe2013-02-20 05:52:05 +0000478 std::swap(First, Second);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000479 }
480 }
481
482 // Get the length, and make sure it too is known.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000483 SVal LengthVal = state->getSVal(Size, LCtx);
David Blaikiedc84cd52013-02-20 22:23:23 +0000484 Optional<NonLoc> Length = LengthVal.getAs<NonLoc>();
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000485 if (!Length)
486 return state;
487
488 // Convert the first buffer's start address to char*.
489 // Bail out if the cast fails.
Jordy Roseee2fde12011-06-16 05:56:50 +0000490 ASTContext &Ctx = svalBuilder.getContext();
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000491 QualType CharPtrTy = Ctx.getPointerType(Ctx.CharTy);
Jordy Rose1e022412011-06-16 05:51:02 +0000492 SVal FirstStart = svalBuilder.evalCast(*firstLoc, CharPtrTy,
493 First->getType());
David Blaikiedc84cd52013-02-20 22:23:23 +0000494 Optional<Loc> FirstStartLoc = FirstStart.getAs<Loc>();
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000495 if (!FirstStartLoc)
496 return state;
497
498 // Compute the end of the first buffer. Bail out if THAT fails.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000499 SVal FirstEnd = svalBuilder.evalBinOpLN(state, BO_Add,
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000500 *FirstStartLoc, *Length, CharPtrTy);
David Blaikiedc84cd52013-02-20 22:23:23 +0000501 Optional<Loc> FirstEndLoc = FirstEnd.getAs<Loc>();
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000502 if (!FirstEndLoc)
503 return state;
504
505 // Is the end of the first buffer past the start of the second buffer?
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000506 SVal Overlap = svalBuilder.evalBinOpLL(state, BO_GT,
507 *FirstEndLoc, *secondLoc, cmpTy);
David Blaikiedc84cd52013-02-20 22:23:23 +0000508 Optional<DefinedOrUnknownSVal> OverlapTest =
David Blaikie5251abe2013-02-20 05:52:05 +0000509 Overlap.getAs<DefinedOrUnknownSVal>();
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000510 if (!OverlapTest)
511 return state;
512
Stephen Hines651f13c2014-04-23 16:59:28 -0700513 std::tie(stateTrue, stateFalse) = state->assume(*OverlapTest);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000514
515 if (stateTrue && !stateFalse) {
516 // Overlap!
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000517 emitOverlapBug(C, stateTrue, First, Second);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000518 return NULL;
519 }
520
Ted Kremenek28f47b92010-12-01 22:16:56 +0000521 // assume the two expressions don't overlap.
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000522 assert(stateFalse);
523 return stateFalse;
524}
525
Ted Kremenek8bef8232012-01-26 21:29:00 +0000526void CStringChecker::emitOverlapBug(CheckerContext &C, ProgramStateRef state,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000527 const Stmt *First, const Stmt *Second) const {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000528 ExplodedNode *N = C.generateSink(state);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000529 if (!N)
530 return;
531
532 if (!BT_Overlap)
Stephen Hines651f13c2014-04-23 16:59:28 -0700533 BT_Overlap.reset(new BugType(Filter.CheckNameCStringBufferOverlap,
534 categories::UnixAPI, "Improper arguments"));
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000535
536 // Generate a report for this bug.
Anna Zakse172e8b2011-08-17 23:00:25 +0000537 BugReport *report =
538 new BugReport(*BT_Overlap,
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000539 "Arguments must not be overlapping buffers", N);
540 report->addRange(First->getSourceRange());
541 report->addRange(Second->getSourceRange());
542
Jordan Rose785950e2012-11-02 01:53:40 +0000543 C.emitReport(report);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000544}
545
Ted Kremenek8bef8232012-01-26 21:29:00 +0000546ProgramStateRef CStringChecker::checkAdditionOverflow(CheckerContext &C,
547 ProgramStateRef state,
Jordy Rosed5af0e12011-06-15 05:52:56 +0000548 NonLoc left,
549 NonLoc right) const {
Anna Zaks57300762012-02-07 00:56:14 +0000550 // If out-of-bounds checking is turned off, skip the rest.
551 if (!Filter.CheckCStringOutOfBounds)
552 return state;
553
Jordy Rosed5af0e12011-06-15 05:52:56 +0000554 // If a previous check has failed, propagate the failure.
555 if (!state)
556 return NULL;
557
558 SValBuilder &svalBuilder = C.getSValBuilder();
559 BasicValueFactory &BVF = svalBuilder.getBasicValueFactory();
560
561 QualType sizeTy = svalBuilder.getContext().getSizeType();
562 const llvm::APSInt &maxValInt = BVF.getMaxValue(sizeTy);
563 NonLoc maxVal = svalBuilder.makeIntVal(maxValInt);
564
Anna Zakse3d250e2011-12-11 18:43:40 +0000565 SVal maxMinusRight;
David Blaikie5251abe2013-02-20 05:52:05 +0000566 if (right.getAs<nonloc::ConcreteInt>()) {
Anna Zakse3d250e2011-12-11 18:43:40 +0000567 maxMinusRight = svalBuilder.evalBinOpNN(state, BO_Sub, maxVal, right,
568 sizeTy);
569 } else {
Jordy Rosed5af0e12011-06-15 05:52:56 +0000570 // Try switching the operands. (The order of these two assignments is
571 // important!)
572 maxMinusRight = svalBuilder.evalBinOpNN(state, BO_Sub, maxVal, left,
573 sizeTy);
574 left = right;
575 }
576
David Blaikiedc84cd52013-02-20 22:23:23 +0000577 if (Optional<NonLoc> maxMinusRightNL = maxMinusRight.getAs<NonLoc>()) {
Jordy Rosed5af0e12011-06-15 05:52:56 +0000578 QualType cmpTy = svalBuilder.getConditionType();
579 // If left > max - right, we have an overflow.
580 SVal willOverflow = svalBuilder.evalBinOpNN(state, BO_GT, left,
581 *maxMinusRightNL, cmpTy);
582
Ted Kremenek8bef8232012-01-26 21:29:00 +0000583 ProgramStateRef stateOverflow, stateOkay;
Stephen Hines651f13c2014-04-23 16:59:28 -0700584 std::tie(stateOverflow, stateOkay) =
David Blaikie5251abe2013-02-20 05:52:05 +0000585 state->assume(willOverflow.castAs<DefinedOrUnknownSVal>());
Jordy Rosed5af0e12011-06-15 05:52:56 +0000586
587 if (stateOverflow && !stateOkay) {
588 // We have an overflow. Emit a bug report.
589 ExplodedNode *N = C.generateSink(stateOverflow);
590 if (!N)
591 return NULL;
592
593 if (!BT_AdditionOverflow)
Stephen Hines651f13c2014-04-23 16:59:28 -0700594 BT_AdditionOverflow.reset(
595 new BuiltinBug(Filter.CheckNameCStringOutOfBounds, "API",
596 "Sum of expressions causes overflow"));
Jordy Rosed5af0e12011-06-15 05:52:56 +0000597
Jordy Rosed5af0e12011-06-15 05:52:56 +0000598 // This isn't a great error message, but this should never occur in real
599 // code anyway -- you'd have to create a buffer longer than a size_t can
600 // represent, which is sort of a contradiction.
Jordy Rose8cc24912011-06-20 03:51:53 +0000601 const char *warning =
602 "This expression will create a string whose length is too big to "
603 "be represented as a size_t";
Jordy Rosed5af0e12011-06-15 05:52:56 +0000604
605 // Generate a report for this bug.
Jordy Rose8cc24912011-06-20 03:51:53 +0000606 BugReport *report = new BugReport(*BT_AdditionOverflow, warning, N);
Jordan Rose785950e2012-11-02 01:53:40 +0000607 C.emitReport(report);
Jordy Rosed5af0e12011-06-15 05:52:56 +0000608
609 return NULL;
610 }
611
612 // From now on, assume an overflow didn't occur.
613 assert(stateOkay);
614 state = stateOkay;
615 }
616
617 return state;
618}
619
Ted Kremenek8bef8232012-01-26 21:29:00 +0000620ProgramStateRef CStringChecker::setCStringLength(ProgramStateRef state,
Jordy Rosee64f3112010-08-16 07:51:42 +0000621 const MemRegion *MR,
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000622 SVal strLength) {
623 assert(!strLength.isUndef() && "Attempt to set an undefined string length");
Jordy Rosee64f3112010-08-16 07:51:42 +0000624
625 MR = MR->StripCasts();
626
627 switch (MR->getKind()) {
628 case MemRegion::StringRegionKind:
629 // FIXME: This can happen if we strcpy() into a string region. This is
630 // undefined [C99 6.4.5p6], but we should still warn about it.
631 return state;
632
633 case MemRegion::SymbolicRegionKind:
634 case MemRegion::AllocaRegionKind:
635 case MemRegion::VarRegionKind:
636 case MemRegion::FieldRegionKind:
637 case MemRegion::ObjCIvarRegionKind:
Jordy Rose210c05b2011-06-15 05:14:03 +0000638 // These are the types we can currently track string lengths for.
639 break;
Jordy Rosee64f3112010-08-16 07:51:42 +0000640
641 case MemRegion::ElementRegionKind:
642 // FIXME: Handle element regions by upper-bounding the parent region's
643 // string length.
644 return state;
645
646 default:
647 // Other regions (mostly non-data) can't have a reliable C string length.
648 // For now, just ignore the change.
649 // FIXME: These are rare but not impossible. We should output some kind of
650 // warning for things like strcpy((char[]){'a', 0}, "b");
651 return state;
652 }
Jordy Rose210c05b2011-06-15 05:14:03 +0000653
654 if (strLength.isUnknown())
655 return state->remove<CStringLength>(MR);
656
657 return state->set<CStringLength>(MR, strLength);
Jordy Rosee64f3112010-08-16 07:51:42 +0000658}
659
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000660SVal CStringChecker::getCStringLengthForRegion(CheckerContext &C,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000661 ProgramStateRef &state,
Jordy Rosea5261542010-08-14 21:02:52 +0000662 const Expr *Ex,
Jordy Rosed5af0e12011-06-15 05:52:56 +0000663 const MemRegion *MR,
664 bool hypothetical) {
665 if (!hypothetical) {
666 // If there's a recorded length, go ahead and return it.
667 const SVal *Recorded = state->get<CStringLength>(MR);
668 if (Recorded)
669 return *Recorded;
670 }
Jordan Rosea728e922013-08-19 16:27:34 +0000671
Jordy Rosea5261542010-08-14 21:02:52 +0000672 // Otherwise, get a new symbol and update the state.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000673 SValBuilder &svalBuilder = C.getSValBuilder();
674 QualType sizeTy = svalBuilder.getContext().getSizeType();
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000675 SVal strLength = svalBuilder.getMetadataSymbolVal(CStringChecker::getTag(),
Ted Kremenek66c486f2012-08-22 06:26:15 +0000676 MR, Ex, sizeTy,
677 C.blockCount());
Jordy Rosed5af0e12011-06-15 05:52:56 +0000678
Jordan Rosea728e922013-08-19 16:27:34 +0000679 if (!hypothetical) {
680 if (Optional<NonLoc> strLn = strLength.getAs<NonLoc>()) {
681 // In case of unbounded calls strlen etc bound the range to SIZE_MAX/4
682 BasicValueFactory &BVF = svalBuilder.getBasicValueFactory();
683 const llvm::APSInt &maxValInt = BVF.getMaxValue(sizeTy);
684 llvm::APSInt fourInt = APSIntType(maxValInt).getValue(4);
685 const llvm::APSInt *maxLengthInt = BVF.evalAPSInt(BO_Div, maxValInt,
686 fourInt);
687 NonLoc maxLength = svalBuilder.makeIntVal(*maxLengthInt);
688 SVal evalLength = svalBuilder.evalBinOpNN(state, BO_LE, *strLn,
689 maxLength, sizeTy);
690 state = state->assume(evalLength.castAs<DefinedOrUnknownSVal>(), true);
691 }
Jordy Rosed5af0e12011-06-15 05:52:56 +0000692 state = state->set<CStringLength>(MR, strLength);
Jordan Rosea728e922013-08-19 16:27:34 +0000693 }
Jordy Rosed5af0e12011-06-15 05:52:56 +0000694
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000695 return strLength;
Jordy Rosea5261542010-08-14 21:02:52 +0000696}
697
Ted Kremenek8bef8232012-01-26 21:29:00 +0000698SVal CStringChecker::getCStringLength(CheckerContext &C, ProgramStateRef &state,
Jordy Rosed5af0e12011-06-15 05:52:56 +0000699 const Expr *Ex, SVal Buf,
700 bool hypothetical) const {
Jordy Rose19c5dd12010-07-27 01:37:31 +0000701 const MemRegion *MR = Buf.getAsRegion();
702 if (!MR) {
703 // If we can't get a region, see if it's something we /know/ isn't a
704 // C string. In the context of locations, the only time we can issue such
705 // a warning is for labels.
David Blaikiedc84cd52013-02-20 22:23:23 +0000706 if (Optional<loc::GotoLabel> Label = Buf.getAs<loc::GotoLabel>()) {
Anna Zaks57300762012-02-07 00:56:14 +0000707 if (!Filter.CheckCStringNotNullTerm)
708 return UndefinedVal();
709
Anna Zaks0bd6b112011-10-26 21:06:34 +0000710 if (ExplodedNode *N = C.addTransition(state)) {
Jordy Rose19c5dd12010-07-27 01:37:31 +0000711 if (!BT_NotCString)
Stephen Hines651f13c2014-04-23 16:59:28 -0700712 BT_NotCString.reset(new BuiltinBug(
713 Filter.CheckNameCStringNotNullTerm, categories::UnixAPI,
714 "Argument is not a null-terminated string."));
Jordy Rose19c5dd12010-07-27 01:37:31 +0000715
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000716 SmallString<120> buf;
Jordy Rose19c5dd12010-07-27 01:37:31 +0000717 llvm::raw_svector_ostream os(buf);
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000718 assert(CurrentFunctionDescription);
719 os << "Argument to " << CurrentFunctionDescription
720 << " is the address of the label '" << Label->getLabel()->getName()
Jordy Rose19c5dd12010-07-27 01:37:31 +0000721 << "', which is not a null-terminated string";
722
723 // Generate a report for this bug.
Stephen Hines651f13c2014-04-23 16:59:28 -0700724 BugReport *report = new BugReport(*BT_NotCString, os.str(), N);
Jordy Rose19c5dd12010-07-27 01:37:31 +0000725
726 report->addRange(Ex->getSourceRange());
Jordan Rose785950e2012-11-02 01:53:40 +0000727 C.emitReport(report);
Jordy Rose19c5dd12010-07-27 01:37:31 +0000728 }
Jordy Rose19c5dd12010-07-27 01:37:31 +0000729 return UndefinedVal();
Anna Zaks57300762012-02-07 00:56:14 +0000730
Jordy Rose19c5dd12010-07-27 01:37:31 +0000731 }
732
Jordy Rosea5261542010-08-14 21:02:52 +0000733 // If it's not a region and not a label, give up.
734 return UnknownVal();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000735 }
736
Jordy Rosea5261542010-08-14 21:02:52 +0000737 // If we have a region, strip casts from it and see if we can figure out
738 // its length. For anything we can't figure out, just return UnknownVal.
739 MR = MR->StripCasts();
740
741 switch (MR->getKind()) {
742 case MemRegion::StringRegionKind: {
743 // Modifying the contents of string regions is undefined [C99 6.4.5p6],
744 // so we can assume that the byte length is the correct C string length.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000745 SValBuilder &svalBuilder = C.getSValBuilder();
746 QualType sizeTy = svalBuilder.getContext().getSizeType();
747 const StringLiteral *strLit = cast<StringRegion>(MR)->getStringLiteral();
748 return svalBuilder.makeIntVal(strLit->getByteLength(), sizeTy);
Jordy Rosea5261542010-08-14 21:02:52 +0000749 }
750 case MemRegion::SymbolicRegionKind:
751 case MemRegion::AllocaRegionKind:
752 case MemRegion::VarRegionKind:
753 case MemRegion::FieldRegionKind:
754 case MemRegion::ObjCIvarRegionKind:
Jordy Rosed5af0e12011-06-15 05:52:56 +0000755 return getCStringLengthForRegion(C, state, Ex, MR, hypothetical);
Jordy Rosea5261542010-08-14 21:02:52 +0000756 case MemRegion::CompoundLiteralRegionKind:
757 // FIXME: Can we track this? Is it necessary?
758 return UnknownVal();
759 case MemRegion::ElementRegionKind:
760 // FIXME: How can we handle this? It's not good enough to subtract the
761 // offset from the base string length; consider "123\x00567" and &a[5].
762 return UnknownVal();
763 default:
764 // Other regions (mostly non-data) can't have a reliable C string length.
765 // In this case, an error is emitted and UndefinedVal is returned.
766 // The caller should always be prepared to handle this case.
Anna Zaks57300762012-02-07 00:56:14 +0000767 if (!Filter.CheckCStringNotNullTerm)
768 return UndefinedVal();
769
Anna Zaks0bd6b112011-10-26 21:06:34 +0000770 if (ExplodedNode *N = C.addTransition(state)) {
Jordy Rosea5261542010-08-14 21:02:52 +0000771 if (!BT_NotCString)
Stephen Hines651f13c2014-04-23 16:59:28 -0700772 BT_NotCString.reset(new BuiltinBug(
773 Filter.CheckNameCStringNotNullTerm, categories::UnixAPI,
774 "Argument is not a null-terminated string."));
Jordy Rosea5261542010-08-14 21:02:52 +0000775
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000776 SmallString<120> buf;
Jordy Rosea5261542010-08-14 21:02:52 +0000777 llvm::raw_svector_ostream os(buf);
778
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000779 assert(CurrentFunctionDescription);
780 os << "Argument to " << CurrentFunctionDescription << " is ";
Jordy Rosea5261542010-08-14 21:02:52 +0000781
782 if (SummarizeRegion(os, C.getASTContext(), MR))
783 os << ", which is not a null-terminated string";
784 else
785 os << "not a null-terminated string";
786
787 // Generate a report for this bug.
Anna Zakse172e8b2011-08-17 23:00:25 +0000788 BugReport *report = new BugReport(*BT_NotCString,
Jordy Rosea5261542010-08-14 21:02:52 +0000789 os.str(), N);
790
791 report->addRange(Ex->getSourceRange());
Jordan Rose785950e2012-11-02 01:53:40 +0000792 C.emitReport(report);
Jordy Rosea5261542010-08-14 21:02:52 +0000793 }
794
795 return UndefinedVal();
796 }
Jordy Rose19c5dd12010-07-27 01:37:31 +0000797}
798
Lenny Maiorani318dd922011-04-12 17:08:43 +0000799const StringLiteral *CStringChecker::getCStringLiteral(CheckerContext &C,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000800 ProgramStateRef &state, const Expr *expr, SVal val) const {
Lenny Maiorani318dd922011-04-12 17:08:43 +0000801
802 // Get the memory region pointed to by the val.
803 const MemRegion *bufRegion = val.getAsRegion();
804 if (!bufRegion)
805 return NULL;
806
807 // Strip casts off the memory region.
808 bufRegion = bufRegion->StripCasts();
809
810 // Cast the memory region to a string region.
811 const StringRegion *strRegion= dyn_cast<StringRegion>(bufRegion);
812 if (!strRegion)
813 return NULL;
814
815 // Return the actual string in the string region.
816 return strRegion->getStringLiteral();
817}
818
Ted Kremenek8bef8232012-01-26 21:29:00 +0000819ProgramStateRef CStringChecker::InvalidateBuffer(CheckerContext &C,
Anton Yartsevb7a747b2013-11-17 09:18:48 +0000820 ProgramStateRef state,
821 const Expr *E, SVal V,
822 bool IsSourceBuffer) {
David Blaikiedc84cd52013-02-20 22:23:23 +0000823 Optional<Loc> L = V.getAs<Loc>();
Jordy Rosee64f3112010-08-16 07:51:42 +0000824 if (!L)
825 return state;
826
827 // FIXME: This is a simplified version of what's in CFRefCount.cpp -- it makes
828 // some assumptions about the value that CFRefCount can't. Even so, it should
829 // probably be refactored.
David Blaikiedc84cd52013-02-20 22:23:23 +0000830 if (Optional<loc::MemRegionVal> MR = L->getAs<loc::MemRegionVal>()) {
Jordy Rosee64f3112010-08-16 07:51:42 +0000831 const MemRegion *R = MR->getRegion()->StripCasts();
832
833 // Are we dealing with an ElementRegion? If so, we should be invalidating
834 // the super-region.
835 if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
836 R = ER->getSuperRegion();
837 // FIXME: What about layers of ElementRegions?
838 }
839
840 // Invalidate this region.
Ted Kremenek3133f792012-02-17 23:13:45 +0000841 const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
Anton Yartsevb7a747b2013-11-17 09:18:48 +0000842
843 bool CausesPointerEscape = false;
844 RegionAndSymbolInvalidationTraits ITraits;
845 // Invalidate and escape only indirect regions accessible through the source
846 // buffer.
847 if (IsSourceBuffer) {
848 ITraits.setTrait(R,
849 RegionAndSymbolInvalidationTraits::TK_PreserveContents);
850 ITraits.setTrait(R, RegionAndSymbolInvalidationTraits::TK_SuppressEscape);
851 CausesPointerEscape = true;
852 }
853
854 return state->invalidateRegions(R, E, C.blockCount(), LCtx,
855 CausesPointerEscape, 0, 0, &ITraits);
Jordy Rosee64f3112010-08-16 07:51:42 +0000856 }
857
858 // If we have a non-region value by chance, just remove the binding.
859 // FIXME: is this necessary or correct? This handles the non-Region
860 // cases. Is it ever valid to store to these?
Ted Kremenek56a46b52012-08-22 06:37:46 +0000861 return state->killBinding(*L);
Jordy Rosee64f3112010-08-16 07:51:42 +0000862}
863
Ted Kremenek9c378f72011-08-12 23:37:29 +0000864bool CStringChecker::SummarizeRegion(raw_ostream &os, ASTContext &Ctx,
Jordy Rose19c5dd12010-07-27 01:37:31 +0000865 const MemRegion *MR) {
Ted Kremenek96979342011-08-12 20:02:48 +0000866 const TypedValueRegion *TVR = dyn_cast<TypedValueRegion>(MR);
Jordy Rose19c5dd12010-07-27 01:37:31 +0000867
Jordy Rose096aef92011-08-12 21:41:07 +0000868 switch (MR->getKind()) {
Jordy Rose19c5dd12010-07-27 01:37:31 +0000869 case MemRegion::FunctionTextRegionKind: {
Anna Zaks5fc1d0c2012-09-17 19:13:56 +0000870 const NamedDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000871 if (FD)
Benjamin Kramerb8989f22011-10-14 18:45:37 +0000872 os << "the address of the function '" << *FD << '\'';
Jordy Rose19c5dd12010-07-27 01:37:31 +0000873 else
874 os << "the address of a function";
875 return true;
876 }
877 case MemRegion::BlockTextRegionKind:
878 os << "block text";
879 return true;
880 case MemRegion::BlockDataRegionKind:
881 os << "a block";
882 return true;
883 case MemRegion::CXXThisRegionKind:
Zhongxing Xu02fe28c2010-11-26 08:52:48 +0000884 case MemRegion::CXXTempObjectRegionKind:
Ted Kremenek96979342011-08-12 20:02:48 +0000885 os << "a C++ temp object of type " << TVR->getValueType().getAsString();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000886 return true;
887 case MemRegion::VarRegionKind:
Ted Kremenek96979342011-08-12 20:02:48 +0000888 os << "a variable of type" << TVR->getValueType().getAsString();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000889 return true;
890 case MemRegion::FieldRegionKind:
Ted Kremenek96979342011-08-12 20:02:48 +0000891 os << "a field of type " << TVR->getValueType().getAsString();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000892 return true;
893 case MemRegion::ObjCIvarRegionKind:
Ted Kremenek96979342011-08-12 20:02:48 +0000894 os << "an instance variable of type " << TVR->getValueType().getAsString();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000895 return true;
896 default:
897 return false;
898 }
899}
900
Jordy Rosed325ffb2010-07-08 23:57:29 +0000901//===----------------------------------------------------------------------===//
Ted Kremenek9c149532010-12-01 21:57:22 +0000902// evaluation of individual function calls.
Jordy Rosed325ffb2010-07-08 23:57:29 +0000903//===----------------------------------------------------------------------===//
904
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000905void CStringChecker::evalCopyCommon(CheckerContext &C,
906 const CallExpr *CE,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000907 ProgramStateRef state,
Jordy Rosed325ffb2010-07-08 23:57:29 +0000908 const Expr *Size, const Expr *Dest,
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000909 const Expr *Source, bool Restricted,
910 bool IsMempcpy) const {
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000911 CurrentFunctionDescription = "memory copy function";
912
Jordy Rosed325ffb2010-07-08 23:57:29 +0000913 // See if the size argument is zero.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000914 const LocationContext *LCtx = C.getLocationContext();
915 SVal sizeVal = state->getSVal(Size, LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000916 QualType sizeTy = Size->getType();
Jordy Rosed325ffb2010-07-08 23:57:29 +0000917
Ted Kremenek8bef8232012-01-26 21:29:00 +0000918 ProgramStateRef stateZeroSize, stateNonZeroSize;
Stephen Hines651f13c2014-04-23 16:59:28 -0700919 std::tie(stateZeroSize, stateNonZeroSize) =
Jordy Rose1e022412011-06-16 05:51:02 +0000920 assumeZero(C, state, sizeVal, sizeTy);
Jordy Rosed325ffb2010-07-08 23:57:29 +0000921
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000922 // Get the value of the Dest.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000923 SVal destVal = state->getSVal(Dest, LCtx);
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000924
925 // If the size is zero, there won't be any actual memory access, so
926 // just bind the return value to the destination buffer and return.
Anna Zaksdd160f32012-05-03 18:21:28 +0000927 if (stateZeroSize && !stateNonZeroSize) {
Ted Kremenek5eca4822012-01-06 22:09:28 +0000928 stateZeroSize = stateZeroSize->BindExpr(CE, LCtx, destVal);
Anna Zaks0bd6b112011-10-26 21:06:34 +0000929 C.addTransition(stateZeroSize);
Anna Zaksdd160f32012-05-03 18:21:28 +0000930 return;
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000931 }
Jordy Rosed325ffb2010-07-08 23:57:29 +0000932
933 // If the size can be nonzero, we have to check the other arguments.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000934 if (stateNonZeroSize) {
Jordy Rose22d27172011-06-04 00:04:22 +0000935 state = stateNonZeroSize;
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000936
937 // Ensure the destination is not null. If it is NULL there will be a
938 // NULL pointer dereference.
939 state = checkNonNull(C, state, Dest, destVal);
940 if (!state)
941 return;
942
943 // Get the value of the Src.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000944 SVal srcVal = state->getSVal(Source, LCtx);
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000945
946 // Ensure the source is not null. If it is NULL there will be a
947 // NULL pointer dereference.
948 state = checkNonNull(C, state, Source, srcVal);
949 if (!state)
950 return;
951
Jordy Rose7182b962011-06-04 01:50:25 +0000952 // Ensure the accesses are valid and that the buffers do not overlap.
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000953 const char * const writeWarning =
954 "Memory copy function overflows destination buffer";
Jordy Rosee64f3112010-08-16 07:51:42 +0000955 state = CheckBufferAccess(C, state, Size, Dest, Source,
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000956 writeWarning, /* sourceWarning = */ NULL);
Jordy Rosed325ffb2010-07-08 23:57:29 +0000957 if (Restricted)
958 state = CheckOverlap(C, state, Size, Dest, Source);
Jordy Rosee64f3112010-08-16 07:51:42 +0000959
Jordy Rose7182b962011-06-04 01:50:25 +0000960 if (!state)
961 return;
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000962
Jordy Rose7182b962011-06-04 01:50:25 +0000963 // If this is mempcpy, get the byte after the last byte copied and
964 // bind the expr.
965 if (IsMempcpy) {
David Blaikie5251abe2013-02-20 05:52:05 +0000966 loc::MemRegionVal destRegVal = destVal.castAs<loc::MemRegionVal>();
Jordy Rose7182b962011-06-04 01:50:25 +0000967
968 // Get the length to copy.
David Blaikiedc84cd52013-02-20 22:23:23 +0000969 if (Optional<NonLoc> lenValNonLoc = sizeVal.getAs<NonLoc>()) {
Jordy Rose7182b962011-06-04 01:50:25 +0000970 // Get the byte after the last byte copied.
971 SVal lastElement = C.getSValBuilder().evalBinOpLN(state, BO_Add,
David Blaikie5251abe2013-02-20 05:52:05 +0000972 destRegVal,
Jordy Rose7182b962011-06-04 01:50:25 +0000973 *lenValNonLoc,
974 Dest->getType());
975
976 // The byte after the last byte copied is the return value.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000977 state = state->BindExpr(CE, LCtx, lastElement);
Jordy Rose3f8bb2f2011-06-04 01:47:27 +0000978 } else {
Jordy Rose7182b962011-06-04 01:50:25 +0000979 // If we don't know how much we copied, we can at least
980 // conjure a return value for later.
Ted Kremenek66c486f2012-08-22 06:26:15 +0000981 SVal result = C.getSValBuilder().conjureSymbolVal(0, CE, LCtx,
982 C.blockCount());
Ted Kremenek5eca4822012-01-06 22:09:28 +0000983 state = state->BindExpr(CE, LCtx, result);
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000984 }
985
Jordy Rose7182b962011-06-04 01:50:25 +0000986 } else {
987 // All other copies return the destination buffer.
988 // (Well, bcopy() has a void return type, but this won't hurt.)
Ted Kremenek5eca4822012-01-06 22:09:28 +0000989 state = state->BindExpr(CE, LCtx, destVal);
Jordy Rosee64f3112010-08-16 07:51:42 +0000990 }
Jordy Rose7182b962011-06-04 01:50:25 +0000991
Anton Yartsevb7a747b2013-11-17 09:18:48 +0000992 // Invalidate the destination (regular invalidation without pointer-escaping
993 // the address of the top-level region).
Jordy Rose7182b962011-06-04 01:50:25 +0000994 // FIXME: Even if we can't perfectly model the copy, we should see if we
995 // can use LazyCompoundVals to copy the source values into the destination.
996 // This would probably remove any existing bindings past the end of the
997 // copied region, but that's still an improvement over blank invalidation.
Anton Yartsevb7a747b2013-11-17 09:18:48 +0000998 state = InvalidateBuffer(C, state, Dest, C.getSVal(Dest),
999 /*IsSourceBuffer*/false);
1000
1001 // Invalidate the source (const-invalidation without const-pointer-escaping
1002 // the address of the top-level region).
1003 state = InvalidateBuffer(C, state, Source, C.getSVal(Source),
1004 /*IsSourceBuffer*/true);
1005
Anna Zaks0bd6b112011-10-26 21:06:34 +00001006 C.addTransition(state);
Jordy Rosed325ffb2010-07-08 23:57:29 +00001007 }
1008}
1009
1010
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001011void CStringChecker::evalMemcpy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001012 if (CE->getNumArgs() < 3)
1013 return;
1014
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001015 // void *memcpy(void *restrict dst, const void *restrict src, size_t n);
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001016 // The return value is the address of the destination buffer.
Jordy Rosed325ffb2010-07-08 23:57:29 +00001017 const Expr *Dest = CE->getArg(0);
Ted Kremenek8bef8232012-01-26 21:29:00 +00001018 ProgramStateRef state = C.getState();
Jordy Rose3f8bb2f2011-06-04 01:47:27 +00001019
Lenny Maioranib8b875b2011-03-31 21:36:53 +00001020 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1), true);
1021}
1022
1023void CStringChecker::evalMempcpy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001024 if (CE->getNumArgs() < 3)
1025 return;
1026
Lenny Maioranib8b875b2011-03-31 21:36:53 +00001027 // void *mempcpy(void *restrict dst, const void *restrict src, size_t n);
1028 // The return value is a pointer to the byte following the last written byte.
1029 const Expr *Dest = CE->getArg(0);
Ted Kremenek8bef8232012-01-26 21:29:00 +00001030 ProgramStateRef state = C.getState();
Lenny Maioranib8b875b2011-03-31 21:36:53 +00001031
1032 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1), true, true);
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001033}
1034
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001035void CStringChecker::evalMemmove(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001036 if (CE->getNumArgs() < 3)
1037 return;
1038
Jordy Rosed325ffb2010-07-08 23:57:29 +00001039 // void *memmove(void *dst, const void *src, size_t n);
1040 // The return value is the address of the destination buffer.
1041 const Expr *Dest = CE->getArg(0);
Ted Kremenek8bef8232012-01-26 21:29:00 +00001042 ProgramStateRef state = C.getState();
Jordy Rose3f8bb2f2011-06-04 01:47:27 +00001043
Lenny Maioranib8b875b2011-03-31 21:36:53 +00001044 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1));
Jordy Rosed325ffb2010-07-08 23:57:29 +00001045}
1046
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001047void CStringChecker::evalBcopy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001048 if (CE->getNumArgs() < 3)
1049 return;
1050
Jordy Rosed325ffb2010-07-08 23:57:29 +00001051 // void bcopy(const void *src, void *dst, size_t n);
Lenny Maioranib8b875b2011-03-31 21:36:53 +00001052 evalCopyCommon(C, CE, C.getState(),
1053 CE->getArg(2), CE->getArg(1), CE->getArg(0));
Jordy Rosed325ffb2010-07-08 23:57:29 +00001054}
1055
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001056void CStringChecker::evalMemcmp(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001057 if (CE->getNumArgs() < 3)
1058 return;
1059
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001060 // int memcmp(const void *s1, const void *s2, size_t n);
Jordy Rose9e49d9f2011-06-20 02:06:40 +00001061 CurrentFunctionDescription = "memory comparison function";
1062
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001063 const Expr *Left = CE->getArg(0);
1064 const Expr *Right = CE->getArg(1);
1065 const Expr *Size = CE->getArg(2);
1066
Ted Kremenek8bef8232012-01-26 21:29:00 +00001067 ProgramStateRef state = C.getState();
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001068 SValBuilder &svalBuilder = C.getSValBuilder();
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001069
Jordy Rosed325ffb2010-07-08 23:57:29 +00001070 // See if the size argument is zero.
Ted Kremenek5eca4822012-01-06 22:09:28 +00001071 const LocationContext *LCtx = C.getLocationContext();
1072 SVal sizeVal = state->getSVal(Size, LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001073 QualType sizeTy = Size->getType();
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001074
Ted Kremenek8bef8232012-01-26 21:29:00 +00001075 ProgramStateRef stateZeroSize, stateNonZeroSize;
Stephen Hines651f13c2014-04-23 16:59:28 -07001076 std::tie(stateZeroSize, stateNonZeroSize) =
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001077 assumeZero(C, state, sizeVal, sizeTy);
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001078
Jordy Rosed325ffb2010-07-08 23:57:29 +00001079 // If the size can be zero, the result will be 0 in that case, and we don't
1080 // have to check either of the buffers.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001081 if (stateZeroSize) {
1082 state = stateZeroSize;
Ted Kremenek5eca4822012-01-06 22:09:28 +00001083 state = state->BindExpr(CE, LCtx,
1084 svalBuilder.makeZeroVal(CE->getType()));
Anna Zaks0bd6b112011-10-26 21:06:34 +00001085 C.addTransition(state);
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001086 }
1087
Jordy Rosed325ffb2010-07-08 23:57:29 +00001088 // If the size can be nonzero, we have to check the other arguments.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001089 if (stateNonZeroSize) {
1090 state = stateNonZeroSize;
Jordy Rosed325ffb2010-07-08 23:57:29 +00001091 // If we know the two buffers are the same, we know the result is 0.
1092 // First, get the two buffers' addresses. Another checker will have already
1093 // made sure they're not undefined.
Ted Kremenek5eca4822012-01-06 22:09:28 +00001094 DefinedOrUnknownSVal LV =
David Blaikie5251abe2013-02-20 05:52:05 +00001095 state->getSVal(Left, LCtx).castAs<DefinedOrUnknownSVal>();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001096 DefinedOrUnknownSVal RV =
David Blaikie5251abe2013-02-20 05:52:05 +00001097 state->getSVal(Right, LCtx).castAs<DefinedOrUnknownSVal>();
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001098
Jordy Rosed325ffb2010-07-08 23:57:29 +00001099 // See if they are the same.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001100 DefinedOrUnknownSVal SameBuf = svalBuilder.evalEQ(state, LV, RV);
Ted Kremenek8bef8232012-01-26 21:29:00 +00001101 ProgramStateRef StSameBuf, StNotSameBuf;
Stephen Hines651f13c2014-04-23 16:59:28 -07001102 std::tie(StSameBuf, StNotSameBuf) = state->assume(SameBuf);
Jordy Rosed325ffb2010-07-08 23:57:29 +00001103
Jordy Rose1e022412011-06-16 05:51:02 +00001104 // If the two arguments might be the same buffer, we know the result is 0,
Jordy Rosed325ffb2010-07-08 23:57:29 +00001105 // and we only need to check one size.
1106 if (StSameBuf) {
1107 state = StSameBuf;
1108 state = CheckBufferAccess(C, state, Size, Left);
1109 if (state) {
Ted Kremenek5eca4822012-01-06 22:09:28 +00001110 state = StSameBuf->BindExpr(CE, LCtx,
1111 svalBuilder.makeZeroVal(CE->getType()));
Anna Zaks0bd6b112011-10-26 21:06:34 +00001112 C.addTransition(state);
Jordy Rosed325ffb2010-07-08 23:57:29 +00001113 }
1114 }
1115
1116 // If the two arguments might be different buffers, we have to check the
1117 // size of both of them.
1118 if (StNotSameBuf) {
1119 state = StNotSameBuf;
1120 state = CheckBufferAccess(C, state, Size, Left, Right);
1121 if (state) {
1122 // The return value is the comparison result, which we don't know.
Ted Kremenek66c486f2012-08-22 06:26:15 +00001123 SVal CmpV = svalBuilder.conjureSymbolVal(0, CE, LCtx, C.blockCount());
Ted Kremenek5eca4822012-01-06 22:09:28 +00001124 state = state->BindExpr(CE, LCtx, CmpV);
Anna Zaks0bd6b112011-10-26 21:06:34 +00001125 C.addTransition(state);
Jordy Rosed325ffb2010-07-08 23:57:29 +00001126 }
1127 }
1128 }
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001129}
1130
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001131void CStringChecker::evalstrLength(CheckerContext &C,
1132 const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001133 if (CE->getNumArgs() < 1)
1134 return;
1135
Jordy Rose19c5dd12010-07-27 01:37:31 +00001136 // size_t strlen(const char *s);
Ted Kremenekbe4242c2011-02-22 04:55:05 +00001137 evalstrLengthCommon(C, CE, /* IsStrnlen = */ false);
1138}
1139
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001140void CStringChecker::evalstrnLength(CheckerContext &C,
1141 const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001142 if (CE->getNumArgs() < 2)
1143 return;
1144
Ted Kremenekbe4242c2011-02-22 04:55:05 +00001145 // size_t strnlen(const char *s, size_t maxlen);
1146 evalstrLengthCommon(C, CE, /* IsStrnlen = */ true);
1147}
1148
1149void CStringChecker::evalstrLengthCommon(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001150 bool IsStrnlen) const {
Jordy Rose9e49d9f2011-06-20 02:06:40 +00001151 CurrentFunctionDescription = "string length function";
Ted Kremenek8bef8232012-01-26 21:29:00 +00001152 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001153 const LocationContext *LCtx = C.getLocationContext();
Jordy Rose793bff32011-06-14 01:15:31 +00001154
1155 if (IsStrnlen) {
1156 const Expr *maxlenExpr = CE->getArg(1);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001157 SVal maxlenVal = state->getSVal(maxlenExpr, LCtx);
Jordy Rose793bff32011-06-14 01:15:31 +00001158
Ted Kremenek8bef8232012-01-26 21:29:00 +00001159 ProgramStateRef stateZeroSize, stateNonZeroSize;
Stephen Hines651f13c2014-04-23 16:59:28 -07001160 std::tie(stateZeroSize, stateNonZeroSize) =
Jordy Rose793bff32011-06-14 01:15:31 +00001161 assumeZero(C, state, maxlenVal, maxlenExpr->getType());
1162
1163 // If the size can be zero, the result will be 0 in that case, and we don't
1164 // have to check the string itself.
1165 if (stateZeroSize) {
1166 SVal zero = C.getSValBuilder().makeZeroVal(CE->getType());
Ted Kremenek5eca4822012-01-06 22:09:28 +00001167 stateZeroSize = stateZeroSize->BindExpr(CE, LCtx, zero);
Anna Zaks0bd6b112011-10-26 21:06:34 +00001168 C.addTransition(stateZeroSize);
Jordy Rose793bff32011-06-14 01:15:31 +00001169 }
1170
1171 // If the size is GUARANTEED to be zero, we're done!
1172 if (!stateNonZeroSize)
1173 return;
1174
1175 // Otherwise, record the assumption that the size is nonzero.
1176 state = stateNonZeroSize;
1177 }
1178
1179 // Check that the string argument is non-null.
Jordy Rose19c5dd12010-07-27 01:37:31 +00001180 const Expr *Arg = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001181 SVal ArgVal = state->getSVal(Arg, LCtx);
Jordy Rose19c5dd12010-07-27 01:37:31 +00001182
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001183 state = checkNonNull(C, state, Arg, ArgVal);
Jordy Rose19c5dd12010-07-27 01:37:31 +00001184
Jordy Rosebd32bee2011-06-14 01:26:48 +00001185 if (!state)
1186 return;
Jordy Rosea5261542010-08-14 21:02:52 +00001187
Jordy Rosebd32bee2011-06-14 01:26:48 +00001188 SVal strLength = getCStringLength(C, state, Arg, ArgVal);
Jordy Rosea5261542010-08-14 21:02:52 +00001189
Jordy Rosebd32bee2011-06-14 01:26:48 +00001190 // If the argument isn't a valid C string, there's no valid state to
1191 // transition to.
1192 if (strLength.isUndef())
1193 return;
Jordy Rose793bff32011-06-14 01:15:31 +00001194
Jordy Rosebd32bee2011-06-14 01:26:48 +00001195 DefinedOrUnknownSVal result = UnknownVal();
Jordy Rose793bff32011-06-14 01:15:31 +00001196
Jordy Rosebd32bee2011-06-14 01:26:48 +00001197 // If the check is for strnlen() then bind the return value to no more than
1198 // the maxlen value.
1199 if (IsStrnlen) {
Jordy Roseee2fde12011-06-16 05:56:50 +00001200 QualType cmpTy = C.getSValBuilder().getConditionType();
Jordy Rose793bff32011-06-14 01:15:31 +00001201
Jordy Rosebd32bee2011-06-14 01:26:48 +00001202 // It's a little unfortunate to be getting this again,
1203 // but it's not that expensive...
1204 const Expr *maxlenExpr = CE->getArg(1);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001205 SVal maxlenVal = state->getSVal(maxlenExpr, LCtx);
Ted Kremenekbe4242c2011-02-22 04:55:05 +00001206
David Blaikiedc84cd52013-02-20 22:23:23 +00001207 Optional<NonLoc> strLengthNL = strLength.getAs<NonLoc>();
1208 Optional<NonLoc> maxlenValNL = maxlenVal.getAs<NonLoc>();
Ted Kremenekbe4242c2011-02-22 04:55:05 +00001209
Jordy Rosebd32bee2011-06-14 01:26:48 +00001210 if (strLengthNL && maxlenValNL) {
Ted Kremenek8bef8232012-01-26 21:29:00 +00001211 ProgramStateRef stateStringTooLong, stateStringNotTooLong;
Jordy Rose793bff32011-06-14 01:15:31 +00001212
Jordy Rosebd32bee2011-06-14 01:26:48 +00001213 // Check if the strLength is greater than the maxlen.
Stephen Hines651f13c2014-04-23 16:59:28 -07001214 std::tie(stateStringTooLong, stateStringNotTooLong) = state->assume(
1215 C.getSValBuilder()
1216 .evalBinOpNN(state, BO_GT, *strLengthNL, *maxlenValNL, cmpTy)
1217 .castAs<DefinedOrUnknownSVal>());
Jordy Rose793bff32011-06-14 01:15:31 +00001218
Jordy Rosebd32bee2011-06-14 01:26:48 +00001219 if (stateStringTooLong && !stateStringNotTooLong) {
1220 // If the string is longer than maxlen, return maxlen.
1221 result = *maxlenValNL;
1222 } else if (stateStringNotTooLong && !stateStringTooLong) {
1223 // If the string is shorter than maxlen, return its length.
1224 result = *strLengthNL;
Ted Kremenekbe4242c2011-02-22 04:55:05 +00001225 }
1226 }
1227
Jordy Rosebd32bee2011-06-14 01:26:48 +00001228 if (result.isUnknown()) {
1229 // If we don't have enough information for a comparison, there's
1230 // no guarantee the full string length will actually be returned.
1231 // All we know is the return value is the min of the string length
1232 // and the limit. This is better than nothing.
Ted Kremenek66c486f2012-08-22 06:26:15 +00001233 result = C.getSValBuilder().conjureSymbolVal(0, CE, LCtx, C.blockCount());
David Blaikie5251abe2013-02-20 05:52:05 +00001234 NonLoc resultNL = result.castAs<NonLoc>();
Jordy Rosebd32bee2011-06-14 01:26:48 +00001235
1236 if (strLengthNL) {
David Blaikie5251abe2013-02-20 05:52:05 +00001237 state = state->assume(C.getSValBuilder().evalBinOpNN(
1238 state, BO_LE, resultNL, *strLengthNL, cmpTy)
1239 .castAs<DefinedOrUnknownSVal>(), true);
Jordy Rosebd32bee2011-06-14 01:26:48 +00001240 }
1241
1242 if (maxlenValNL) {
David Blaikie5251abe2013-02-20 05:52:05 +00001243 state = state->assume(C.getSValBuilder().evalBinOpNN(
1244 state, BO_LE, resultNL, *maxlenValNL, cmpTy)
1245 .castAs<DefinedOrUnknownSVal>(), true);
Jordy Rosebd32bee2011-06-14 01:26:48 +00001246 }
1247 }
1248
1249 } else {
1250 // This is a plain strlen(), not strnlen().
David Blaikie5251abe2013-02-20 05:52:05 +00001251 result = strLength.castAs<DefinedOrUnknownSVal>();
Jordy Rosebd32bee2011-06-14 01:26:48 +00001252
1253 // If we don't know the length of the string, conjure a return
1254 // value, so it can be used in constraints, at least.
1255 if (result.isUnknown()) {
Ted Kremenek66c486f2012-08-22 06:26:15 +00001256 result = C.getSValBuilder().conjureSymbolVal(0, CE, LCtx, C.blockCount());
Jordy Rosebd32bee2011-06-14 01:26:48 +00001257 }
Jordy Rose19c5dd12010-07-27 01:37:31 +00001258 }
Jordy Rosebd32bee2011-06-14 01:26:48 +00001259
1260 // Bind the return value.
1261 assert(!result.isUnknown() && "Should have conjured a value by now");
Ted Kremenek5eca4822012-01-06 22:09:28 +00001262 state = state->BindExpr(CE, LCtx, result);
Anna Zaks0bd6b112011-10-26 21:06:34 +00001263 C.addTransition(state);
Jordy Rose19c5dd12010-07-27 01:37:31 +00001264}
1265
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001266void CStringChecker::evalStrcpy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001267 if (CE->getNumArgs() < 2)
1268 return;
1269
Jordy Rosee64f3112010-08-16 07:51:42 +00001270 // char *strcpy(char *restrict dst, const char *restrict src);
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001271 evalStrcpyCommon(C, CE,
1272 /* returnEnd = */ false,
1273 /* isBounded = */ false,
1274 /* isAppending = */ false);
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001275}
1276
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001277void CStringChecker::evalStrncpy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001278 if (CE->getNumArgs() < 3)
1279 return;
1280
Jordy Rosec1525862011-06-04 00:05:23 +00001281 // char *strncpy(char *restrict dst, const char *restrict src, size_t n);
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001282 evalStrcpyCommon(C, CE,
1283 /* returnEnd = */ false,
1284 /* isBounded = */ true,
1285 /* isAppending = */ false);
Jordy Rosee64f3112010-08-16 07:51:42 +00001286}
1287
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001288void CStringChecker::evalStpcpy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001289 if (CE->getNumArgs() < 2)
1290 return;
1291
Jordy Rosee64f3112010-08-16 07:51:42 +00001292 // char *stpcpy(char *restrict dst, const char *restrict src);
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001293 evalStrcpyCommon(C, CE,
1294 /* returnEnd = */ true,
1295 /* isBounded = */ false,
1296 /* isAppending = */ false);
1297}
1298
1299void CStringChecker::evalStrcat(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001300 if (CE->getNumArgs() < 2)
1301 return;
1302
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001303 //char *strcat(char *restrict s1, const char *restrict s2);
1304 evalStrcpyCommon(C, CE,
1305 /* returnEnd = */ false,
1306 /* isBounded = */ false,
1307 /* isAppending = */ true);
1308}
1309
1310void CStringChecker::evalStrncat(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001311 if (CE->getNumArgs() < 3)
1312 return;
1313
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001314 //char *strncat(char *restrict s1, const char *restrict s2, size_t n);
1315 evalStrcpyCommon(C, CE,
1316 /* returnEnd = */ false,
1317 /* isBounded = */ true,
1318 /* isAppending = */ true);
Jordy Rosee64f3112010-08-16 07:51:42 +00001319}
1320
Ted Kremenek9c149532010-12-01 21:57:22 +00001321void CStringChecker::evalStrcpyCommon(CheckerContext &C, const CallExpr *CE,
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001322 bool returnEnd, bool isBounded,
1323 bool isAppending) const {
Jordy Rose9e49d9f2011-06-20 02:06:40 +00001324 CurrentFunctionDescription = "string copy function";
Ted Kremenek8bef8232012-01-26 21:29:00 +00001325 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001326 const LocationContext *LCtx = C.getLocationContext();
Jordy Rosee64f3112010-08-16 07:51:42 +00001327
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001328 // Check that the destination is non-null.
Jordy Rosee64f3112010-08-16 07:51:42 +00001329 const Expr *Dst = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001330 SVal DstVal = state->getSVal(Dst, LCtx);
Jordy Rosee64f3112010-08-16 07:51:42 +00001331
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001332 state = checkNonNull(C, state, Dst, DstVal);
Jordy Rosee64f3112010-08-16 07:51:42 +00001333 if (!state)
1334 return;
1335
1336 // Check that the source is non-null.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001337 const Expr *srcExpr = CE->getArg(1);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001338 SVal srcVal = state->getSVal(srcExpr, LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001339 state = checkNonNull(C, state, srcExpr, srcVal);
Jordy Rosee64f3112010-08-16 07:51:42 +00001340 if (!state)
1341 return;
1342
1343 // Get the string length of the source.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001344 SVal strLength = getCStringLength(C, state, srcExpr, srcVal);
Jordy Rosee64f3112010-08-16 07:51:42 +00001345
1346 // If the source isn't a valid C string, give up.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001347 if (strLength.isUndef())
Jordy Rosee64f3112010-08-16 07:51:42 +00001348 return;
1349
Jordy Rosed5af0e12011-06-15 05:52:56 +00001350 SValBuilder &svalBuilder = C.getSValBuilder();
1351 QualType cmpTy = svalBuilder.getConditionType();
Jordy Rose8912aae2011-06-20 21:55:40 +00001352 QualType sizeTy = svalBuilder.getContext().getSizeType();
Jordy Rosed5af0e12011-06-15 05:52:56 +00001353
Jordy Rose8912aae2011-06-20 21:55:40 +00001354 // These two values allow checking two kinds of errors:
1355 // - actual overflows caused by a source that doesn't fit in the destination
1356 // - potential overflows caused by a bound that could exceed the destination
Jordy Rosed5af0e12011-06-15 05:52:56 +00001357 SVal amountCopied = UnknownVal();
Jordy Rose8912aae2011-06-20 21:55:40 +00001358 SVal maxLastElementIndex = UnknownVal();
1359 const char *boundWarning = NULL;
Jordy Rosed5af0e12011-06-15 05:52:56 +00001360
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001361 // If the function is strncpy, strncat, etc... it is bounded.
1362 if (isBounded) {
1363 // Get the max number of characters to copy.
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001364 const Expr *lenExpr = CE->getArg(2);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001365 SVal lenVal = state->getSVal(lenExpr, LCtx);
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001366
Jordy Rosed5af0e12011-06-15 05:52:56 +00001367 // Protect against misdeclared strncpy().
Jordy Rose8912aae2011-06-20 21:55:40 +00001368 lenVal = svalBuilder.evalCast(lenVal, sizeTy, lenExpr->getType());
Jordy Rosed5af0e12011-06-15 05:52:56 +00001369
David Blaikiedc84cd52013-02-20 22:23:23 +00001370 Optional<NonLoc> strLengthNL = strLength.getAs<NonLoc>();
1371 Optional<NonLoc> lenValNL = lenVal.getAs<NonLoc>();
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001372
Jordy Rosed5af0e12011-06-15 05:52:56 +00001373 // If we know both values, we might be able to figure out how much
1374 // we're copying.
1375 if (strLengthNL && lenValNL) {
Ted Kremenek8bef8232012-01-26 21:29:00 +00001376 ProgramStateRef stateSourceTooLong, stateSourceNotTooLong;
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001377
Jordy Rosed5af0e12011-06-15 05:52:56 +00001378 // Check if the max number to copy is less than the length of the src.
Jordy Rose8912aae2011-06-20 21:55:40 +00001379 // If the bound is equal to the source length, strncpy won't null-
1380 // terminate the result!
Stephen Hines651f13c2014-04-23 16:59:28 -07001381 std::tie(stateSourceTooLong, stateSourceNotTooLong) = state->assume(
David Blaikie5251abe2013-02-20 05:52:05 +00001382 svalBuilder.evalBinOpNN(state, BO_GE, *strLengthNL, *lenValNL, cmpTy)
1383 .castAs<DefinedOrUnknownSVal>());
Jordy Rosed5af0e12011-06-15 05:52:56 +00001384
1385 if (stateSourceTooLong && !stateSourceNotTooLong) {
1386 // Max number to copy is less than the length of the src, so the actual
1387 // strLength copied is the max number arg.
1388 state = stateSourceTooLong;
1389 amountCopied = lenVal;
1390
1391 } else if (!stateSourceTooLong && stateSourceNotTooLong) {
1392 // The source buffer entirely fits in the bound.
1393 state = stateSourceNotTooLong;
1394 amountCopied = strLength;
1395 }
1396 }
1397
Jordy Rose5e5f1502011-06-20 03:49:16 +00001398 // We still want to know if the bound is known to be too large.
Jordy Rose8912aae2011-06-20 21:55:40 +00001399 if (lenValNL) {
1400 if (isAppending) {
1401 // For strncat, the check is strlen(dst) + lenVal < sizeof(dst)
1402
1403 // Get the string length of the destination. If the destination is
1404 // memory that can't have a string length, we shouldn't be copying
1405 // into it anyway.
1406 SVal dstStrLength = getCStringLength(C, state, Dst, DstVal);
1407 if (dstStrLength.isUndef())
1408 return;
1409
David Blaikiedc84cd52013-02-20 22:23:23 +00001410 if (Optional<NonLoc> dstStrLengthNL = dstStrLength.getAs<NonLoc>()) {
Jordy Rose8912aae2011-06-20 21:55:40 +00001411 maxLastElementIndex = svalBuilder.evalBinOpNN(state, BO_Add,
1412 *lenValNL,
1413 *dstStrLengthNL,
1414 sizeTy);
1415 boundWarning = "Size argument is greater than the free space in the "
1416 "destination buffer";
1417 }
1418
1419 } else {
1420 // For strncpy, this is just checking that lenVal <= sizeof(dst)
1421 // (Yes, strncpy and strncat differ in how they treat termination.
1422 // strncat ALWAYS terminates, but strncpy doesn't.)
Jordy Rose6e4244e2012-05-14 17:58:35 +00001423
1424 // We need a special case for when the copy size is zero, in which
1425 // case strncpy will do no work at all. Our bounds check uses n-1
1426 // as the last element accessed, so n == 0 is problematic.
1427 ProgramStateRef StateZeroSize, StateNonZeroSize;
Stephen Hines651f13c2014-04-23 16:59:28 -07001428 std::tie(StateZeroSize, StateNonZeroSize) =
Jordy Rose6e4244e2012-05-14 17:58:35 +00001429 assumeZero(C, state, *lenValNL, sizeTy);
1430
1431 // If the size is known to be zero, we're done.
1432 if (StateZeroSize && !StateNonZeroSize) {
1433 StateZeroSize = StateZeroSize->BindExpr(CE, LCtx, DstVal);
1434 C.addTransition(StateZeroSize);
1435 return;
1436 }
1437
1438 // Otherwise, go ahead and figure out the last element we'll touch.
1439 // We don't record the non-zero assumption here because we can't
1440 // be sure. We won't warn on a possible zero.
David Blaikie5251abe2013-02-20 05:52:05 +00001441 NonLoc one = svalBuilder.makeIntVal(1, sizeTy).castAs<NonLoc>();
Jordy Rose8912aae2011-06-20 21:55:40 +00001442 maxLastElementIndex = svalBuilder.evalBinOpNN(state, BO_Sub, *lenValNL,
1443 one, sizeTy);
1444 boundWarning = "Size argument is greater than the length of the "
1445 "destination buffer";
1446 }
1447 }
Jordy Rose5e5f1502011-06-20 03:49:16 +00001448
Jordy Rosed5af0e12011-06-15 05:52:56 +00001449 // If we couldn't pin down the copy length, at least bound it.
Jordy Rose8912aae2011-06-20 21:55:40 +00001450 // FIXME: We should actually run this code path for append as well, but
1451 // right now it creates problems with constraints (since we can end up
1452 // trying to pass constraints from symbol to symbol).
1453 if (amountCopied.isUnknown() && !isAppending) {
Jordy Rosed5af0e12011-06-15 05:52:56 +00001454 // Try to get a "hypothetical" string length symbol, which we can later
1455 // set as a real value if that turns out to be the case.
1456 amountCopied = getCStringLength(C, state, lenExpr, srcVal, true);
1457 assert(!amountCopied.isUndef());
1458
David Blaikiedc84cd52013-02-20 22:23:23 +00001459 if (Optional<NonLoc> amountCopiedNL = amountCopied.getAs<NonLoc>()) {
Jordy Rosed5af0e12011-06-15 05:52:56 +00001460 if (lenValNL) {
1461 // amountCopied <= lenVal
1462 SVal copiedLessThanBound = svalBuilder.evalBinOpNN(state, BO_LE,
1463 *amountCopiedNL,
1464 *lenValNL,
1465 cmpTy);
David Blaikie5251abe2013-02-20 05:52:05 +00001466 state = state->assume(
1467 copiedLessThanBound.castAs<DefinedOrUnknownSVal>(), true);
Jordy Rosed5af0e12011-06-15 05:52:56 +00001468 if (!state)
1469 return;
1470 }
1471
1472 if (strLengthNL) {
1473 // amountCopied <= strlen(source)
1474 SVal copiedLessThanSrc = svalBuilder.evalBinOpNN(state, BO_LE,
1475 *amountCopiedNL,
1476 *strLengthNL,
1477 cmpTy);
David Blaikie5251abe2013-02-20 05:52:05 +00001478 state = state->assume(
1479 copiedLessThanSrc.castAs<DefinedOrUnknownSVal>(), true);
Jordy Rosed5af0e12011-06-15 05:52:56 +00001480 if (!state)
1481 return;
1482 }
1483 }
1484 }
1485
1486 } else {
1487 // The function isn't bounded. The amount copied should match the length
1488 // of the source buffer.
1489 amountCopied = strLength;
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001490 }
1491
Jordy Rosed5af0e12011-06-15 05:52:56 +00001492 assert(state);
1493
1494 // This represents the number of characters copied into the destination
1495 // buffer. (It may not actually be the strlen if the destination buffer
1496 // is not terminated.)
1497 SVal finalStrLength = UnknownVal();
1498
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001499 // If this is an appending function (strcat, strncat...) then set the
1500 // string length to strlen(src) + strlen(dst) since the buffer will
1501 // ultimately contain both.
1502 if (isAppending) {
Jordy Rose1e022412011-06-16 05:51:02 +00001503 // Get the string length of the destination. If the destination is memory
1504 // that can't have a string length, we shouldn't be copying into it anyway.
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001505 SVal dstStrLength = getCStringLength(C, state, Dst, DstVal);
1506 if (dstStrLength.isUndef())
1507 return;
1508
David Blaikiedc84cd52013-02-20 22:23:23 +00001509 Optional<NonLoc> srcStrLengthNL = amountCopied.getAs<NonLoc>();
1510 Optional<NonLoc> dstStrLengthNL = dstStrLength.getAs<NonLoc>();
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001511
Jordy Rosed5af0e12011-06-15 05:52:56 +00001512 // If we know both string lengths, we might know the final string length.
1513 if (srcStrLengthNL && dstStrLengthNL) {
1514 // Make sure the two lengths together don't overflow a size_t.
1515 state = checkAdditionOverflow(C, state, *srcStrLengthNL, *dstStrLengthNL);
1516 if (!state)
1517 return;
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001518
Jordy Rosed5af0e12011-06-15 05:52:56 +00001519 finalStrLength = svalBuilder.evalBinOpNN(state, BO_Add, *srcStrLengthNL,
1520 *dstStrLengthNL, sizeTy);
1521 }
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001522
Jordy Rosed5af0e12011-06-15 05:52:56 +00001523 // If we couldn't get a single value for the final string length,
1524 // we can at least bound it by the individual lengths.
1525 if (finalStrLength.isUnknown()) {
1526 // Try to get a "hypothetical" string length symbol, which we can later
1527 // set as a real value if that turns out to be the case.
1528 finalStrLength = getCStringLength(C, state, CE, DstVal, true);
1529 assert(!finalStrLength.isUndef());
1530
David Blaikiedc84cd52013-02-20 22:23:23 +00001531 if (Optional<NonLoc> finalStrLengthNL = finalStrLength.getAs<NonLoc>()) {
Jordy Rosed5af0e12011-06-15 05:52:56 +00001532 if (srcStrLengthNL) {
1533 // finalStrLength >= srcStrLength
1534 SVal sourceInResult = svalBuilder.evalBinOpNN(state, BO_GE,
1535 *finalStrLengthNL,
1536 *srcStrLengthNL,
1537 cmpTy);
David Blaikie5251abe2013-02-20 05:52:05 +00001538 state = state->assume(sourceInResult.castAs<DefinedOrUnknownSVal>(),
Jordy Rosed5af0e12011-06-15 05:52:56 +00001539 true);
1540 if (!state)
1541 return;
1542 }
1543
1544 if (dstStrLengthNL) {
1545 // finalStrLength >= dstStrLength
1546 SVal destInResult = svalBuilder.evalBinOpNN(state, BO_GE,
1547 *finalStrLengthNL,
1548 *dstStrLengthNL,
1549 cmpTy);
David Blaikie5251abe2013-02-20 05:52:05 +00001550 state =
1551 state->assume(destInResult.castAs<DefinedOrUnknownSVal>(), true);
Jordy Rosed5af0e12011-06-15 05:52:56 +00001552 if (!state)
1553 return;
1554 }
1555 }
1556 }
1557
1558 } else {
1559 // Otherwise, this is a copy-over function (strcpy, strncpy, ...), and
1560 // the final string length will match the input string length.
1561 finalStrLength = amountCopied;
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001562 }
1563
Jordy Rosed5af0e12011-06-15 05:52:56 +00001564 // The final result of the function will either be a pointer past the last
1565 // copied element, or a pointer to the start of the destination buffer.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001566 SVal Result = (returnEnd ? UnknownVal() : DstVal);
Jordy Rosee64f3112010-08-16 07:51:42 +00001567
Jordy Rosed5af0e12011-06-15 05:52:56 +00001568 assert(state);
1569
Jordy Rosee64f3112010-08-16 07:51:42 +00001570 // If the destination is a MemRegion, try to check for a buffer overflow and
1571 // record the new string length.
David Blaikiedc84cd52013-02-20 22:23:23 +00001572 if (Optional<loc::MemRegionVal> dstRegVal =
David Blaikie5251abe2013-02-20 05:52:05 +00001573 DstVal.getAs<loc::MemRegionVal>()) {
Jordy Rose8912aae2011-06-20 21:55:40 +00001574 QualType ptrTy = Dst->getType();
1575
1576 // If we have an exact value on a bounded copy, use that to check for
1577 // overflows, rather than our estimate about how much is actually copied.
1578 if (boundWarning) {
David Blaikiedc84cd52013-02-20 22:23:23 +00001579 if (Optional<NonLoc> maxLastNL = maxLastElementIndex.getAs<NonLoc>()) {
Jordy Rose8912aae2011-06-20 21:55:40 +00001580 SVal maxLastElement = svalBuilder.evalBinOpLN(state, BO_Add, *dstRegVal,
1581 *maxLastNL, ptrTy);
1582 state = CheckLocation(C, state, CE->getArg(2), maxLastElement,
1583 boundWarning);
1584 if (!state)
1585 return;
1586 }
1587 }
1588
1589 // Then, if the final length is known...
David Blaikiedc84cd52013-02-20 22:23:23 +00001590 if (Optional<NonLoc> knownStrLength = finalStrLength.getAs<NonLoc>()) {
Jordy Rosed5af0e12011-06-15 05:52:56 +00001591 SVal lastElement = svalBuilder.evalBinOpLN(state, BO_Add, *dstRegVal,
Jordy Rose8912aae2011-06-20 21:55:40 +00001592 *knownStrLength, ptrTy);
Jordy Rosee64f3112010-08-16 07:51:42 +00001593
Jordy Rose8912aae2011-06-20 21:55:40 +00001594 // ...and we haven't checked the bound, we'll check the actual copy.
1595 if (!boundWarning) {
1596 const char * const warningMsg =
1597 "String copy function overflows destination buffer";
1598 state = CheckLocation(C, state, Dst, lastElement, warningMsg);
1599 if (!state)
1600 return;
1601 }
Jordy Rosee64f3112010-08-16 07:51:42 +00001602
1603 // If this is a stpcpy-style copy, the last element is the return value.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001604 if (returnEnd)
1605 Result = lastElement;
Jordy Rosee64f3112010-08-16 07:51:42 +00001606 }
1607
Anton Yartsevb7a747b2013-11-17 09:18:48 +00001608 // Invalidate the destination (regular invalidation without pointer-escaping
1609 // the address of the top-level region). This must happen before we set the
1610 // C string length because invalidation will clear the length.
Jordy Rosee64f3112010-08-16 07:51:42 +00001611 // FIXME: Even if we can't perfectly model the copy, we should see if we
1612 // can use LazyCompoundVals to copy the source values into the destination.
1613 // This would probably remove any existing bindings past the end of the
1614 // string, but that's still an improvement over blank invalidation.
Anton Yartsevb7a747b2013-11-17 09:18:48 +00001615 state = InvalidateBuffer(C, state, Dst, *dstRegVal,
1616 /*IsSourceBuffer*/false);
1617
1618 // Invalidate the source (const-invalidation without const-pointer-escaping
1619 // the address of the top-level region).
1620 state = InvalidateBuffer(C, state, srcExpr, srcVal, /*IsSourceBuffer*/true);
Jordy Rosee64f3112010-08-16 07:51:42 +00001621
Jordy Rose5e5f1502011-06-20 03:49:16 +00001622 // Set the C string length of the destination, if we know it.
Jordy Rose8912aae2011-06-20 21:55:40 +00001623 if (isBounded && !isAppending) {
1624 // strncpy is annoying in that it doesn't guarantee to null-terminate
1625 // the result string. If the original string didn't fit entirely inside
1626 // the bound (including the null-terminator), we don't know how long the
1627 // result is.
1628 if (amountCopied != strLength)
1629 finalStrLength = UnknownVal();
1630 }
1631 state = setCStringLength(state, dstRegVal->getRegion(), finalStrLength);
Jordy Rosee64f3112010-08-16 07:51:42 +00001632 }
1633
Jordy Rosed5af0e12011-06-15 05:52:56 +00001634 assert(state);
1635
Jordy Rosee64f3112010-08-16 07:51:42 +00001636 // If this is a stpcpy-style copy, but we were unable to check for a buffer
1637 // overflow, we still need a result. Conjure a return value.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001638 if (returnEnd && Result.isUnknown()) {
Ted Kremenek66c486f2012-08-22 06:26:15 +00001639 Result = svalBuilder.conjureSymbolVal(0, CE, LCtx, C.blockCount());
Jordy Rosee64f3112010-08-16 07:51:42 +00001640 }
1641
1642 // Set the return value.
Ted Kremenek5eca4822012-01-06 22:09:28 +00001643 state = state->BindExpr(CE, LCtx, Result);
Anna Zaks0bd6b112011-10-26 21:06:34 +00001644 C.addTransition(state);
Jordy Rosee64f3112010-08-16 07:51:42 +00001645}
1646
Lenny Maiorani318dd922011-04-12 17:08:43 +00001647void CStringChecker::evalStrcmp(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001648 if (CE->getNumArgs() < 2)
1649 return;
1650
Jordy Roseadc42d42011-06-16 07:13:34 +00001651 //int strcmp(const char *s1, const char *s2);
Lenny Maioranibd1d16a2011-04-28 15:09:11 +00001652 evalStrcmpCommon(C, CE, /* isBounded = */ false, /* ignoreCase = */ false);
Lenny Maiorani357f6ee2011-04-25 22:21:00 +00001653}
Lenny Maiorani318dd922011-04-12 17:08:43 +00001654
Lenny Maiorani357f6ee2011-04-25 22:21:00 +00001655void CStringChecker::evalStrncmp(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001656 if (CE->getNumArgs() < 3)
1657 return;
1658
Jordy Roseadc42d42011-06-16 07:13:34 +00001659 //int strncmp(const char *s1, const char *s2, size_t n);
Lenny Maioranibd1d16a2011-04-28 15:09:11 +00001660 evalStrcmpCommon(C, CE, /* isBounded = */ true, /* ignoreCase = */ false);
1661}
1662
1663void CStringChecker::evalStrcasecmp(CheckerContext &C,
1664 const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001665 if (CE->getNumArgs() < 2)
1666 return;
1667
Jordy Roseadc42d42011-06-16 07:13:34 +00001668 //int strcasecmp(const char *s1, const char *s2);
Lenny Maioranibd1d16a2011-04-28 15:09:11 +00001669 evalStrcmpCommon(C, CE, /* isBounded = */ false, /* ignoreCase = */ true);
Lenny Maiorani357f6ee2011-04-25 22:21:00 +00001670}
1671
Lenny Maiorani454fd2d2011-05-02 19:05:49 +00001672void CStringChecker::evalStrncasecmp(CheckerContext &C,
1673 const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001674 if (CE->getNumArgs() < 3)
1675 return;
1676
Jordy Roseadc42d42011-06-16 07:13:34 +00001677 //int strncasecmp(const char *s1, const char *s2, size_t n);
Lenny Maiorani454fd2d2011-05-02 19:05:49 +00001678 evalStrcmpCommon(C, CE, /* isBounded = */ true, /* ignoreCase = */ true);
1679}
1680
Lenny Maiorani357f6ee2011-04-25 22:21:00 +00001681void CStringChecker::evalStrcmpCommon(CheckerContext &C, const CallExpr *CE,
Lenny Maioranibd1d16a2011-04-28 15:09:11 +00001682 bool isBounded, bool ignoreCase) const {
Jordy Rose9e49d9f2011-06-20 02:06:40 +00001683 CurrentFunctionDescription = "string comparison function";
Ted Kremenek8bef8232012-01-26 21:29:00 +00001684 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001685 const LocationContext *LCtx = C.getLocationContext();
Lenny Maiorani318dd922011-04-12 17:08:43 +00001686
1687 // Check that the first string is non-null
1688 const Expr *s1 = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001689 SVal s1Val = state->getSVal(s1, LCtx);
Lenny Maiorani318dd922011-04-12 17:08:43 +00001690 state = checkNonNull(C, state, s1, s1Val);
1691 if (!state)
1692 return;
1693
1694 // Check that the second string is non-null.
1695 const Expr *s2 = CE->getArg(1);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001696 SVal s2Val = state->getSVal(s2, LCtx);
Lenny Maiorani318dd922011-04-12 17:08:43 +00001697 state = checkNonNull(C, state, s2, s2Val);
1698 if (!state)
1699 return;
1700
1701 // Get the string length of the first string or give up.
1702 SVal s1Length = getCStringLength(C, state, s1, s1Val);
1703 if (s1Length.isUndef())
1704 return;
1705
1706 // Get the string length of the second string or give up.
1707 SVal s2Length = getCStringLength(C, state, s2, s2Val);
1708 if (s2Length.isUndef())
1709 return;
1710
Jordy Roseadc42d42011-06-16 07:13:34 +00001711 // If we know the two buffers are the same, we know the result is 0.
1712 // First, get the two buffers' addresses. Another checker will have already
1713 // made sure they're not undefined.
David Blaikie5251abe2013-02-20 05:52:05 +00001714 DefinedOrUnknownSVal LV = s1Val.castAs<DefinedOrUnknownSVal>();
1715 DefinedOrUnknownSVal RV = s2Val.castAs<DefinedOrUnknownSVal>();
Lenny Maiorani318dd922011-04-12 17:08:43 +00001716
Jordy Roseadc42d42011-06-16 07:13:34 +00001717 // See if they are the same.
Lenny Maiorani318dd922011-04-12 17:08:43 +00001718 SValBuilder &svalBuilder = C.getSValBuilder();
Jordy Roseadc42d42011-06-16 07:13:34 +00001719 DefinedOrUnknownSVal SameBuf = svalBuilder.evalEQ(state, LV, RV);
Ted Kremenek8bef8232012-01-26 21:29:00 +00001720 ProgramStateRef StSameBuf, StNotSameBuf;
Stephen Hines651f13c2014-04-23 16:59:28 -07001721 std::tie(StSameBuf, StNotSameBuf) = state->assume(SameBuf);
Lenny Maiorani318dd922011-04-12 17:08:43 +00001722
Jordy Roseadc42d42011-06-16 07:13:34 +00001723 // If the two arguments might be the same buffer, we know the result is 0,
1724 // and we only need to check one size.
1725 if (StSameBuf) {
Ted Kremenek5eca4822012-01-06 22:09:28 +00001726 StSameBuf = StSameBuf->BindExpr(CE, LCtx,
1727 svalBuilder.makeZeroVal(CE->getType()));
Anna Zaks0bd6b112011-10-26 21:06:34 +00001728 C.addTransition(StSameBuf);
Jordy Roseadc42d42011-06-16 07:13:34 +00001729
1730 // If the two arguments are GUARANTEED to be the same, we're done!
1731 if (!StNotSameBuf)
1732 return;
1733 }
1734
1735 assert(StNotSameBuf);
1736 state = StNotSameBuf;
1737
1738 // At this point we can go about comparing the two buffers.
1739 // For now, we only do this if they're both known string literals.
1740
1741 // Attempt to extract string literals from both expressions.
1742 const StringLiteral *s1StrLiteral = getCStringLiteral(C, state, s1, s1Val);
1743 const StringLiteral *s2StrLiteral = getCStringLiteral(C, state, s2, s2Val);
1744 bool canComputeResult = false;
1745
1746 if (s1StrLiteral && s2StrLiteral) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001747 StringRef s1StrRef = s1StrLiteral->getString();
1748 StringRef s2StrRef = s2StrLiteral->getString();
Jordy Roseadc42d42011-06-16 07:13:34 +00001749
1750 if (isBounded) {
1751 // Get the max number of characters to compare.
1752 const Expr *lenExpr = CE->getArg(2);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001753 SVal lenVal = state->getSVal(lenExpr, LCtx);
Jordy Roseadc42d42011-06-16 07:13:34 +00001754
1755 // If the length is known, we can get the right substrings.
1756 if (const llvm::APSInt *len = svalBuilder.getKnownValue(state, lenVal)) {
1757 // Create substrings of each to compare the prefix.
1758 s1StrRef = s1StrRef.substr(0, (size_t)len->getZExtValue());
1759 s2StrRef = s2StrRef.substr(0, (size_t)len->getZExtValue());
1760 canComputeResult = true;
1761 }
1762 } else {
1763 // This is a normal, unbounded strcmp.
1764 canComputeResult = true;
1765 }
1766
1767 if (canComputeResult) {
1768 // Real strcmp stops at null characters.
1769 size_t s1Term = s1StrRef.find('\0');
Chris Lattner5f9e2722011-07-23 10:55:15 +00001770 if (s1Term != StringRef::npos)
Jordy Roseadc42d42011-06-16 07:13:34 +00001771 s1StrRef = s1StrRef.substr(0, s1Term);
1772
1773 size_t s2Term = s2StrRef.find('\0');
Chris Lattner5f9e2722011-07-23 10:55:15 +00001774 if (s2Term != StringRef::npos)
Jordy Roseadc42d42011-06-16 07:13:34 +00001775 s2StrRef = s2StrRef.substr(0, s2Term);
1776
1777 // Use StringRef's comparison methods to compute the actual result.
1778 int result;
1779
1780 if (ignoreCase) {
1781 // Compare string 1 to string 2 the same way strcasecmp() does.
1782 result = s1StrRef.compare_lower(s2StrRef);
1783 } else {
1784 // Compare string 1 to string 2 the same way strcmp() does.
1785 result = s1StrRef.compare(s2StrRef);
1786 }
1787
1788 // Build the SVal of the comparison and bind the return value.
1789 SVal resultVal = svalBuilder.makeIntVal(result, CE->getType());
Ted Kremenek5eca4822012-01-06 22:09:28 +00001790 state = state->BindExpr(CE, LCtx, resultVal);
Jordy Roseadc42d42011-06-16 07:13:34 +00001791 }
1792 }
1793
1794 if (!canComputeResult) {
1795 // Conjure a symbolic value. It's the best we can do.
Ted Kremenek66c486f2012-08-22 06:26:15 +00001796 SVal resultVal = svalBuilder.conjureSymbolVal(0, CE, LCtx, C.blockCount());
Ted Kremenek5eca4822012-01-06 22:09:28 +00001797 state = state->BindExpr(CE, LCtx, resultVal);
Jordy Roseadc42d42011-06-16 07:13:34 +00001798 }
1799
1800 // Record this as a possible path.
Anna Zaks0bd6b112011-10-26 21:06:34 +00001801 C.addTransition(state);
Lenny Maiorani318dd922011-04-12 17:08:43 +00001802}
1803
Jordan Roseaf226212013-04-22 23:18:42 +00001804void CStringChecker::evalStrsep(CheckerContext &C, const CallExpr *CE) const {
1805 //char *strsep(char **stringp, const char *delim);
1806 if (CE->getNumArgs() < 2)
1807 return;
1808
1809 // Sanity: does the search string parameter match the return type?
1810 const Expr *SearchStrPtr = CE->getArg(0);
1811 QualType CharPtrTy = SearchStrPtr->getType()->getPointeeType();
1812 if (CharPtrTy.isNull() ||
1813 CE->getType().getUnqualifiedType() != CharPtrTy.getUnqualifiedType())
1814 return;
1815
1816 CurrentFunctionDescription = "strsep()";
1817 ProgramStateRef State = C.getState();
1818 const LocationContext *LCtx = C.getLocationContext();
1819
1820 // Check that the search string pointer is non-null (though it may point to
1821 // a null string).
1822 SVal SearchStrVal = State->getSVal(SearchStrPtr, LCtx);
1823 State = checkNonNull(C, State, SearchStrPtr, SearchStrVal);
1824 if (!State)
1825 return;
1826
1827 // Check that the delimiter string is non-null.
1828 const Expr *DelimStr = CE->getArg(1);
1829 SVal DelimStrVal = State->getSVal(DelimStr, LCtx);
1830 State = checkNonNull(C, State, DelimStr, DelimStrVal);
1831 if (!State)
1832 return;
1833
1834 SValBuilder &SVB = C.getSValBuilder();
1835 SVal Result;
1836 if (Optional<Loc> SearchStrLoc = SearchStrVal.getAs<Loc>()) {
1837 // Get the current value of the search string pointer, as a char*.
1838 Result = State->getSVal(*SearchStrLoc, CharPtrTy);
1839
1840 // Invalidate the search string, representing the change of one delimiter
1841 // character to NUL.
Anton Yartsevb7a747b2013-11-17 09:18:48 +00001842 State = InvalidateBuffer(C, State, SearchStrPtr, Result,
1843 /*IsSourceBuffer*/false);
Jordan Roseaf226212013-04-22 23:18:42 +00001844
1845 // Overwrite the search string pointer. The new value is either an address
1846 // further along in the same string, or NULL if there are no more tokens.
1847 State = State->bindLoc(*SearchStrLoc,
1848 SVB.conjureSymbolVal(getTag(), CE, LCtx, CharPtrTy,
1849 C.blockCount()));
1850 } else {
1851 assert(SearchStrVal.isUnknown());
1852 // Conjure a symbolic value. It's the best we can do.
1853 Result = SVB.conjureSymbolVal(0, CE, LCtx, C.blockCount());
1854 }
1855
1856 // Set the return value, and finish.
1857 State = State->BindExpr(CE, LCtx, Result);
1858 C.addTransition(State);
1859}
1860
1861
Jordy Rosed325ffb2010-07-08 23:57:29 +00001862//===----------------------------------------------------------------------===//
Jordy Rosea5261542010-08-14 21:02:52 +00001863// The driver method, and other Checker callbacks.
Jordy Rosed325ffb2010-07-08 23:57:29 +00001864//===----------------------------------------------------------------------===//
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001865
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001866bool CStringChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
Anna Zaks998e2752012-02-17 22:35:26 +00001867 const FunctionDecl *FDecl = C.getCalleeDecl(CE);
1868
1869 if (!FDecl)
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001870 return false;
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001871
Jordan Roseaf226212013-04-22 23:18:42 +00001872 // FIXME: Poorly-factored string switches are slow.
Anna Zaks998e2752012-02-17 22:35:26 +00001873 FnCheck evalFunction = 0;
1874 if (C.isCLibraryFunction(FDecl, "memcpy"))
1875 evalFunction = &CStringChecker::evalMemcpy;
1876 else if (C.isCLibraryFunction(FDecl, "mempcpy"))
1877 evalFunction = &CStringChecker::evalMempcpy;
1878 else if (C.isCLibraryFunction(FDecl, "memcmp"))
1879 evalFunction = &CStringChecker::evalMemcmp;
1880 else if (C.isCLibraryFunction(FDecl, "memmove"))
1881 evalFunction = &CStringChecker::evalMemmove;
1882 else if (C.isCLibraryFunction(FDecl, "strcpy"))
1883 evalFunction = &CStringChecker::evalStrcpy;
1884 else if (C.isCLibraryFunction(FDecl, "strncpy"))
1885 evalFunction = &CStringChecker::evalStrncpy;
1886 else if (C.isCLibraryFunction(FDecl, "stpcpy"))
1887 evalFunction = &CStringChecker::evalStpcpy;
1888 else if (C.isCLibraryFunction(FDecl, "strcat"))
1889 evalFunction = &CStringChecker::evalStrcat;
1890 else if (C.isCLibraryFunction(FDecl, "strncat"))
1891 evalFunction = &CStringChecker::evalStrncat;
1892 else if (C.isCLibraryFunction(FDecl, "strlen"))
1893 evalFunction = &CStringChecker::evalstrLength;
1894 else if (C.isCLibraryFunction(FDecl, "strnlen"))
1895 evalFunction = &CStringChecker::evalstrnLength;
1896 else if (C.isCLibraryFunction(FDecl, "strcmp"))
1897 evalFunction = &CStringChecker::evalStrcmp;
1898 else if (C.isCLibraryFunction(FDecl, "strncmp"))
1899 evalFunction = &CStringChecker::evalStrncmp;
1900 else if (C.isCLibraryFunction(FDecl, "strcasecmp"))
1901 evalFunction = &CStringChecker::evalStrcasecmp;
1902 else if (C.isCLibraryFunction(FDecl, "strncasecmp"))
1903 evalFunction = &CStringChecker::evalStrncasecmp;
Jordan Roseaf226212013-04-22 23:18:42 +00001904 else if (C.isCLibraryFunction(FDecl, "strsep"))
1905 evalFunction = &CStringChecker::evalStrsep;
Anna Zaks998e2752012-02-17 22:35:26 +00001906 else if (C.isCLibraryFunction(FDecl, "bcopy"))
1907 evalFunction = &CStringChecker::evalBcopy;
1908 else if (C.isCLibraryFunction(FDecl, "bcmp"))
1909 evalFunction = &CStringChecker::evalMemcmp;
1910
Jordy Rosed325ffb2010-07-08 23:57:29 +00001911 // If the callee isn't a string function, let another checker handle it.
Ted Kremenek9c149532010-12-01 21:57:22 +00001912 if (!evalFunction)
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001913 return false;
1914
Jordy Rose9e49d9f2011-06-20 02:06:40 +00001915 // Make sure each function sets its own description.
1916 // (But don't bother in a release build.)
1917 assert(!(CurrentFunctionDescription = NULL));
1918
Jordy Rosed325ffb2010-07-08 23:57:29 +00001919 // Check and evaluate the call.
Ted Kremenek9c149532010-12-01 21:57:22 +00001920 (this->*evalFunction)(C, CE);
Anna Zaks57300762012-02-07 00:56:14 +00001921
1922 // If the evaluate call resulted in no change, chain to the next eval call
1923 // handler.
1924 // Note, the custom CString evaluation calls assume that basic safety
1925 // properties are held. However, if the user chooses to turn off some of these
1926 // checks, we ignore the issues and leave the call evaluation to a generic
1927 // handler.
1928 if (!C.isDifferent())
1929 return false;
1930
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001931 return true;
1932}
Jordy Rosea5261542010-08-14 21:02:52 +00001933
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001934void CStringChecker::checkPreStmt(const DeclStmt *DS, CheckerContext &C) const {
Jordy Rosea5261542010-08-14 21:02:52 +00001935 // Record string length for char a[] = "abc";
Ted Kremenek8bef8232012-01-26 21:29:00 +00001936 ProgramStateRef state = C.getState();
Jordy Rosea5261542010-08-14 21:02:52 +00001937
Stephen Hines651f13c2014-04-23 16:59:28 -07001938 for (const auto *I : DS->decls()) {
1939 const VarDecl *D = dyn_cast<VarDecl>(I);
Jordy Rosea5261542010-08-14 21:02:52 +00001940 if (!D)
1941 continue;
1942
1943 // FIXME: Handle array fields of structs.
1944 if (!D->getType()->isArrayType())
1945 continue;
1946
1947 const Expr *Init = D->getInit();
1948 if (!Init)
1949 continue;
1950 if (!isa<StringLiteral>(Init))
1951 continue;
1952
Anna Zaks39ac1872011-10-26 21:06:44 +00001953 Loc VarLoc = state->getLValue(D, C.getLocationContext());
Jordy Rosea5261542010-08-14 21:02:52 +00001954 const MemRegion *MR = VarLoc.getAsRegion();
1955 if (!MR)
1956 continue;
1957
Ted Kremenek5eca4822012-01-06 22:09:28 +00001958 SVal StrVal = state->getSVal(Init, C.getLocationContext());
Jordy Rosea5261542010-08-14 21:02:52 +00001959 assert(StrVal.isValid() && "Initializer string is unknown or undefined");
David Blaikie5251abe2013-02-20 05:52:05 +00001960 DefinedOrUnknownSVal strLength =
1961 getCStringLength(C, state, Init, StrVal).castAs<DefinedOrUnknownSVal>();
Jordy Rosea5261542010-08-14 21:02:52 +00001962
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001963 state = state->set<CStringLength>(MR, strLength);
Jordy Rosea5261542010-08-14 21:02:52 +00001964 }
1965
Anna Zaks0bd6b112011-10-26 21:06:34 +00001966 C.addTransition(state);
Jordy Rosea5261542010-08-14 21:02:52 +00001967}
1968
Ted Kremenek8bef8232012-01-26 21:29:00 +00001969bool CStringChecker::wantsRegionChangeUpdate(ProgramStateRef state) const {
Jordan Rose166d5022012-11-02 01:54:06 +00001970 CStringLengthTy Entries = state->get<CStringLength>();
Jordy Rosea5261542010-08-14 21:02:52 +00001971 return !Entries.isEmpty();
1972}
1973
Ted Kremenek8bef8232012-01-26 21:29:00 +00001974ProgramStateRef
1975CStringChecker::checkRegionChanges(ProgramStateRef state,
Anna Zaksbf53dfa2012-12-20 00:38:25 +00001976 const InvalidatedSymbols *,
Jordy Rose537716a2011-08-27 22:51:26 +00001977 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00001978 ArrayRef<const MemRegion *> Regions,
Jordan Rose740d4902012-07-02 19:27:35 +00001979 const CallEvent *Call) const {
Jordan Rose166d5022012-11-02 01:54:06 +00001980 CStringLengthTy Entries = state->get<CStringLength>();
Jordy Rosea5261542010-08-14 21:02:52 +00001981 if (Entries.isEmpty())
1982 return state;
1983
1984 llvm::SmallPtrSet<const MemRegion *, 8> Invalidated;
1985 llvm::SmallPtrSet<const MemRegion *, 32> SuperRegions;
1986
1987 // First build sets for the changed regions and their super-regions.
Jordy Rose537716a2011-08-27 22:51:26 +00001988 for (ArrayRef<const MemRegion *>::iterator
1989 I = Regions.begin(), E = Regions.end(); I != E; ++I) {
1990 const MemRegion *MR = *I;
Jordy Rosea5261542010-08-14 21:02:52 +00001991 Invalidated.insert(MR);
1992
1993 SuperRegions.insert(MR);
1994 while (const SubRegion *SR = dyn_cast<SubRegion>(MR)) {
1995 MR = SR->getSuperRegion();
1996 SuperRegions.insert(MR);
1997 }
1998 }
1999
Jordan Rose166d5022012-11-02 01:54:06 +00002000 CStringLengthTy::Factory &F = state->get_context<CStringLength>();
Jordy Rosea5261542010-08-14 21:02:52 +00002001
2002 // Then loop over the entries in the current state.
Jordan Rose166d5022012-11-02 01:54:06 +00002003 for (CStringLengthTy::iterator I = Entries.begin(),
Jordy Rosea5261542010-08-14 21:02:52 +00002004 E = Entries.end(); I != E; ++I) {
2005 const MemRegion *MR = I.getKey();
2006
2007 // Is this entry for a super-region of a changed region?
2008 if (SuperRegions.count(MR)) {
Ted Kremenek3baf6722010-11-24 00:54:37 +00002009 Entries = F.remove(Entries, MR);
Jordy Rosea5261542010-08-14 21:02:52 +00002010 continue;
2011 }
2012
2013 // Is this entry for a sub-region of a changed region?
2014 const MemRegion *Super = MR;
2015 while (const SubRegion *SR = dyn_cast<SubRegion>(Super)) {
2016 Super = SR->getSuperRegion();
2017 if (Invalidated.count(Super)) {
Ted Kremenek3baf6722010-11-24 00:54:37 +00002018 Entries = F.remove(Entries, MR);
Jordy Rosea5261542010-08-14 21:02:52 +00002019 break;
2020 }
2021 }
2022 }
2023
2024 return state->set<CStringLength>(Entries);
2025}
2026
Ted Kremenek8bef8232012-01-26 21:29:00 +00002027void CStringChecker::checkLiveSymbols(ProgramStateRef state,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00002028 SymbolReaper &SR) const {
Jordy Rosea5261542010-08-14 21:02:52 +00002029 // Mark all symbols in our string length map as valid.
Jordan Rose166d5022012-11-02 01:54:06 +00002030 CStringLengthTy Entries = state->get<CStringLength>();
Jordy Rosea5261542010-08-14 21:02:52 +00002031
Jordan Rose166d5022012-11-02 01:54:06 +00002032 for (CStringLengthTy::iterator I = Entries.begin(), E = Entries.end();
Jordy Rosea5261542010-08-14 21:02:52 +00002033 I != E; ++I) {
2034 SVal Len = I.getData();
Jordy Rosed5af0e12011-06-15 05:52:56 +00002035
Anna Zaks1d1d5152011-12-06 23:12:33 +00002036 for (SymExpr::symbol_iterator si = Len.symbol_begin(),
2037 se = Len.symbol_end(); si != se; ++si)
Jordy Rosed5af0e12011-06-15 05:52:56 +00002038 SR.markInUse(*si);
Jordy Rosea5261542010-08-14 21:02:52 +00002039 }
2040}
2041
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00002042void CStringChecker::checkDeadSymbols(SymbolReaper &SR,
2043 CheckerContext &C) const {
Jordy Rosea5261542010-08-14 21:02:52 +00002044 if (!SR.hasDeadSymbols())
2045 return;
2046
Ted Kremenek8bef8232012-01-26 21:29:00 +00002047 ProgramStateRef state = C.getState();
Jordan Rose166d5022012-11-02 01:54:06 +00002048 CStringLengthTy Entries = state->get<CStringLength>();
Jordy Rosea5261542010-08-14 21:02:52 +00002049 if (Entries.isEmpty())
2050 return;
2051
Jordan Rose166d5022012-11-02 01:54:06 +00002052 CStringLengthTy::Factory &F = state->get_context<CStringLength>();
2053 for (CStringLengthTy::iterator I = Entries.begin(), E = Entries.end();
Jordy Rosea5261542010-08-14 21:02:52 +00002054 I != E; ++I) {
2055 SVal Len = I.getData();
2056 if (SymbolRef Sym = Len.getAsSymbol()) {
2057 if (SR.isDead(Sym))
Ted Kremenek3baf6722010-11-24 00:54:37 +00002058 Entries = F.remove(Entries, I.getKey());
Jordy Rosea5261542010-08-14 21:02:52 +00002059 }
2060 }
2061
2062 state = state->set<CStringLength>(Entries);
Anna Zaks0bd6b112011-10-26 21:06:34 +00002063 C.addTransition(state);
Jordy Rosea5261542010-08-14 21:02:52 +00002064}
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00002065
Stephen Hines651f13c2014-04-23 16:59:28 -07002066#define REGISTER_CHECKER(name) \
2067 void ento::register##name(CheckerManager &mgr) { \
2068 CStringChecker *checker = mgr.registerChecker<CStringChecker>(); \
2069 checker->Filter.Check##name = true; \
2070 checker->Filter.CheckName##name = mgr.getCurrentCheckName(); \
2071 }
Anna Zaks57300762012-02-07 00:56:14 +00002072
2073REGISTER_CHECKER(CStringNullArg)
2074REGISTER_CHECKER(CStringOutOfBounds)
2075REGISTER_CHECKER(CStringBufferOverlap)
2076REGISTER_CHECKER(CStringNotNullTerm)
Anna Zaksf0dfc9c2012-02-17 22:35:31 +00002077
2078void ento::registerCStringCheckerBasic(CheckerManager &Mgr) {
2079 registerCStringNullArg(Mgr);
2080}