blob: c3736d7e5d71618c1b04a7859d95c4e8edb65e00 [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 > {
Anna Zaks57300762012-02-07 00:56:14 +000038 mutable OwningPtr<BugType> BT_Null,
39 BT_Bounds,
40 BT_Overlap,
41 BT_NotCString,
42 BT_AdditionOverflow;
43
Jordy Rose9e49d9f2011-06-20 02:06:40 +000044 mutable const char *CurrentFunctionDescription;
45
Jordy Roseccbf7ee2010-07-06 23:11:01 +000046public:
Anna Zaks57300762012-02-07 00:56:14 +000047 /// The filter is used to filter out the diagnostics which are not enabled by
48 /// the user.
49 struct CStringChecksFilter {
50 DefaultBool CheckCStringNullArg;
51 DefaultBool CheckCStringOutOfBounds;
52 DefaultBool CheckCStringBufferOverlap;
53 DefaultBool CheckCStringNotNullTerm;
54 };
55
56 CStringChecksFilter Filter;
57
Jordy Roseccbf7ee2010-07-06 23:11:01 +000058 static void *getTag() { static int tag; return &tag; }
59
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000060 bool evalCall(const CallExpr *CE, CheckerContext &C) const;
61 void checkPreStmt(const DeclStmt *DS, CheckerContext &C) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +000062 void checkLiveSymbols(ProgramStateRef state, SymbolReaper &SR) const;
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000063 void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +000064 bool wantsRegionChangeUpdate(ProgramStateRef state) const;
Jordy Rosea5261542010-08-14 21:02:52 +000065
Ted Kremenek8bef8232012-01-26 21:29:00 +000066 ProgramStateRef
67 checkRegionChanges(ProgramStateRef state,
Anna Zaksbf53dfa2012-12-20 00:38:25 +000068 const InvalidatedSymbols *,
Jordy Rose537716a2011-08-27 22:51:26 +000069 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +000070 ArrayRef<const MemRegion *> Regions,
Jordan Rose740d4902012-07-02 19:27:35 +000071 const CallEvent *Call) const;
Jordy Roseccbf7ee2010-07-06 23:11:01 +000072
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000073 typedef void (CStringChecker::*FnCheck)(CheckerContext &,
74 const CallExpr *) const;
Jordy Roseccbf7ee2010-07-06 23:11:01 +000075
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000076 void evalMemcpy(CheckerContext &C, const CallExpr *CE) const;
Lenny Maioranib8b875b2011-03-31 21:36:53 +000077 void evalMempcpy(CheckerContext &C, const CallExpr *CE) const;
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000078 void evalMemmove(CheckerContext &C, const CallExpr *CE) const;
79 void evalBcopy(CheckerContext &C, const CallExpr *CE) const;
Lenny Maioranib8b875b2011-03-31 21:36:53 +000080 void evalCopyCommon(CheckerContext &C, const CallExpr *CE,
Ted Kremenek8bef8232012-01-26 21:29:00 +000081 ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +000082 const Expr *Size,
83 const Expr *Source,
84 const Expr *Dest,
Lenny Maioranib8b875b2011-03-31 21:36:53 +000085 bool Restricted = false,
86 bool IsMempcpy = false) const;
Jordy Rosed325ffb2010-07-08 23:57:29 +000087
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000088 void evalMemcmp(CheckerContext &C, const CallExpr *CE) const;
Jordy Roseccbf7ee2010-07-06 23:11:01 +000089
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000090 void evalstrLength(CheckerContext &C, const CallExpr *CE) const;
91 void evalstrnLength(CheckerContext &C, const CallExpr *CE) const;
Ted Kremenek18c66fd2011-08-15 22:09:50 +000092 void evalstrLengthCommon(CheckerContext &C,
93 const CallExpr *CE,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000094 bool IsStrnlen = false) const;
Jordy Rose19c5dd12010-07-27 01:37:31 +000095
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000096 void evalStrcpy(CheckerContext &C, const CallExpr *CE) const;
97 void evalStrncpy(CheckerContext &C, const CallExpr *CE) const;
98 void evalStpcpy(CheckerContext &C, const CallExpr *CE) const;
Ted Kremenek18c66fd2011-08-15 22:09:50 +000099 void evalStrcpyCommon(CheckerContext &C,
100 const CallExpr *CE,
101 bool returnEnd,
102 bool isBounded,
103 bool isAppending) const;
Lenny Maiorani067bbd02011-04-09 15:12:58 +0000104
105 void evalStrcat(CheckerContext &C, const CallExpr *CE) const;
106 void evalStrncat(CheckerContext &C, const CallExpr *CE) const;
Jordy Rosee64f3112010-08-16 07:51:42 +0000107
Lenny Maiorani318dd922011-04-12 17:08:43 +0000108 void evalStrcmp(CheckerContext &C, const CallExpr *CE) const;
Lenny Maiorani357f6ee2011-04-25 22:21:00 +0000109 void evalStrncmp(CheckerContext &C, const CallExpr *CE) const;
Lenny Maioranibd1d16a2011-04-28 15:09:11 +0000110 void evalStrcasecmp(CheckerContext &C, const CallExpr *CE) const;
Lenny Maiorani454fd2d2011-05-02 19:05:49 +0000111 void evalStrncasecmp(CheckerContext &C, const CallExpr *CE) const;
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000112 void evalStrcmpCommon(CheckerContext &C,
113 const CallExpr *CE,
114 bool isBounded = false,
115 bool ignoreCase = false) const;
Lenny Maiorani318dd922011-04-12 17:08:43 +0000116
Jordan Roseaf226212013-04-22 23:18:42 +0000117 void evalStrsep(CheckerContext &C, const CallExpr *CE) const;
118
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000119 // Utility methods
Ted Kremenek8bef8232012-01-26 21:29:00 +0000120 std::pair<ProgramStateRef , ProgramStateRef >
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000121 static assumeZero(CheckerContext &C,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000122 ProgramStateRef state, SVal V, QualType Ty);
Jordy Rosed325ffb2010-07-08 23:57:29 +0000123
Ted Kremenek8bef8232012-01-26 21:29:00 +0000124 static ProgramStateRef setCStringLength(ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000125 const MemRegion *MR,
126 SVal strLength);
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000127 static SVal getCStringLengthForRegion(CheckerContext &C,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000128 ProgramStateRef &state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000129 const Expr *Ex,
130 const MemRegion *MR,
Jordy Rosed5af0e12011-06-15 05:52:56 +0000131 bool hypothetical);
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000132 SVal getCStringLength(CheckerContext &C,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000133 ProgramStateRef &state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000134 const Expr *Ex,
135 SVal Buf,
Jordy Rosed5af0e12011-06-15 05:52:56 +0000136 bool hypothetical = false) const;
Jordy Rose19c5dd12010-07-27 01:37:31 +0000137
Lenny Maiorani318dd922011-04-12 17:08:43 +0000138 const StringLiteral *getCStringLiteral(CheckerContext &C,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000139 ProgramStateRef &state,
Lenny Maiorani318dd922011-04-12 17:08:43 +0000140 const Expr *expr,
141 SVal val) const;
142
Ted Kremenek8bef8232012-01-26 21:29:00 +0000143 static ProgramStateRef InvalidateBuffer(CheckerContext &C,
Anton Yartsevb7a747b2013-11-17 09:18:48 +0000144 ProgramStateRef state,
145 const Expr *Ex, SVal V,
146 bool IsSourceBuffer);
Jordy Rosee64f3112010-08-16 07:51:42 +0000147
Ted Kremenek9c378f72011-08-12 23:37:29 +0000148 static bool SummarizeRegion(raw_ostream &os, ASTContext &Ctx,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000149 const MemRegion *MR);
Jordy Rose19c5dd12010-07-27 01:37:31 +0000150
151 // Re-usable checks
Ted Kremenek8bef8232012-01-26 21:29:00 +0000152 ProgramStateRef checkNonNull(CheckerContext &C,
153 ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000154 const Expr *S,
155 SVal l) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000156 ProgramStateRef CheckLocation(CheckerContext &C,
157 ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000158 const Expr *S,
159 SVal l,
160 const char *message = NULL) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000161 ProgramStateRef CheckBufferAccess(CheckerContext &C,
162 ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000163 const Expr *Size,
164 const Expr *FirstBuf,
165 const Expr *SecondBuf,
166 const char *firstMessage = NULL,
167 const char *secondMessage = NULL,
168 bool WarnAboutSize = false) const;
169
Ted Kremenek8bef8232012-01-26 21:29:00 +0000170 ProgramStateRef CheckBufferAccess(CheckerContext &C,
171 ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000172 const Expr *Size,
173 const Expr *Buf,
174 const char *message = NULL,
175 bool WarnAboutSize = false) const {
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000176 // This is a convenience override.
Jordy Rose5e5f1502011-06-20 03:49:16 +0000177 return CheckBufferAccess(C, state, Size, Buf, NULL, message, NULL,
178 WarnAboutSize);
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000179 }
Ted Kremenek8bef8232012-01-26 21:29:00 +0000180 ProgramStateRef CheckOverlap(CheckerContext &C,
181 ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000182 const Expr *Size,
183 const Expr *First,
184 const Expr *Second) const;
185 void emitOverlapBug(CheckerContext &C,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000186 ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000187 const Stmt *First,
188 const Stmt *Second) const;
189
Ted Kremenek8bef8232012-01-26 21:29:00 +0000190 ProgramStateRef checkAdditionOverflow(CheckerContext &C,
191 ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000192 NonLoc left,
193 NonLoc right) const;
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000194};
Jordy Rosea5261542010-08-14 21:02:52 +0000195
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000196} //end anonymous namespace
197
Jordan Rose166d5022012-11-02 01:54:06 +0000198REGISTER_MAP_WITH_PROGRAMSTATE(CStringLength, const MemRegion *, SVal)
Jordy Rosea5261542010-08-14 21:02:52 +0000199
Jordy Rosed325ffb2010-07-08 23:57:29 +0000200//===----------------------------------------------------------------------===//
201// Individual checks and utility methods.
202//===----------------------------------------------------------------------===//
203
Ted Kremenek8bef8232012-01-26 21:29:00 +0000204std::pair<ProgramStateRef , ProgramStateRef >
205CStringChecker::assumeZero(CheckerContext &C, ProgramStateRef state, SVal V,
Jordy Rosed325ffb2010-07-08 23:57:29 +0000206 QualType Ty) {
David Blaikiedc84cd52013-02-20 22:23:23 +0000207 Optional<DefinedSVal> val = V.getAs<DefinedSVal>();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000208 if (!val)
Ted Kremenek8bef8232012-01-26 21:29:00 +0000209 return std::pair<ProgramStateRef , ProgramStateRef >(state, state);
Jordy Rosea6b808c2010-07-07 07:48:06 +0000210
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000211 SValBuilder &svalBuilder = C.getSValBuilder();
212 DefinedOrUnknownSVal zero = svalBuilder.makeZeroVal(Ty);
213 return state->assume(svalBuilder.evalEQ(state, *val, zero));
Jordy Rosed325ffb2010-07-08 23:57:29 +0000214}
Jordy Rosea6b808c2010-07-07 07:48:06 +0000215
Ted Kremenek8bef8232012-01-26 21:29:00 +0000216ProgramStateRef CStringChecker::checkNonNull(CheckerContext &C,
217 ProgramStateRef state,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000218 const Expr *S, SVal l) const {
Jordy Rosed325ffb2010-07-08 23:57:29 +0000219 // If a previous check has failed, propagate the failure.
220 if (!state)
221 return NULL;
222
Ted Kremenek8bef8232012-01-26 21:29:00 +0000223 ProgramStateRef stateNull, stateNonNull;
Ted Kremenek28f47b92010-12-01 22:16:56 +0000224 llvm::tie(stateNull, stateNonNull) = assumeZero(C, state, l, S->getType());
Jordy Rosed325ffb2010-07-08 23:57:29 +0000225
226 if (stateNull && !stateNonNull) {
Anna Zaks57300762012-02-07 00:56:14 +0000227 if (!Filter.CheckCStringNullArg)
228 return NULL;
229
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000230 ExplodedNode *N = C.generateSink(stateNull);
Jordy Rosea6b808c2010-07-07 07:48:06 +0000231 if (!N)
232 return NULL;
233
Jordy Rosed325ffb2010-07-08 23:57:29 +0000234 if (!BT_Null)
Jordan Roseedcc1992013-10-04 00:25:24 +0000235 BT_Null.reset(new BuiltinBug(categories::UnixAPI,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000236 "Null pointer argument in call to byte string function"));
Jordy Rosea6b808c2010-07-07 07:48:06 +0000237
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000238 SmallString<80> buf;
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000239 llvm::raw_svector_ostream os(buf);
240 assert(CurrentFunctionDescription);
241 os << "Null pointer argument in call to " << CurrentFunctionDescription;
242
Jordy Rosea6b808c2010-07-07 07:48:06 +0000243 // Generate a report for this bug.
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000244 BuiltinBug *BT = static_cast<BuiltinBug*>(BT_Null.get());
Anna Zakse172e8b2011-08-17 23:00:25 +0000245 BugReport *report = new BugReport(*BT, os.str(), N);
Jordy Rosea6b808c2010-07-07 07:48:06 +0000246
247 report->addRange(S->getSourceRange());
Jordan Rosea1f81bb2012-08-28 00:50:51 +0000248 bugreporter::trackNullOrUndefValue(N, S, *report);
Jordan Rose785950e2012-11-02 01:53:40 +0000249 C.emitReport(report);
Jordy Rosea6b808c2010-07-07 07:48:06 +0000250 return NULL;
251 }
252
253 // From here on, assume that the value is non-null.
Jordy Rosed325ffb2010-07-08 23:57:29 +0000254 assert(stateNonNull);
255 return stateNonNull;
Jordy Rosea6b808c2010-07-07 07:48:06 +0000256}
257
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000258// FIXME: This was originally copied from ArrayBoundChecker.cpp. Refactor?
Ted Kremenek8bef8232012-01-26 21:29:00 +0000259ProgramStateRef CStringChecker::CheckLocation(CheckerContext &C,
260 ProgramStateRef state,
Jordy Rosee64f3112010-08-16 07:51:42 +0000261 const Expr *S, SVal l,
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000262 const char *warningMsg) const {
Jordy Rosed325ffb2010-07-08 23:57:29 +0000263 // If a previous check has failed, propagate the failure.
264 if (!state)
265 return NULL;
266
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000267 // Check for out of bound array element access.
268 const MemRegion *R = l.getAsRegion();
269 if (!R)
270 return state;
271
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000272 const ElementRegion *ER = dyn_cast<ElementRegion>(R);
273 if (!ER)
274 return state;
275
Zhongxing Xu018220c2010-08-11 06:10:55 +0000276 assert(ER->getValueType() == C.getASTContext().CharTy &&
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000277 "CheckLocation should only be called with char* ElementRegions");
278
279 // Get the size of the array.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000280 const SubRegion *superReg = cast<SubRegion>(ER->getSuperRegion());
281 SValBuilder &svalBuilder = C.getSValBuilder();
Jordy Rose1e022412011-06-16 05:51:02 +0000282 SVal Extent =
283 svalBuilder.convertToArrayIndex(superReg->getExtent(svalBuilder));
David Blaikie5251abe2013-02-20 05:52:05 +0000284 DefinedOrUnknownSVal Size = Extent.castAs<DefinedOrUnknownSVal>();
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000285
286 // Get the index of the accessed element.
David Blaikie7a95de62013-02-21 22:23:56 +0000287 DefinedOrUnknownSVal Idx = ER->getIndex().castAs<DefinedOrUnknownSVal>();
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000288
Ted Kremenek8bef8232012-01-26 21:29:00 +0000289 ProgramStateRef StInBound = state->assumeInBound(Idx, Size, true);
290 ProgramStateRef StOutBound = state->assumeInBound(Idx, Size, false);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000291 if (StOutBound && !StInBound) {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000292 ExplodedNode *N = C.generateSink(StOutBound);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000293 if (!N)
294 return NULL;
295
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000296 if (!BT_Bounds) {
297 BT_Bounds.reset(new BuiltinBug("Out-of-bound array access",
298 "Byte string function accesses out-of-bound array element"));
299 }
300 BuiltinBug *BT = static_cast<BuiltinBug*>(BT_Bounds.get());
301
302 // Generate a report for this bug.
Anna Zakse172e8b2011-08-17 23:00:25 +0000303 BugReport *report;
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000304 if (warningMsg) {
Anna Zakse172e8b2011-08-17 23:00:25 +0000305 report = new BugReport(*BT, warningMsg, N);
Jordy Rosee64f3112010-08-16 07:51:42 +0000306 } else {
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000307 assert(CurrentFunctionDescription);
308 assert(CurrentFunctionDescription[0] != '\0');
309
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000310 SmallString<80> buf;
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000311 llvm::raw_svector_ostream os(buf);
Jordan Rose223f0ff2013-02-09 10:09:43 +0000312 os << toUppercase(CurrentFunctionDescription[0])
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000313 << &CurrentFunctionDescription[1]
314 << " accesses out-of-bound array element";
Anna Zakse172e8b2011-08-17 23:00:25 +0000315 report = new BugReport(*BT, os.str(), N);
Jordy Rosee64f3112010-08-16 07:51:42 +0000316 }
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000317
318 // FIXME: It would be nice to eventually make this diagnostic more clear,
319 // e.g., by referencing the original declaration or by saying *why* this
320 // reference is outside the range.
321
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000322 report->addRange(S->getSourceRange());
Jordan Rose785950e2012-11-02 01:53:40 +0000323 C.emitReport(report);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000324 return NULL;
325 }
326
327 // Array bound check succeeded. From this point forward the array bound
328 // should always succeed.
329 return StInBound;
330}
331
Ted Kremenek8bef8232012-01-26 21:29:00 +0000332ProgramStateRef CStringChecker::CheckBufferAccess(CheckerContext &C,
333 ProgramStateRef state,
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000334 const Expr *Size,
335 const Expr *FirstBuf,
Jordy Rosee64f3112010-08-16 07:51:42 +0000336 const Expr *SecondBuf,
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000337 const char *firstMessage,
Jordy Rose5e5f1502011-06-20 03:49:16 +0000338 const char *secondMessage,
339 bool WarnAboutSize) const {
Jordy Rosed325ffb2010-07-08 23:57:29 +0000340 // If a previous check has failed, propagate the failure.
341 if (!state)
342 return NULL;
343
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000344 SValBuilder &svalBuilder = C.getSValBuilder();
Jordy Rose1e022412011-06-16 05:51:02 +0000345 ASTContext &Ctx = svalBuilder.getContext();
Ted Kremenek5eca4822012-01-06 22:09:28 +0000346 const LocationContext *LCtx = C.getLocationContext();
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000347
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000348 QualType sizeTy = Size->getType();
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000349 QualType PtrTy = Ctx.getPointerType(Ctx.CharTy);
350
Jordy Rosea6b808c2010-07-07 07:48:06 +0000351 // Check that the first buffer is non-null.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000352 SVal BufVal = state->getSVal(FirstBuf, LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000353 state = checkNonNull(C, state, FirstBuf, BufVal);
Jordy Rosea6b808c2010-07-07 07:48:06 +0000354 if (!state)
355 return NULL;
356
Anna Zaks57300762012-02-07 00:56:14 +0000357 // If out-of-bounds checking is turned off, skip the rest.
358 if (!Filter.CheckCStringOutOfBounds)
359 return state;
360
Jordy Rosed325ffb2010-07-08 23:57:29 +0000361 // Get the access length and make sure it is known.
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000362 // FIXME: This assumes the caller has already checked that the access length
363 // is positive. And that it's unsigned.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000364 SVal LengthVal = state->getSVal(Size, LCtx);
David Blaikiedc84cd52013-02-20 22:23:23 +0000365 Optional<NonLoc> Length = LengthVal.getAs<NonLoc>();
Jordy Rosed325ffb2010-07-08 23:57:29 +0000366 if (!Length)
367 return state;
368
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000369 // Compute the offset of the last element to be accessed: size-1.
David Blaikie5251abe2013-02-20 05:52:05 +0000370 NonLoc One = svalBuilder.makeIntVal(1, sizeTy).castAs<NonLoc>();
371 NonLoc LastOffset = svalBuilder
372 .evalBinOpNN(state, BO_Sub, *Length, One, sizeTy).castAs<NonLoc>();
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000373
Chris Lattnerfc8f0e12011-04-15 05:22:18 +0000374 // Check that the first buffer is sufficiently long.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000375 SVal BufStart = svalBuilder.evalCast(BufVal, PtrTy, FirstBuf->getType());
David Blaikiedc84cd52013-02-20 22:23:23 +0000376 if (Optional<Loc> BufLoc = BufStart.getAs<Loc>()) {
Jordy Rose5e5f1502011-06-20 03:49:16 +0000377 const Expr *warningExpr = (WarnAboutSize ? Size : FirstBuf);
378
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000379 SVal BufEnd = svalBuilder.evalBinOpLN(state, BO_Add, *BufLoc,
380 LastOffset, PtrTy);
Jordy Rose5e5f1502011-06-20 03:49:16 +0000381 state = CheckLocation(C, state, warningExpr, BufEnd, firstMessage);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000382
Jordy Roseb6a40262010-08-05 23:11:30 +0000383 // If the buffer isn't large enough, abort.
384 if (!state)
385 return NULL;
386 }
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000387
388 // If there's a second buffer, check it as well.
389 if (SecondBuf) {
Ted Kremenek5eca4822012-01-06 22:09:28 +0000390 BufVal = state->getSVal(SecondBuf, LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000391 state = checkNonNull(C, state, SecondBuf, BufVal);
Jordy Rosea6b808c2010-07-07 07:48:06 +0000392 if (!state)
393 return NULL;
394
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000395 BufStart = svalBuilder.evalCast(BufVal, PtrTy, SecondBuf->getType());
David Blaikiedc84cd52013-02-20 22:23:23 +0000396 if (Optional<Loc> BufLoc = BufStart.getAs<Loc>()) {
Jordy Rose5e5f1502011-06-20 03:49:16 +0000397 const Expr *warningExpr = (WarnAboutSize ? Size : SecondBuf);
398
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000399 SVal BufEnd = svalBuilder.evalBinOpLN(state, BO_Add, *BufLoc,
400 LastOffset, PtrTy);
Jordy Rose5e5f1502011-06-20 03:49:16 +0000401 state = CheckLocation(C, state, warningExpr, BufEnd, secondMessage);
Jordy Roseb6a40262010-08-05 23:11:30 +0000402 }
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000403 }
404
405 // Large enough or not, return this state!
406 return state;
407}
408
Ted Kremenek8bef8232012-01-26 21:29:00 +0000409ProgramStateRef CStringChecker::CheckOverlap(CheckerContext &C,
410 ProgramStateRef state,
Jordy Rosed325ffb2010-07-08 23:57:29 +0000411 const Expr *Size,
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000412 const Expr *First,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000413 const Expr *Second) const {
Anna Zaks57300762012-02-07 00:56:14 +0000414 if (!Filter.CheckCStringBufferOverlap)
415 return state;
416
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000417 // Do a simple check for overlap: if the two arguments are from the same
418 // buffer, see if the end of the first is greater than the start of the second
419 // or vice versa.
420
Jordy Rosed325ffb2010-07-08 23:57:29 +0000421 // If a previous check has failed, propagate the failure.
422 if (!state)
423 return NULL;
424
Ted Kremenek8bef8232012-01-26 21:29:00 +0000425 ProgramStateRef stateTrue, stateFalse;
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000426
427 // Get the buffer values and make sure they're known locations.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000428 const LocationContext *LCtx = C.getLocationContext();
429 SVal firstVal = state->getSVal(First, LCtx);
430 SVal secondVal = state->getSVal(Second, LCtx);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000431
David Blaikiedc84cd52013-02-20 22:23:23 +0000432 Optional<Loc> firstLoc = firstVal.getAs<Loc>();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000433 if (!firstLoc)
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000434 return state;
435
David Blaikiedc84cd52013-02-20 22:23:23 +0000436 Optional<Loc> secondLoc = secondVal.getAs<Loc>();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000437 if (!secondLoc)
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000438 return state;
439
440 // Are the two values the same?
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000441 SValBuilder &svalBuilder = C.getSValBuilder();
442 llvm::tie(stateTrue, stateFalse) =
443 state->assume(svalBuilder.evalEQ(state, *firstLoc, *secondLoc));
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000444
445 if (stateTrue && !stateFalse) {
446 // If the values are known to be equal, that's automatically an overlap.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000447 emitOverlapBug(C, stateTrue, First, Second);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000448 return NULL;
449 }
450
Ted Kremenek28f47b92010-12-01 22:16:56 +0000451 // assume the two expressions are not equal.
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000452 assert(stateFalse);
453 state = stateFalse;
454
455 // Which value comes first?
Jordy Roseee2fde12011-06-16 05:56:50 +0000456 QualType cmpTy = svalBuilder.getConditionType();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000457 SVal reverse = svalBuilder.evalBinOpLL(state, BO_GT,
458 *firstLoc, *secondLoc, cmpTy);
David Blaikiedc84cd52013-02-20 22:23:23 +0000459 Optional<DefinedOrUnknownSVal> reverseTest =
David Blaikie5251abe2013-02-20 05:52:05 +0000460 reverse.getAs<DefinedOrUnknownSVal>();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000461 if (!reverseTest)
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000462 return state;
463
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000464 llvm::tie(stateTrue, stateFalse) = state->assume(*reverseTest);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000465 if (stateTrue) {
466 if (stateFalse) {
467 // If we don't know which one comes first, we can't perform this test.
468 return state;
469 } else {
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000470 // Switch the values so that firstVal is before secondVal.
David Blaikie5251abe2013-02-20 05:52:05 +0000471 std::swap(firstLoc, secondLoc);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000472
473 // Switch the Exprs as well, so that they still correspond.
David Blaikie5251abe2013-02-20 05:52:05 +0000474 std::swap(First, Second);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000475 }
476 }
477
478 // Get the length, and make sure it too is known.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000479 SVal LengthVal = state->getSVal(Size, LCtx);
David Blaikiedc84cd52013-02-20 22:23:23 +0000480 Optional<NonLoc> Length = LengthVal.getAs<NonLoc>();
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000481 if (!Length)
482 return state;
483
484 // Convert the first buffer's start address to char*.
485 // Bail out if the cast fails.
Jordy Roseee2fde12011-06-16 05:56:50 +0000486 ASTContext &Ctx = svalBuilder.getContext();
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000487 QualType CharPtrTy = Ctx.getPointerType(Ctx.CharTy);
Jordy Rose1e022412011-06-16 05:51:02 +0000488 SVal FirstStart = svalBuilder.evalCast(*firstLoc, CharPtrTy,
489 First->getType());
David Blaikiedc84cd52013-02-20 22:23:23 +0000490 Optional<Loc> FirstStartLoc = FirstStart.getAs<Loc>();
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000491 if (!FirstStartLoc)
492 return state;
493
494 // Compute the end of the first buffer. Bail out if THAT fails.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000495 SVal FirstEnd = svalBuilder.evalBinOpLN(state, BO_Add,
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000496 *FirstStartLoc, *Length, CharPtrTy);
David Blaikiedc84cd52013-02-20 22:23:23 +0000497 Optional<Loc> FirstEndLoc = FirstEnd.getAs<Loc>();
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000498 if (!FirstEndLoc)
499 return state;
500
501 // Is the end of the first buffer past the start of the second buffer?
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000502 SVal Overlap = svalBuilder.evalBinOpLL(state, BO_GT,
503 *FirstEndLoc, *secondLoc, cmpTy);
David Blaikiedc84cd52013-02-20 22:23:23 +0000504 Optional<DefinedOrUnknownSVal> OverlapTest =
David Blaikie5251abe2013-02-20 05:52:05 +0000505 Overlap.getAs<DefinedOrUnknownSVal>();
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000506 if (!OverlapTest)
507 return state;
508
Ted Kremenek28f47b92010-12-01 22:16:56 +0000509 llvm::tie(stateTrue, stateFalse) = state->assume(*OverlapTest);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000510
511 if (stateTrue && !stateFalse) {
512 // Overlap!
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000513 emitOverlapBug(C, stateTrue, First, Second);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000514 return NULL;
515 }
516
Ted Kremenek28f47b92010-12-01 22:16:56 +0000517 // assume the two expressions don't overlap.
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000518 assert(stateFalse);
519 return stateFalse;
520}
521
Ted Kremenek8bef8232012-01-26 21:29:00 +0000522void CStringChecker::emitOverlapBug(CheckerContext &C, ProgramStateRef state,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000523 const Stmt *First, const Stmt *Second) const {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000524 ExplodedNode *N = C.generateSink(state);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000525 if (!N)
526 return;
527
528 if (!BT_Overlap)
Jordan Roseedcc1992013-10-04 00:25:24 +0000529 BT_Overlap.reset(new BugType(categories::UnixAPI, "Improper arguments"));
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000530
531 // Generate a report for this bug.
Anna Zakse172e8b2011-08-17 23:00:25 +0000532 BugReport *report =
533 new BugReport(*BT_Overlap,
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000534 "Arguments must not be overlapping buffers", N);
535 report->addRange(First->getSourceRange());
536 report->addRange(Second->getSourceRange());
537
Jordan Rose785950e2012-11-02 01:53:40 +0000538 C.emitReport(report);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000539}
540
Ted Kremenek8bef8232012-01-26 21:29:00 +0000541ProgramStateRef CStringChecker::checkAdditionOverflow(CheckerContext &C,
542 ProgramStateRef state,
Jordy Rosed5af0e12011-06-15 05:52:56 +0000543 NonLoc left,
544 NonLoc right) const {
Anna Zaks57300762012-02-07 00:56:14 +0000545 // If out-of-bounds checking is turned off, skip the rest.
546 if (!Filter.CheckCStringOutOfBounds)
547 return state;
548
Jordy Rosed5af0e12011-06-15 05:52:56 +0000549 // If a previous check has failed, propagate the failure.
550 if (!state)
551 return NULL;
552
553 SValBuilder &svalBuilder = C.getSValBuilder();
554 BasicValueFactory &BVF = svalBuilder.getBasicValueFactory();
555
556 QualType sizeTy = svalBuilder.getContext().getSizeType();
557 const llvm::APSInt &maxValInt = BVF.getMaxValue(sizeTy);
558 NonLoc maxVal = svalBuilder.makeIntVal(maxValInt);
559
Anna Zakse3d250e2011-12-11 18:43:40 +0000560 SVal maxMinusRight;
David Blaikie5251abe2013-02-20 05:52:05 +0000561 if (right.getAs<nonloc::ConcreteInt>()) {
Anna Zakse3d250e2011-12-11 18:43:40 +0000562 maxMinusRight = svalBuilder.evalBinOpNN(state, BO_Sub, maxVal, right,
563 sizeTy);
564 } else {
Jordy Rosed5af0e12011-06-15 05:52:56 +0000565 // Try switching the operands. (The order of these two assignments is
566 // important!)
567 maxMinusRight = svalBuilder.evalBinOpNN(state, BO_Sub, maxVal, left,
568 sizeTy);
569 left = right;
570 }
571
David Blaikiedc84cd52013-02-20 22:23:23 +0000572 if (Optional<NonLoc> maxMinusRightNL = maxMinusRight.getAs<NonLoc>()) {
Jordy Rosed5af0e12011-06-15 05:52:56 +0000573 QualType cmpTy = svalBuilder.getConditionType();
574 // If left > max - right, we have an overflow.
575 SVal willOverflow = svalBuilder.evalBinOpNN(state, BO_GT, left,
576 *maxMinusRightNL, cmpTy);
577
Ted Kremenek8bef8232012-01-26 21:29:00 +0000578 ProgramStateRef stateOverflow, stateOkay;
Jordy Rosed5af0e12011-06-15 05:52:56 +0000579 llvm::tie(stateOverflow, stateOkay) =
David Blaikie5251abe2013-02-20 05:52:05 +0000580 state->assume(willOverflow.castAs<DefinedOrUnknownSVal>());
Jordy Rosed5af0e12011-06-15 05:52:56 +0000581
582 if (stateOverflow && !stateOkay) {
583 // We have an overflow. Emit a bug report.
584 ExplodedNode *N = C.generateSink(stateOverflow);
585 if (!N)
586 return NULL;
587
588 if (!BT_AdditionOverflow)
589 BT_AdditionOverflow.reset(new BuiltinBug("API",
590 "Sum of expressions causes overflow"));
591
Jordy Rosed5af0e12011-06-15 05:52:56 +0000592 // This isn't a great error message, but this should never occur in real
593 // code anyway -- you'd have to create a buffer longer than a size_t can
594 // represent, which is sort of a contradiction.
Jordy Rose8cc24912011-06-20 03:51:53 +0000595 const char *warning =
596 "This expression will create a string whose length is too big to "
597 "be represented as a size_t";
Jordy Rosed5af0e12011-06-15 05:52:56 +0000598
599 // Generate a report for this bug.
Jordy Rose8cc24912011-06-20 03:51:53 +0000600 BugReport *report = new BugReport(*BT_AdditionOverflow, warning, N);
Jordan Rose785950e2012-11-02 01:53:40 +0000601 C.emitReport(report);
Jordy Rosed5af0e12011-06-15 05:52:56 +0000602
603 return NULL;
604 }
605
606 // From now on, assume an overflow didn't occur.
607 assert(stateOkay);
608 state = stateOkay;
609 }
610
611 return state;
612}
613
Ted Kremenek8bef8232012-01-26 21:29:00 +0000614ProgramStateRef CStringChecker::setCStringLength(ProgramStateRef state,
Jordy Rosee64f3112010-08-16 07:51:42 +0000615 const MemRegion *MR,
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000616 SVal strLength) {
617 assert(!strLength.isUndef() && "Attempt to set an undefined string length");
Jordy Rosee64f3112010-08-16 07:51:42 +0000618
619 MR = MR->StripCasts();
620
621 switch (MR->getKind()) {
622 case MemRegion::StringRegionKind:
623 // FIXME: This can happen if we strcpy() into a string region. This is
624 // undefined [C99 6.4.5p6], but we should still warn about it.
625 return state;
626
627 case MemRegion::SymbolicRegionKind:
628 case MemRegion::AllocaRegionKind:
629 case MemRegion::VarRegionKind:
630 case MemRegion::FieldRegionKind:
631 case MemRegion::ObjCIvarRegionKind:
Jordy Rose210c05b2011-06-15 05:14:03 +0000632 // These are the types we can currently track string lengths for.
633 break;
Jordy Rosee64f3112010-08-16 07:51:42 +0000634
635 case MemRegion::ElementRegionKind:
636 // FIXME: Handle element regions by upper-bounding the parent region's
637 // string length.
638 return state;
639
640 default:
641 // Other regions (mostly non-data) can't have a reliable C string length.
642 // For now, just ignore the change.
643 // FIXME: These are rare but not impossible. We should output some kind of
644 // warning for things like strcpy((char[]){'a', 0}, "b");
645 return state;
646 }
Jordy Rose210c05b2011-06-15 05:14:03 +0000647
648 if (strLength.isUnknown())
649 return state->remove<CStringLength>(MR);
650
651 return state->set<CStringLength>(MR, strLength);
Jordy Rosee64f3112010-08-16 07:51:42 +0000652}
653
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000654SVal CStringChecker::getCStringLengthForRegion(CheckerContext &C,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000655 ProgramStateRef &state,
Jordy Rosea5261542010-08-14 21:02:52 +0000656 const Expr *Ex,
Jordy Rosed5af0e12011-06-15 05:52:56 +0000657 const MemRegion *MR,
658 bool hypothetical) {
659 if (!hypothetical) {
660 // If there's a recorded length, go ahead and return it.
661 const SVal *Recorded = state->get<CStringLength>(MR);
662 if (Recorded)
663 return *Recorded;
664 }
Jordan Rosea728e922013-08-19 16:27:34 +0000665
Jordy Rosea5261542010-08-14 21:02:52 +0000666 // Otherwise, get a new symbol and update the state.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000667 SValBuilder &svalBuilder = C.getSValBuilder();
668 QualType sizeTy = svalBuilder.getContext().getSizeType();
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000669 SVal strLength = svalBuilder.getMetadataSymbolVal(CStringChecker::getTag(),
Ted Kremenek66c486f2012-08-22 06:26:15 +0000670 MR, Ex, sizeTy,
671 C.blockCount());
Jordy Rosed5af0e12011-06-15 05:52:56 +0000672
Jordan Rosea728e922013-08-19 16:27:34 +0000673 if (!hypothetical) {
674 if (Optional<NonLoc> strLn = strLength.getAs<NonLoc>()) {
675 // In case of unbounded calls strlen etc bound the range to SIZE_MAX/4
676 BasicValueFactory &BVF = svalBuilder.getBasicValueFactory();
677 const llvm::APSInt &maxValInt = BVF.getMaxValue(sizeTy);
678 llvm::APSInt fourInt = APSIntType(maxValInt).getValue(4);
679 const llvm::APSInt *maxLengthInt = BVF.evalAPSInt(BO_Div, maxValInt,
680 fourInt);
681 NonLoc maxLength = svalBuilder.makeIntVal(*maxLengthInt);
682 SVal evalLength = svalBuilder.evalBinOpNN(state, BO_LE, *strLn,
683 maxLength, sizeTy);
684 state = state->assume(evalLength.castAs<DefinedOrUnknownSVal>(), true);
685 }
Jordy Rosed5af0e12011-06-15 05:52:56 +0000686 state = state->set<CStringLength>(MR, strLength);
Jordan Rosea728e922013-08-19 16:27:34 +0000687 }
Jordy Rosed5af0e12011-06-15 05:52:56 +0000688
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000689 return strLength;
Jordy Rosea5261542010-08-14 21:02:52 +0000690}
691
Ted Kremenek8bef8232012-01-26 21:29:00 +0000692SVal CStringChecker::getCStringLength(CheckerContext &C, ProgramStateRef &state,
Jordy Rosed5af0e12011-06-15 05:52:56 +0000693 const Expr *Ex, SVal Buf,
694 bool hypothetical) const {
Jordy Rose19c5dd12010-07-27 01:37:31 +0000695 const MemRegion *MR = Buf.getAsRegion();
696 if (!MR) {
697 // If we can't get a region, see if it's something we /know/ isn't a
698 // C string. In the context of locations, the only time we can issue such
699 // a warning is for labels.
David Blaikiedc84cd52013-02-20 22:23:23 +0000700 if (Optional<loc::GotoLabel> Label = Buf.getAs<loc::GotoLabel>()) {
Anna Zaks57300762012-02-07 00:56:14 +0000701 if (!Filter.CheckCStringNotNullTerm)
702 return UndefinedVal();
703
Anna Zaks0bd6b112011-10-26 21:06:34 +0000704 if (ExplodedNode *N = C.addTransition(state)) {
Jordy Rose19c5dd12010-07-27 01:37:31 +0000705 if (!BT_NotCString)
Jordan Roseedcc1992013-10-04 00:25:24 +0000706 BT_NotCString.reset(new BuiltinBug(categories::UnixAPI,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000707 "Argument is not a null-terminated string."));
Jordy Rose19c5dd12010-07-27 01:37:31 +0000708
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000709 SmallString<120> buf;
Jordy Rose19c5dd12010-07-27 01:37:31 +0000710 llvm::raw_svector_ostream os(buf);
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000711 assert(CurrentFunctionDescription);
712 os << "Argument to " << CurrentFunctionDescription
713 << " is the address of the label '" << Label->getLabel()->getName()
Jordy Rose19c5dd12010-07-27 01:37:31 +0000714 << "', which is not a null-terminated string";
715
716 // Generate a report for this bug.
Anna Zakse172e8b2011-08-17 23:00:25 +0000717 BugReport *report = new BugReport(*BT_NotCString,
Jordy Rose19c5dd12010-07-27 01:37:31 +0000718 os.str(), N);
719
720 report->addRange(Ex->getSourceRange());
Jordan Rose785950e2012-11-02 01:53:40 +0000721 C.emitReport(report);
Jordy Rose19c5dd12010-07-27 01:37:31 +0000722 }
Jordy Rose19c5dd12010-07-27 01:37:31 +0000723 return UndefinedVal();
Anna Zaks57300762012-02-07 00:56:14 +0000724
Jordy Rose19c5dd12010-07-27 01:37:31 +0000725 }
726
Jordy Rosea5261542010-08-14 21:02:52 +0000727 // If it's not a region and not a label, give up.
728 return UnknownVal();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000729 }
730
Jordy Rosea5261542010-08-14 21:02:52 +0000731 // If we have a region, strip casts from it and see if we can figure out
732 // its length. For anything we can't figure out, just return UnknownVal.
733 MR = MR->StripCasts();
734
735 switch (MR->getKind()) {
736 case MemRegion::StringRegionKind: {
737 // Modifying the contents of string regions is undefined [C99 6.4.5p6],
738 // so we can assume that the byte length is the correct C string length.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000739 SValBuilder &svalBuilder = C.getSValBuilder();
740 QualType sizeTy = svalBuilder.getContext().getSizeType();
741 const StringLiteral *strLit = cast<StringRegion>(MR)->getStringLiteral();
742 return svalBuilder.makeIntVal(strLit->getByteLength(), sizeTy);
Jordy Rosea5261542010-08-14 21:02:52 +0000743 }
744 case MemRegion::SymbolicRegionKind:
745 case MemRegion::AllocaRegionKind:
746 case MemRegion::VarRegionKind:
747 case MemRegion::FieldRegionKind:
748 case MemRegion::ObjCIvarRegionKind:
Jordy Rosed5af0e12011-06-15 05:52:56 +0000749 return getCStringLengthForRegion(C, state, Ex, MR, hypothetical);
Jordy Rosea5261542010-08-14 21:02:52 +0000750 case MemRegion::CompoundLiteralRegionKind:
751 // FIXME: Can we track this? Is it necessary?
752 return UnknownVal();
753 case MemRegion::ElementRegionKind:
754 // FIXME: How can we handle this? It's not good enough to subtract the
755 // offset from the base string length; consider "123\x00567" and &a[5].
756 return UnknownVal();
757 default:
758 // Other regions (mostly non-data) can't have a reliable C string length.
759 // In this case, an error is emitted and UndefinedVal is returned.
760 // The caller should always be prepared to handle this case.
Anna Zaks57300762012-02-07 00:56:14 +0000761 if (!Filter.CheckCStringNotNullTerm)
762 return UndefinedVal();
763
Anna Zaks0bd6b112011-10-26 21:06:34 +0000764 if (ExplodedNode *N = C.addTransition(state)) {
Jordy Rosea5261542010-08-14 21:02:52 +0000765 if (!BT_NotCString)
Jordan Roseedcc1992013-10-04 00:25:24 +0000766 BT_NotCString.reset(new BuiltinBug(categories::UnixAPI,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000767 "Argument is not a null-terminated string."));
Jordy Rosea5261542010-08-14 21:02:52 +0000768
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000769 SmallString<120> buf;
Jordy Rosea5261542010-08-14 21:02:52 +0000770 llvm::raw_svector_ostream os(buf);
771
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000772 assert(CurrentFunctionDescription);
773 os << "Argument to " << CurrentFunctionDescription << " is ";
Jordy Rosea5261542010-08-14 21:02:52 +0000774
775 if (SummarizeRegion(os, C.getASTContext(), MR))
776 os << ", which is not a null-terminated string";
777 else
778 os << "not a null-terminated string";
779
780 // Generate a report for this bug.
Anna Zakse172e8b2011-08-17 23:00:25 +0000781 BugReport *report = new BugReport(*BT_NotCString,
Jordy Rosea5261542010-08-14 21:02:52 +0000782 os.str(), N);
783
784 report->addRange(Ex->getSourceRange());
Jordan Rose785950e2012-11-02 01:53:40 +0000785 C.emitReport(report);
Jordy Rosea5261542010-08-14 21:02:52 +0000786 }
787
788 return UndefinedVal();
789 }
Jordy Rose19c5dd12010-07-27 01:37:31 +0000790}
791
Lenny Maiorani318dd922011-04-12 17:08:43 +0000792const StringLiteral *CStringChecker::getCStringLiteral(CheckerContext &C,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000793 ProgramStateRef &state, const Expr *expr, SVal val) const {
Lenny Maiorani318dd922011-04-12 17:08:43 +0000794
795 // Get the memory region pointed to by the val.
796 const MemRegion *bufRegion = val.getAsRegion();
797 if (!bufRegion)
798 return NULL;
799
800 // Strip casts off the memory region.
801 bufRegion = bufRegion->StripCasts();
802
803 // Cast the memory region to a string region.
804 const StringRegion *strRegion= dyn_cast<StringRegion>(bufRegion);
805 if (!strRegion)
806 return NULL;
807
808 // Return the actual string in the string region.
809 return strRegion->getStringLiteral();
810}
811
Ted Kremenek8bef8232012-01-26 21:29:00 +0000812ProgramStateRef CStringChecker::InvalidateBuffer(CheckerContext &C,
Anton Yartsevb7a747b2013-11-17 09:18:48 +0000813 ProgramStateRef state,
814 const Expr *E, SVal V,
815 bool IsSourceBuffer) {
David Blaikiedc84cd52013-02-20 22:23:23 +0000816 Optional<Loc> L = V.getAs<Loc>();
Jordy Rosee64f3112010-08-16 07:51:42 +0000817 if (!L)
818 return state;
819
820 // FIXME: This is a simplified version of what's in CFRefCount.cpp -- it makes
821 // some assumptions about the value that CFRefCount can't. Even so, it should
822 // probably be refactored.
David Blaikiedc84cd52013-02-20 22:23:23 +0000823 if (Optional<loc::MemRegionVal> MR = L->getAs<loc::MemRegionVal>()) {
Jordy Rosee64f3112010-08-16 07:51:42 +0000824 const MemRegion *R = MR->getRegion()->StripCasts();
825
826 // Are we dealing with an ElementRegion? If so, we should be invalidating
827 // the super-region.
828 if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
829 R = ER->getSuperRegion();
830 // FIXME: What about layers of ElementRegions?
831 }
832
833 // Invalidate this region.
Ted Kremenek3133f792012-02-17 23:13:45 +0000834 const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
Anton Yartsevb7a747b2013-11-17 09:18:48 +0000835
836 bool CausesPointerEscape = false;
837 RegionAndSymbolInvalidationTraits ITraits;
838 // Invalidate and escape only indirect regions accessible through the source
839 // buffer.
840 if (IsSourceBuffer) {
841 ITraits.setTrait(R,
842 RegionAndSymbolInvalidationTraits::TK_PreserveContents);
843 ITraits.setTrait(R, RegionAndSymbolInvalidationTraits::TK_SuppressEscape);
844 CausesPointerEscape = true;
845 }
846
847 return state->invalidateRegions(R, E, C.blockCount(), LCtx,
848 CausesPointerEscape, 0, 0, &ITraits);
Jordy Rosee64f3112010-08-16 07:51:42 +0000849 }
850
851 // If we have a non-region value by chance, just remove the binding.
852 // FIXME: is this necessary or correct? This handles the non-Region
853 // cases. Is it ever valid to store to these?
Ted Kremenek56a46b52012-08-22 06:37:46 +0000854 return state->killBinding(*L);
Jordy Rosee64f3112010-08-16 07:51:42 +0000855}
856
Ted Kremenek9c378f72011-08-12 23:37:29 +0000857bool CStringChecker::SummarizeRegion(raw_ostream &os, ASTContext &Ctx,
Jordy Rose19c5dd12010-07-27 01:37:31 +0000858 const MemRegion *MR) {
Ted Kremenek96979342011-08-12 20:02:48 +0000859 const TypedValueRegion *TVR = dyn_cast<TypedValueRegion>(MR);
Jordy Rose19c5dd12010-07-27 01:37:31 +0000860
Jordy Rose096aef92011-08-12 21:41:07 +0000861 switch (MR->getKind()) {
Jordy Rose19c5dd12010-07-27 01:37:31 +0000862 case MemRegion::FunctionTextRegionKind: {
Anna Zaks5fc1d0c2012-09-17 19:13:56 +0000863 const NamedDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000864 if (FD)
Benjamin Kramerb8989f22011-10-14 18:45:37 +0000865 os << "the address of the function '" << *FD << '\'';
Jordy Rose19c5dd12010-07-27 01:37:31 +0000866 else
867 os << "the address of a function";
868 return true;
869 }
870 case MemRegion::BlockTextRegionKind:
871 os << "block text";
872 return true;
873 case MemRegion::BlockDataRegionKind:
874 os << "a block";
875 return true;
876 case MemRegion::CXXThisRegionKind:
Zhongxing Xu02fe28c2010-11-26 08:52:48 +0000877 case MemRegion::CXXTempObjectRegionKind:
Ted Kremenek96979342011-08-12 20:02:48 +0000878 os << "a C++ temp object of type " << TVR->getValueType().getAsString();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000879 return true;
880 case MemRegion::VarRegionKind:
Ted Kremenek96979342011-08-12 20:02:48 +0000881 os << "a variable of type" << TVR->getValueType().getAsString();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000882 return true;
883 case MemRegion::FieldRegionKind:
Ted Kremenek96979342011-08-12 20:02:48 +0000884 os << "a field of type " << TVR->getValueType().getAsString();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000885 return true;
886 case MemRegion::ObjCIvarRegionKind:
Ted Kremenek96979342011-08-12 20:02:48 +0000887 os << "an instance variable of type " << TVR->getValueType().getAsString();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000888 return true;
889 default:
890 return false;
891 }
892}
893
Jordy Rosed325ffb2010-07-08 23:57:29 +0000894//===----------------------------------------------------------------------===//
Ted Kremenek9c149532010-12-01 21:57:22 +0000895// evaluation of individual function calls.
Jordy Rosed325ffb2010-07-08 23:57:29 +0000896//===----------------------------------------------------------------------===//
897
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000898void CStringChecker::evalCopyCommon(CheckerContext &C,
899 const CallExpr *CE,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000900 ProgramStateRef state,
Jordy Rosed325ffb2010-07-08 23:57:29 +0000901 const Expr *Size, const Expr *Dest,
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000902 const Expr *Source, bool Restricted,
903 bool IsMempcpy) const {
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000904 CurrentFunctionDescription = "memory copy function";
905
Jordy Rosed325ffb2010-07-08 23:57:29 +0000906 // See if the size argument is zero.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000907 const LocationContext *LCtx = C.getLocationContext();
908 SVal sizeVal = state->getSVal(Size, LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000909 QualType sizeTy = Size->getType();
Jordy Rosed325ffb2010-07-08 23:57:29 +0000910
Ted Kremenek8bef8232012-01-26 21:29:00 +0000911 ProgramStateRef stateZeroSize, stateNonZeroSize;
Jordy Rose1e022412011-06-16 05:51:02 +0000912 llvm::tie(stateZeroSize, stateNonZeroSize) =
913 assumeZero(C, state, sizeVal, sizeTy);
Jordy Rosed325ffb2010-07-08 23:57:29 +0000914
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000915 // Get the value of the Dest.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000916 SVal destVal = state->getSVal(Dest, LCtx);
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000917
918 // If the size is zero, there won't be any actual memory access, so
919 // just bind the return value to the destination buffer and return.
Anna Zaksdd160f32012-05-03 18:21:28 +0000920 if (stateZeroSize && !stateNonZeroSize) {
Ted Kremenek5eca4822012-01-06 22:09:28 +0000921 stateZeroSize = stateZeroSize->BindExpr(CE, LCtx, destVal);
Anna Zaks0bd6b112011-10-26 21:06:34 +0000922 C.addTransition(stateZeroSize);
Anna Zaksdd160f32012-05-03 18:21:28 +0000923 return;
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000924 }
Jordy Rosed325ffb2010-07-08 23:57:29 +0000925
926 // If the size can be nonzero, we have to check the other arguments.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000927 if (stateNonZeroSize) {
Jordy Rose22d27172011-06-04 00:04:22 +0000928 state = stateNonZeroSize;
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000929
930 // Ensure the destination is not null. If it is NULL there will be a
931 // NULL pointer dereference.
932 state = checkNonNull(C, state, Dest, destVal);
933 if (!state)
934 return;
935
936 // Get the value of the Src.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000937 SVal srcVal = state->getSVal(Source, LCtx);
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000938
939 // Ensure the source is not null. If it is NULL there will be a
940 // NULL pointer dereference.
941 state = checkNonNull(C, state, Source, srcVal);
942 if (!state)
943 return;
944
Jordy Rose7182b962011-06-04 01:50:25 +0000945 // Ensure the accesses are valid and that the buffers do not overlap.
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000946 const char * const writeWarning =
947 "Memory copy function overflows destination buffer";
Jordy Rosee64f3112010-08-16 07:51:42 +0000948 state = CheckBufferAccess(C, state, Size, Dest, Source,
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000949 writeWarning, /* sourceWarning = */ NULL);
Jordy Rosed325ffb2010-07-08 23:57:29 +0000950 if (Restricted)
951 state = CheckOverlap(C, state, Size, Dest, Source);
Jordy Rosee64f3112010-08-16 07:51:42 +0000952
Jordy Rose7182b962011-06-04 01:50:25 +0000953 if (!state)
954 return;
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000955
Jordy Rose7182b962011-06-04 01:50:25 +0000956 // If this is mempcpy, get the byte after the last byte copied and
957 // bind the expr.
958 if (IsMempcpy) {
David Blaikie5251abe2013-02-20 05:52:05 +0000959 loc::MemRegionVal destRegVal = destVal.castAs<loc::MemRegionVal>();
Jordy Rose7182b962011-06-04 01:50:25 +0000960
961 // Get the length to copy.
David Blaikiedc84cd52013-02-20 22:23:23 +0000962 if (Optional<NonLoc> lenValNonLoc = sizeVal.getAs<NonLoc>()) {
Jordy Rose7182b962011-06-04 01:50:25 +0000963 // Get the byte after the last byte copied.
964 SVal lastElement = C.getSValBuilder().evalBinOpLN(state, BO_Add,
David Blaikie5251abe2013-02-20 05:52:05 +0000965 destRegVal,
Jordy Rose7182b962011-06-04 01:50:25 +0000966 *lenValNonLoc,
967 Dest->getType());
968
969 // The byte after the last byte copied is the return value.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000970 state = state->BindExpr(CE, LCtx, lastElement);
Jordy Rose3f8bb2f2011-06-04 01:47:27 +0000971 } else {
Jordy Rose7182b962011-06-04 01:50:25 +0000972 // If we don't know how much we copied, we can at least
973 // conjure a return value for later.
Ted Kremenek66c486f2012-08-22 06:26:15 +0000974 SVal result = C.getSValBuilder().conjureSymbolVal(0, CE, LCtx,
975 C.blockCount());
Ted Kremenek5eca4822012-01-06 22:09:28 +0000976 state = state->BindExpr(CE, LCtx, result);
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000977 }
978
Jordy Rose7182b962011-06-04 01:50:25 +0000979 } else {
980 // All other copies return the destination buffer.
981 // (Well, bcopy() has a void return type, but this won't hurt.)
Ted Kremenek5eca4822012-01-06 22:09:28 +0000982 state = state->BindExpr(CE, LCtx, destVal);
Jordy Rosee64f3112010-08-16 07:51:42 +0000983 }
Jordy Rose7182b962011-06-04 01:50:25 +0000984
Anton Yartsevb7a747b2013-11-17 09:18:48 +0000985 // Invalidate the destination (regular invalidation without pointer-escaping
986 // the address of the top-level region).
Jordy Rose7182b962011-06-04 01:50:25 +0000987 // FIXME: Even if we can't perfectly model the copy, we should see if we
988 // can use LazyCompoundVals to copy the source values into the destination.
989 // This would probably remove any existing bindings past the end of the
990 // copied region, but that's still an improvement over blank invalidation.
Anton Yartsevb7a747b2013-11-17 09:18:48 +0000991 state = InvalidateBuffer(C, state, Dest, C.getSVal(Dest),
992 /*IsSourceBuffer*/false);
993
994 // Invalidate the source (const-invalidation without const-pointer-escaping
995 // the address of the top-level region).
996 state = InvalidateBuffer(C, state, Source, C.getSVal(Source),
997 /*IsSourceBuffer*/true);
998
Anna Zaks0bd6b112011-10-26 21:06:34 +0000999 C.addTransition(state);
Jordy Rosed325ffb2010-07-08 23:57:29 +00001000 }
1001}
1002
1003
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001004void CStringChecker::evalMemcpy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001005 if (CE->getNumArgs() < 3)
1006 return;
1007
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001008 // void *memcpy(void *restrict dst, const void *restrict src, size_t n);
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001009 // The return value is the address of the destination buffer.
Jordy Rosed325ffb2010-07-08 23:57:29 +00001010 const Expr *Dest = CE->getArg(0);
Ted Kremenek8bef8232012-01-26 21:29:00 +00001011 ProgramStateRef state = C.getState();
Jordy Rose3f8bb2f2011-06-04 01:47:27 +00001012
Lenny Maioranib8b875b2011-03-31 21:36:53 +00001013 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1), true);
1014}
1015
1016void CStringChecker::evalMempcpy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001017 if (CE->getNumArgs() < 3)
1018 return;
1019
Lenny Maioranib8b875b2011-03-31 21:36:53 +00001020 // void *mempcpy(void *restrict dst, const void *restrict src, size_t n);
1021 // The return value is a pointer to the byte following the last written byte.
1022 const Expr *Dest = CE->getArg(0);
Ted Kremenek8bef8232012-01-26 21:29:00 +00001023 ProgramStateRef state = C.getState();
Lenny Maioranib8b875b2011-03-31 21:36:53 +00001024
1025 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1), true, true);
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001026}
1027
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001028void CStringChecker::evalMemmove(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001029 if (CE->getNumArgs() < 3)
1030 return;
1031
Jordy Rosed325ffb2010-07-08 23:57:29 +00001032 // void *memmove(void *dst, const void *src, size_t n);
1033 // The return value is the address of the destination buffer.
1034 const Expr *Dest = CE->getArg(0);
Ted Kremenek8bef8232012-01-26 21:29:00 +00001035 ProgramStateRef state = C.getState();
Jordy Rose3f8bb2f2011-06-04 01:47:27 +00001036
Lenny Maioranib8b875b2011-03-31 21:36:53 +00001037 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1));
Jordy Rosed325ffb2010-07-08 23:57:29 +00001038}
1039
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001040void CStringChecker::evalBcopy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001041 if (CE->getNumArgs() < 3)
1042 return;
1043
Jordy Rosed325ffb2010-07-08 23:57:29 +00001044 // void bcopy(const void *src, void *dst, size_t n);
Lenny Maioranib8b875b2011-03-31 21:36:53 +00001045 evalCopyCommon(C, CE, C.getState(),
1046 CE->getArg(2), CE->getArg(1), CE->getArg(0));
Jordy Rosed325ffb2010-07-08 23:57:29 +00001047}
1048
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001049void CStringChecker::evalMemcmp(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001050 if (CE->getNumArgs() < 3)
1051 return;
1052
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001053 // int memcmp(const void *s1, const void *s2, size_t n);
Jordy Rose9e49d9f2011-06-20 02:06:40 +00001054 CurrentFunctionDescription = "memory comparison function";
1055
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001056 const Expr *Left = CE->getArg(0);
1057 const Expr *Right = CE->getArg(1);
1058 const Expr *Size = CE->getArg(2);
1059
Ted Kremenek8bef8232012-01-26 21:29:00 +00001060 ProgramStateRef state = C.getState();
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001061 SValBuilder &svalBuilder = C.getSValBuilder();
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001062
Jordy Rosed325ffb2010-07-08 23:57:29 +00001063 // See if the size argument is zero.
Ted Kremenek5eca4822012-01-06 22:09:28 +00001064 const LocationContext *LCtx = C.getLocationContext();
1065 SVal sizeVal = state->getSVal(Size, LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001066 QualType sizeTy = Size->getType();
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001067
Ted Kremenek8bef8232012-01-26 21:29:00 +00001068 ProgramStateRef stateZeroSize, stateNonZeroSize;
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001069 llvm::tie(stateZeroSize, stateNonZeroSize) =
1070 assumeZero(C, state, sizeVal, sizeTy);
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001071
Jordy Rosed325ffb2010-07-08 23:57:29 +00001072 // If the size can be zero, the result will be 0 in that case, and we don't
1073 // have to check either of the buffers.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001074 if (stateZeroSize) {
1075 state = stateZeroSize;
Ted Kremenek5eca4822012-01-06 22:09:28 +00001076 state = state->BindExpr(CE, LCtx,
1077 svalBuilder.makeZeroVal(CE->getType()));
Anna Zaks0bd6b112011-10-26 21:06:34 +00001078 C.addTransition(state);
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001079 }
1080
Jordy Rosed325ffb2010-07-08 23:57:29 +00001081 // If the size can be nonzero, we have to check the other arguments.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001082 if (stateNonZeroSize) {
1083 state = stateNonZeroSize;
Jordy Rosed325ffb2010-07-08 23:57:29 +00001084 // If we know the two buffers are the same, we know the result is 0.
1085 // First, get the two buffers' addresses. Another checker will have already
1086 // made sure they're not undefined.
Ted Kremenek5eca4822012-01-06 22:09:28 +00001087 DefinedOrUnknownSVal LV =
David Blaikie5251abe2013-02-20 05:52:05 +00001088 state->getSVal(Left, LCtx).castAs<DefinedOrUnknownSVal>();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001089 DefinedOrUnknownSVal RV =
David Blaikie5251abe2013-02-20 05:52:05 +00001090 state->getSVal(Right, LCtx).castAs<DefinedOrUnknownSVal>();
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001091
Jordy Rosed325ffb2010-07-08 23:57:29 +00001092 // See if they are the same.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001093 DefinedOrUnknownSVal SameBuf = svalBuilder.evalEQ(state, LV, RV);
Ted Kremenek8bef8232012-01-26 21:29:00 +00001094 ProgramStateRef StSameBuf, StNotSameBuf;
Ted Kremenek28f47b92010-12-01 22:16:56 +00001095 llvm::tie(StSameBuf, StNotSameBuf) = state->assume(SameBuf);
Jordy Rosed325ffb2010-07-08 23:57:29 +00001096
Jordy Rose1e022412011-06-16 05:51:02 +00001097 // If the two arguments might be the same buffer, we know the result is 0,
Jordy Rosed325ffb2010-07-08 23:57:29 +00001098 // and we only need to check one size.
1099 if (StSameBuf) {
1100 state = StSameBuf;
1101 state = CheckBufferAccess(C, state, Size, Left);
1102 if (state) {
Ted Kremenek5eca4822012-01-06 22:09:28 +00001103 state = StSameBuf->BindExpr(CE, LCtx,
1104 svalBuilder.makeZeroVal(CE->getType()));
Anna Zaks0bd6b112011-10-26 21:06:34 +00001105 C.addTransition(state);
Jordy Rosed325ffb2010-07-08 23:57:29 +00001106 }
1107 }
1108
1109 // If the two arguments might be different buffers, we have to check the
1110 // size of both of them.
1111 if (StNotSameBuf) {
1112 state = StNotSameBuf;
1113 state = CheckBufferAccess(C, state, Size, Left, Right);
1114 if (state) {
1115 // The return value is the comparison result, which we don't know.
Ted Kremenek66c486f2012-08-22 06:26:15 +00001116 SVal CmpV = svalBuilder.conjureSymbolVal(0, CE, LCtx, C.blockCount());
Ted Kremenek5eca4822012-01-06 22:09:28 +00001117 state = state->BindExpr(CE, LCtx, CmpV);
Anna Zaks0bd6b112011-10-26 21:06:34 +00001118 C.addTransition(state);
Jordy Rosed325ffb2010-07-08 23:57:29 +00001119 }
1120 }
1121 }
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001122}
1123
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001124void CStringChecker::evalstrLength(CheckerContext &C,
1125 const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001126 if (CE->getNumArgs() < 1)
1127 return;
1128
Jordy Rose19c5dd12010-07-27 01:37:31 +00001129 // size_t strlen(const char *s);
Ted Kremenekbe4242c2011-02-22 04:55:05 +00001130 evalstrLengthCommon(C, CE, /* IsStrnlen = */ false);
1131}
1132
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001133void CStringChecker::evalstrnLength(CheckerContext &C,
1134 const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001135 if (CE->getNumArgs() < 2)
1136 return;
1137
Ted Kremenekbe4242c2011-02-22 04:55:05 +00001138 // size_t strnlen(const char *s, size_t maxlen);
1139 evalstrLengthCommon(C, CE, /* IsStrnlen = */ true);
1140}
1141
1142void CStringChecker::evalstrLengthCommon(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001143 bool IsStrnlen) const {
Jordy Rose9e49d9f2011-06-20 02:06:40 +00001144 CurrentFunctionDescription = "string length function";
Ted Kremenek8bef8232012-01-26 21:29:00 +00001145 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001146 const LocationContext *LCtx = C.getLocationContext();
Jordy Rose793bff32011-06-14 01:15:31 +00001147
1148 if (IsStrnlen) {
1149 const Expr *maxlenExpr = CE->getArg(1);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001150 SVal maxlenVal = state->getSVal(maxlenExpr, LCtx);
Jordy Rose793bff32011-06-14 01:15:31 +00001151
Ted Kremenek8bef8232012-01-26 21:29:00 +00001152 ProgramStateRef stateZeroSize, stateNonZeroSize;
Jordy Rose793bff32011-06-14 01:15:31 +00001153 llvm::tie(stateZeroSize, stateNonZeroSize) =
1154 assumeZero(C, state, maxlenVal, maxlenExpr->getType());
1155
1156 // If the size can be zero, the result will be 0 in that case, and we don't
1157 // have to check the string itself.
1158 if (stateZeroSize) {
1159 SVal zero = C.getSValBuilder().makeZeroVal(CE->getType());
Ted Kremenek5eca4822012-01-06 22:09:28 +00001160 stateZeroSize = stateZeroSize->BindExpr(CE, LCtx, zero);
Anna Zaks0bd6b112011-10-26 21:06:34 +00001161 C.addTransition(stateZeroSize);
Jordy Rose793bff32011-06-14 01:15:31 +00001162 }
1163
1164 // If the size is GUARANTEED to be zero, we're done!
1165 if (!stateNonZeroSize)
1166 return;
1167
1168 // Otherwise, record the assumption that the size is nonzero.
1169 state = stateNonZeroSize;
1170 }
1171
1172 // Check that the string argument is non-null.
Jordy Rose19c5dd12010-07-27 01:37:31 +00001173 const Expr *Arg = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001174 SVal ArgVal = state->getSVal(Arg, LCtx);
Jordy Rose19c5dd12010-07-27 01:37:31 +00001175
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001176 state = checkNonNull(C, state, Arg, ArgVal);
Jordy Rose19c5dd12010-07-27 01:37:31 +00001177
Jordy Rosebd32bee2011-06-14 01:26:48 +00001178 if (!state)
1179 return;
Jordy Rosea5261542010-08-14 21:02:52 +00001180
Jordy Rosebd32bee2011-06-14 01:26:48 +00001181 SVal strLength = getCStringLength(C, state, Arg, ArgVal);
Jordy Rosea5261542010-08-14 21:02:52 +00001182
Jordy Rosebd32bee2011-06-14 01:26:48 +00001183 // If the argument isn't a valid C string, there's no valid state to
1184 // transition to.
1185 if (strLength.isUndef())
1186 return;
Jordy Rose793bff32011-06-14 01:15:31 +00001187
Jordy Rosebd32bee2011-06-14 01:26:48 +00001188 DefinedOrUnknownSVal result = UnknownVal();
Jordy Rose793bff32011-06-14 01:15:31 +00001189
Jordy Rosebd32bee2011-06-14 01:26:48 +00001190 // If the check is for strnlen() then bind the return value to no more than
1191 // the maxlen value.
1192 if (IsStrnlen) {
Jordy Roseee2fde12011-06-16 05:56:50 +00001193 QualType cmpTy = C.getSValBuilder().getConditionType();
Jordy Rose793bff32011-06-14 01:15:31 +00001194
Jordy Rosebd32bee2011-06-14 01:26:48 +00001195 // It's a little unfortunate to be getting this again,
1196 // but it's not that expensive...
1197 const Expr *maxlenExpr = CE->getArg(1);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001198 SVal maxlenVal = state->getSVal(maxlenExpr, LCtx);
Ted Kremenekbe4242c2011-02-22 04:55:05 +00001199
David Blaikiedc84cd52013-02-20 22:23:23 +00001200 Optional<NonLoc> strLengthNL = strLength.getAs<NonLoc>();
1201 Optional<NonLoc> maxlenValNL = maxlenVal.getAs<NonLoc>();
Ted Kremenekbe4242c2011-02-22 04:55:05 +00001202
Jordy Rosebd32bee2011-06-14 01:26:48 +00001203 if (strLengthNL && maxlenValNL) {
Ted Kremenek8bef8232012-01-26 21:29:00 +00001204 ProgramStateRef stateStringTooLong, stateStringNotTooLong;
Jordy Rose793bff32011-06-14 01:15:31 +00001205
Jordy Rosebd32bee2011-06-14 01:26:48 +00001206 // Check if the strLength is greater than the maxlen.
1207 llvm::tie(stateStringTooLong, stateStringNotTooLong) =
David Blaikie5251abe2013-02-20 05:52:05 +00001208 state->assume(C.getSValBuilder().evalBinOpNN(
1209 state, BO_GT, *strLengthNL, *maxlenValNL, cmpTy)
1210 .castAs<DefinedOrUnknownSVal>());
Jordy Rose793bff32011-06-14 01:15:31 +00001211
Jordy Rosebd32bee2011-06-14 01:26:48 +00001212 if (stateStringTooLong && !stateStringNotTooLong) {
1213 // If the string is longer than maxlen, return maxlen.
1214 result = *maxlenValNL;
1215 } else if (stateStringNotTooLong && !stateStringTooLong) {
1216 // If the string is shorter than maxlen, return its length.
1217 result = *strLengthNL;
Ted Kremenekbe4242c2011-02-22 04:55:05 +00001218 }
1219 }
1220
Jordy Rosebd32bee2011-06-14 01:26:48 +00001221 if (result.isUnknown()) {
1222 // If we don't have enough information for a comparison, there's
1223 // no guarantee the full string length will actually be returned.
1224 // All we know is the return value is the min of the string length
1225 // and the limit. This is better than nothing.
Ted Kremenek66c486f2012-08-22 06:26:15 +00001226 result = C.getSValBuilder().conjureSymbolVal(0, CE, LCtx, C.blockCount());
David Blaikie5251abe2013-02-20 05:52:05 +00001227 NonLoc resultNL = result.castAs<NonLoc>();
Jordy Rosebd32bee2011-06-14 01:26:48 +00001228
1229 if (strLengthNL) {
David Blaikie5251abe2013-02-20 05:52:05 +00001230 state = state->assume(C.getSValBuilder().evalBinOpNN(
1231 state, BO_LE, resultNL, *strLengthNL, cmpTy)
1232 .castAs<DefinedOrUnknownSVal>(), true);
Jordy Rosebd32bee2011-06-14 01:26:48 +00001233 }
1234
1235 if (maxlenValNL) {
David Blaikie5251abe2013-02-20 05:52:05 +00001236 state = state->assume(C.getSValBuilder().evalBinOpNN(
1237 state, BO_LE, resultNL, *maxlenValNL, cmpTy)
1238 .castAs<DefinedOrUnknownSVal>(), true);
Jordy Rosebd32bee2011-06-14 01:26:48 +00001239 }
1240 }
1241
1242 } else {
1243 // This is a plain strlen(), not strnlen().
David Blaikie5251abe2013-02-20 05:52:05 +00001244 result = strLength.castAs<DefinedOrUnknownSVal>();
Jordy Rosebd32bee2011-06-14 01:26:48 +00001245
1246 // If we don't know the length of the string, conjure a return
1247 // value, so it can be used in constraints, at least.
1248 if (result.isUnknown()) {
Ted Kremenek66c486f2012-08-22 06:26:15 +00001249 result = C.getSValBuilder().conjureSymbolVal(0, CE, LCtx, C.blockCount());
Jordy Rosebd32bee2011-06-14 01:26:48 +00001250 }
Jordy Rose19c5dd12010-07-27 01:37:31 +00001251 }
Jordy Rosebd32bee2011-06-14 01:26:48 +00001252
1253 // Bind the return value.
1254 assert(!result.isUnknown() && "Should have conjured a value by now");
Ted Kremenek5eca4822012-01-06 22:09:28 +00001255 state = state->BindExpr(CE, LCtx, result);
Anna Zaks0bd6b112011-10-26 21:06:34 +00001256 C.addTransition(state);
Jordy Rose19c5dd12010-07-27 01:37:31 +00001257}
1258
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001259void CStringChecker::evalStrcpy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001260 if (CE->getNumArgs() < 2)
1261 return;
1262
Jordy Rosee64f3112010-08-16 07:51:42 +00001263 // char *strcpy(char *restrict dst, const char *restrict src);
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001264 evalStrcpyCommon(C, CE,
1265 /* returnEnd = */ false,
1266 /* isBounded = */ false,
1267 /* isAppending = */ false);
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001268}
1269
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001270void CStringChecker::evalStrncpy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001271 if (CE->getNumArgs() < 3)
1272 return;
1273
Jordy Rosec1525862011-06-04 00:05:23 +00001274 // char *strncpy(char *restrict dst, const char *restrict src, size_t n);
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001275 evalStrcpyCommon(C, CE,
1276 /* returnEnd = */ false,
1277 /* isBounded = */ true,
1278 /* isAppending = */ false);
Jordy Rosee64f3112010-08-16 07:51:42 +00001279}
1280
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001281void CStringChecker::evalStpcpy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001282 if (CE->getNumArgs() < 2)
1283 return;
1284
Jordy Rosee64f3112010-08-16 07:51:42 +00001285 // char *stpcpy(char *restrict dst, const char *restrict src);
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001286 evalStrcpyCommon(C, CE,
1287 /* returnEnd = */ true,
1288 /* isBounded = */ false,
1289 /* isAppending = */ false);
1290}
1291
1292void CStringChecker::evalStrcat(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001293 if (CE->getNumArgs() < 2)
1294 return;
1295
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001296 //char *strcat(char *restrict s1, const char *restrict s2);
1297 evalStrcpyCommon(C, CE,
1298 /* returnEnd = */ false,
1299 /* isBounded = */ false,
1300 /* isAppending = */ true);
1301}
1302
1303void CStringChecker::evalStrncat(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001304 if (CE->getNumArgs() < 3)
1305 return;
1306
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001307 //char *strncat(char *restrict s1, const char *restrict s2, size_t n);
1308 evalStrcpyCommon(C, CE,
1309 /* returnEnd = */ false,
1310 /* isBounded = */ true,
1311 /* isAppending = */ true);
Jordy Rosee64f3112010-08-16 07:51:42 +00001312}
1313
Ted Kremenek9c149532010-12-01 21:57:22 +00001314void CStringChecker::evalStrcpyCommon(CheckerContext &C, const CallExpr *CE,
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001315 bool returnEnd, bool isBounded,
1316 bool isAppending) const {
Jordy Rose9e49d9f2011-06-20 02:06:40 +00001317 CurrentFunctionDescription = "string copy function";
Ted Kremenek8bef8232012-01-26 21:29:00 +00001318 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001319 const LocationContext *LCtx = C.getLocationContext();
Jordy Rosee64f3112010-08-16 07:51:42 +00001320
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001321 // Check that the destination is non-null.
Jordy Rosee64f3112010-08-16 07:51:42 +00001322 const Expr *Dst = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001323 SVal DstVal = state->getSVal(Dst, LCtx);
Jordy Rosee64f3112010-08-16 07:51:42 +00001324
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001325 state = checkNonNull(C, state, Dst, DstVal);
Jordy Rosee64f3112010-08-16 07:51:42 +00001326 if (!state)
1327 return;
1328
1329 // Check that the source is non-null.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001330 const Expr *srcExpr = CE->getArg(1);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001331 SVal srcVal = state->getSVal(srcExpr, LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001332 state = checkNonNull(C, state, srcExpr, srcVal);
Jordy Rosee64f3112010-08-16 07:51:42 +00001333 if (!state)
1334 return;
1335
1336 // Get the string length of the source.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001337 SVal strLength = getCStringLength(C, state, srcExpr, srcVal);
Jordy Rosee64f3112010-08-16 07:51:42 +00001338
1339 // If the source isn't a valid C string, give up.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001340 if (strLength.isUndef())
Jordy Rosee64f3112010-08-16 07:51:42 +00001341 return;
1342
Jordy Rosed5af0e12011-06-15 05:52:56 +00001343 SValBuilder &svalBuilder = C.getSValBuilder();
1344 QualType cmpTy = svalBuilder.getConditionType();
Jordy Rose8912aae2011-06-20 21:55:40 +00001345 QualType sizeTy = svalBuilder.getContext().getSizeType();
Jordy Rosed5af0e12011-06-15 05:52:56 +00001346
Jordy Rose8912aae2011-06-20 21:55:40 +00001347 // These two values allow checking two kinds of errors:
1348 // - actual overflows caused by a source that doesn't fit in the destination
1349 // - potential overflows caused by a bound that could exceed the destination
Jordy Rosed5af0e12011-06-15 05:52:56 +00001350 SVal amountCopied = UnknownVal();
Jordy Rose8912aae2011-06-20 21:55:40 +00001351 SVal maxLastElementIndex = UnknownVal();
1352 const char *boundWarning = NULL;
Jordy Rosed5af0e12011-06-15 05:52:56 +00001353
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001354 // If the function is strncpy, strncat, etc... it is bounded.
1355 if (isBounded) {
1356 // Get the max number of characters to copy.
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001357 const Expr *lenExpr = CE->getArg(2);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001358 SVal lenVal = state->getSVal(lenExpr, LCtx);
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001359
Jordy Rosed5af0e12011-06-15 05:52:56 +00001360 // Protect against misdeclared strncpy().
Jordy Rose8912aae2011-06-20 21:55:40 +00001361 lenVal = svalBuilder.evalCast(lenVal, sizeTy, lenExpr->getType());
Jordy Rosed5af0e12011-06-15 05:52:56 +00001362
David Blaikiedc84cd52013-02-20 22:23:23 +00001363 Optional<NonLoc> strLengthNL = strLength.getAs<NonLoc>();
1364 Optional<NonLoc> lenValNL = lenVal.getAs<NonLoc>();
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001365
Jordy Rosed5af0e12011-06-15 05:52:56 +00001366 // If we know both values, we might be able to figure out how much
1367 // we're copying.
1368 if (strLengthNL && lenValNL) {
Ted Kremenek8bef8232012-01-26 21:29:00 +00001369 ProgramStateRef stateSourceTooLong, stateSourceNotTooLong;
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001370
Jordy Rosed5af0e12011-06-15 05:52:56 +00001371 // Check if the max number to copy is less than the length of the src.
Jordy Rose8912aae2011-06-20 21:55:40 +00001372 // If the bound is equal to the source length, strncpy won't null-
1373 // terminate the result!
David Blaikie5251abe2013-02-20 05:52:05 +00001374 llvm::tie(stateSourceTooLong, stateSourceNotTooLong) = state->assume(
1375 svalBuilder.evalBinOpNN(state, BO_GE, *strLengthNL, *lenValNL, cmpTy)
1376 .castAs<DefinedOrUnknownSVal>());
Jordy Rosed5af0e12011-06-15 05:52:56 +00001377
1378 if (stateSourceTooLong && !stateSourceNotTooLong) {
1379 // Max number to copy is less than the length of the src, so the actual
1380 // strLength copied is the max number arg.
1381 state = stateSourceTooLong;
1382 amountCopied = lenVal;
1383
1384 } else if (!stateSourceTooLong && stateSourceNotTooLong) {
1385 // The source buffer entirely fits in the bound.
1386 state = stateSourceNotTooLong;
1387 amountCopied = strLength;
1388 }
1389 }
1390
Jordy Rose5e5f1502011-06-20 03:49:16 +00001391 // We still want to know if the bound is known to be too large.
Jordy Rose8912aae2011-06-20 21:55:40 +00001392 if (lenValNL) {
1393 if (isAppending) {
1394 // For strncat, the check is strlen(dst) + lenVal < sizeof(dst)
1395
1396 // Get the string length of the destination. If the destination is
1397 // memory that can't have a string length, we shouldn't be copying
1398 // into it anyway.
1399 SVal dstStrLength = getCStringLength(C, state, Dst, DstVal);
1400 if (dstStrLength.isUndef())
1401 return;
1402
David Blaikiedc84cd52013-02-20 22:23:23 +00001403 if (Optional<NonLoc> dstStrLengthNL = dstStrLength.getAs<NonLoc>()) {
Jordy Rose8912aae2011-06-20 21:55:40 +00001404 maxLastElementIndex = svalBuilder.evalBinOpNN(state, BO_Add,
1405 *lenValNL,
1406 *dstStrLengthNL,
1407 sizeTy);
1408 boundWarning = "Size argument is greater than the free space in the "
1409 "destination buffer";
1410 }
1411
1412 } else {
1413 // For strncpy, this is just checking that lenVal <= sizeof(dst)
1414 // (Yes, strncpy and strncat differ in how they treat termination.
1415 // strncat ALWAYS terminates, but strncpy doesn't.)
Jordy Rose6e4244e2012-05-14 17:58:35 +00001416
1417 // We need a special case for when the copy size is zero, in which
1418 // case strncpy will do no work at all. Our bounds check uses n-1
1419 // as the last element accessed, so n == 0 is problematic.
1420 ProgramStateRef StateZeroSize, StateNonZeroSize;
1421 llvm::tie(StateZeroSize, StateNonZeroSize) =
1422 assumeZero(C, state, *lenValNL, sizeTy);
1423
1424 // If the size is known to be zero, we're done.
1425 if (StateZeroSize && !StateNonZeroSize) {
1426 StateZeroSize = StateZeroSize->BindExpr(CE, LCtx, DstVal);
1427 C.addTransition(StateZeroSize);
1428 return;
1429 }
1430
1431 // Otherwise, go ahead and figure out the last element we'll touch.
1432 // We don't record the non-zero assumption here because we can't
1433 // be sure. We won't warn on a possible zero.
David Blaikie5251abe2013-02-20 05:52:05 +00001434 NonLoc one = svalBuilder.makeIntVal(1, sizeTy).castAs<NonLoc>();
Jordy Rose8912aae2011-06-20 21:55:40 +00001435 maxLastElementIndex = svalBuilder.evalBinOpNN(state, BO_Sub, *lenValNL,
1436 one, sizeTy);
1437 boundWarning = "Size argument is greater than the length of the "
1438 "destination buffer";
1439 }
1440 }
Jordy Rose5e5f1502011-06-20 03:49:16 +00001441
Jordy Rosed5af0e12011-06-15 05:52:56 +00001442 // If we couldn't pin down the copy length, at least bound it.
Jordy Rose8912aae2011-06-20 21:55:40 +00001443 // FIXME: We should actually run this code path for append as well, but
1444 // right now it creates problems with constraints (since we can end up
1445 // trying to pass constraints from symbol to symbol).
1446 if (amountCopied.isUnknown() && !isAppending) {
Jordy Rosed5af0e12011-06-15 05:52:56 +00001447 // Try to get a "hypothetical" string length symbol, which we can later
1448 // set as a real value if that turns out to be the case.
1449 amountCopied = getCStringLength(C, state, lenExpr, srcVal, true);
1450 assert(!amountCopied.isUndef());
1451
David Blaikiedc84cd52013-02-20 22:23:23 +00001452 if (Optional<NonLoc> amountCopiedNL = amountCopied.getAs<NonLoc>()) {
Jordy Rosed5af0e12011-06-15 05:52:56 +00001453 if (lenValNL) {
1454 // amountCopied <= lenVal
1455 SVal copiedLessThanBound = svalBuilder.evalBinOpNN(state, BO_LE,
1456 *amountCopiedNL,
1457 *lenValNL,
1458 cmpTy);
David Blaikie5251abe2013-02-20 05:52:05 +00001459 state = state->assume(
1460 copiedLessThanBound.castAs<DefinedOrUnknownSVal>(), true);
Jordy Rosed5af0e12011-06-15 05:52:56 +00001461 if (!state)
1462 return;
1463 }
1464
1465 if (strLengthNL) {
1466 // amountCopied <= strlen(source)
1467 SVal copiedLessThanSrc = svalBuilder.evalBinOpNN(state, BO_LE,
1468 *amountCopiedNL,
1469 *strLengthNL,
1470 cmpTy);
David Blaikie5251abe2013-02-20 05:52:05 +00001471 state = state->assume(
1472 copiedLessThanSrc.castAs<DefinedOrUnknownSVal>(), true);
Jordy Rosed5af0e12011-06-15 05:52:56 +00001473 if (!state)
1474 return;
1475 }
1476 }
1477 }
1478
1479 } else {
1480 // The function isn't bounded. The amount copied should match the length
1481 // of the source buffer.
1482 amountCopied = strLength;
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001483 }
1484
Jordy Rosed5af0e12011-06-15 05:52:56 +00001485 assert(state);
1486
1487 // This represents the number of characters copied into the destination
1488 // buffer. (It may not actually be the strlen if the destination buffer
1489 // is not terminated.)
1490 SVal finalStrLength = UnknownVal();
1491
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001492 // If this is an appending function (strcat, strncat...) then set the
1493 // string length to strlen(src) + strlen(dst) since the buffer will
1494 // ultimately contain both.
1495 if (isAppending) {
Jordy Rose1e022412011-06-16 05:51:02 +00001496 // Get the string length of the destination. If the destination is memory
1497 // that can't have a string length, we shouldn't be copying into it anyway.
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001498 SVal dstStrLength = getCStringLength(C, state, Dst, DstVal);
1499 if (dstStrLength.isUndef())
1500 return;
1501
David Blaikiedc84cd52013-02-20 22:23:23 +00001502 Optional<NonLoc> srcStrLengthNL = amountCopied.getAs<NonLoc>();
1503 Optional<NonLoc> dstStrLengthNL = dstStrLength.getAs<NonLoc>();
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001504
Jordy Rosed5af0e12011-06-15 05:52:56 +00001505 // If we know both string lengths, we might know the final string length.
1506 if (srcStrLengthNL && dstStrLengthNL) {
1507 // Make sure the two lengths together don't overflow a size_t.
1508 state = checkAdditionOverflow(C, state, *srcStrLengthNL, *dstStrLengthNL);
1509 if (!state)
1510 return;
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001511
Jordy Rosed5af0e12011-06-15 05:52:56 +00001512 finalStrLength = svalBuilder.evalBinOpNN(state, BO_Add, *srcStrLengthNL,
1513 *dstStrLengthNL, sizeTy);
1514 }
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001515
Jordy Rosed5af0e12011-06-15 05:52:56 +00001516 // If we couldn't get a single value for the final string length,
1517 // we can at least bound it by the individual lengths.
1518 if (finalStrLength.isUnknown()) {
1519 // Try to get a "hypothetical" string length symbol, which we can later
1520 // set as a real value if that turns out to be the case.
1521 finalStrLength = getCStringLength(C, state, CE, DstVal, true);
1522 assert(!finalStrLength.isUndef());
1523
David Blaikiedc84cd52013-02-20 22:23:23 +00001524 if (Optional<NonLoc> finalStrLengthNL = finalStrLength.getAs<NonLoc>()) {
Jordy Rosed5af0e12011-06-15 05:52:56 +00001525 if (srcStrLengthNL) {
1526 // finalStrLength >= srcStrLength
1527 SVal sourceInResult = svalBuilder.evalBinOpNN(state, BO_GE,
1528 *finalStrLengthNL,
1529 *srcStrLengthNL,
1530 cmpTy);
David Blaikie5251abe2013-02-20 05:52:05 +00001531 state = state->assume(sourceInResult.castAs<DefinedOrUnknownSVal>(),
Jordy Rosed5af0e12011-06-15 05:52:56 +00001532 true);
1533 if (!state)
1534 return;
1535 }
1536
1537 if (dstStrLengthNL) {
1538 // finalStrLength >= dstStrLength
1539 SVal destInResult = svalBuilder.evalBinOpNN(state, BO_GE,
1540 *finalStrLengthNL,
1541 *dstStrLengthNL,
1542 cmpTy);
David Blaikie5251abe2013-02-20 05:52:05 +00001543 state =
1544 state->assume(destInResult.castAs<DefinedOrUnknownSVal>(), true);
Jordy Rosed5af0e12011-06-15 05:52:56 +00001545 if (!state)
1546 return;
1547 }
1548 }
1549 }
1550
1551 } else {
1552 // Otherwise, this is a copy-over function (strcpy, strncpy, ...), and
1553 // the final string length will match the input string length.
1554 finalStrLength = amountCopied;
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001555 }
1556
Jordy Rosed5af0e12011-06-15 05:52:56 +00001557 // The final result of the function will either be a pointer past the last
1558 // copied element, or a pointer to the start of the destination buffer.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001559 SVal Result = (returnEnd ? UnknownVal() : DstVal);
Jordy Rosee64f3112010-08-16 07:51:42 +00001560
Jordy Rosed5af0e12011-06-15 05:52:56 +00001561 assert(state);
1562
Jordy Rosee64f3112010-08-16 07:51:42 +00001563 // If the destination is a MemRegion, try to check for a buffer overflow and
1564 // record the new string length.
David Blaikiedc84cd52013-02-20 22:23:23 +00001565 if (Optional<loc::MemRegionVal> dstRegVal =
David Blaikie5251abe2013-02-20 05:52:05 +00001566 DstVal.getAs<loc::MemRegionVal>()) {
Jordy Rose8912aae2011-06-20 21:55:40 +00001567 QualType ptrTy = Dst->getType();
1568
1569 // If we have an exact value on a bounded copy, use that to check for
1570 // overflows, rather than our estimate about how much is actually copied.
1571 if (boundWarning) {
David Blaikiedc84cd52013-02-20 22:23:23 +00001572 if (Optional<NonLoc> maxLastNL = maxLastElementIndex.getAs<NonLoc>()) {
Jordy Rose8912aae2011-06-20 21:55:40 +00001573 SVal maxLastElement = svalBuilder.evalBinOpLN(state, BO_Add, *dstRegVal,
1574 *maxLastNL, ptrTy);
1575 state = CheckLocation(C, state, CE->getArg(2), maxLastElement,
1576 boundWarning);
1577 if (!state)
1578 return;
1579 }
1580 }
1581
1582 // Then, if the final length is known...
David Blaikiedc84cd52013-02-20 22:23:23 +00001583 if (Optional<NonLoc> knownStrLength = finalStrLength.getAs<NonLoc>()) {
Jordy Rosed5af0e12011-06-15 05:52:56 +00001584 SVal lastElement = svalBuilder.evalBinOpLN(state, BO_Add, *dstRegVal,
Jordy Rose8912aae2011-06-20 21:55:40 +00001585 *knownStrLength, ptrTy);
Jordy Rosee64f3112010-08-16 07:51:42 +00001586
Jordy Rose8912aae2011-06-20 21:55:40 +00001587 // ...and we haven't checked the bound, we'll check the actual copy.
1588 if (!boundWarning) {
1589 const char * const warningMsg =
1590 "String copy function overflows destination buffer";
1591 state = CheckLocation(C, state, Dst, lastElement, warningMsg);
1592 if (!state)
1593 return;
1594 }
Jordy Rosee64f3112010-08-16 07:51:42 +00001595
1596 // If this is a stpcpy-style copy, the last element is the return value.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001597 if (returnEnd)
1598 Result = lastElement;
Jordy Rosee64f3112010-08-16 07:51:42 +00001599 }
1600
Anton Yartsevb7a747b2013-11-17 09:18:48 +00001601 // Invalidate the destination (regular invalidation without pointer-escaping
1602 // the address of the top-level region). This must happen before we set the
1603 // C string length because invalidation will clear the length.
Jordy Rosee64f3112010-08-16 07:51:42 +00001604 // FIXME: Even if we can't perfectly model the copy, we should see if we
1605 // can use LazyCompoundVals to copy the source values into the destination.
1606 // This would probably remove any existing bindings past the end of the
1607 // string, but that's still an improvement over blank invalidation.
Anton Yartsevb7a747b2013-11-17 09:18:48 +00001608 state = InvalidateBuffer(C, state, Dst, *dstRegVal,
1609 /*IsSourceBuffer*/false);
1610
1611 // Invalidate the source (const-invalidation without const-pointer-escaping
1612 // the address of the top-level region).
1613 state = InvalidateBuffer(C, state, srcExpr, srcVal, /*IsSourceBuffer*/true);
Jordy Rosee64f3112010-08-16 07:51:42 +00001614
Jordy Rose5e5f1502011-06-20 03:49:16 +00001615 // Set the C string length of the destination, if we know it.
Jordy Rose8912aae2011-06-20 21:55:40 +00001616 if (isBounded && !isAppending) {
1617 // strncpy is annoying in that it doesn't guarantee to null-terminate
1618 // the result string. If the original string didn't fit entirely inside
1619 // the bound (including the null-terminator), we don't know how long the
1620 // result is.
1621 if (amountCopied != strLength)
1622 finalStrLength = UnknownVal();
1623 }
1624 state = setCStringLength(state, dstRegVal->getRegion(), finalStrLength);
Jordy Rosee64f3112010-08-16 07:51:42 +00001625 }
1626
Jordy Rosed5af0e12011-06-15 05:52:56 +00001627 assert(state);
1628
Jordy Rosee64f3112010-08-16 07:51:42 +00001629 // If this is a stpcpy-style copy, but we were unable to check for a buffer
1630 // overflow, we still need a result. Conjure a return value.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001631 if (returnEnd && Result.isUnknown()) {
Ted Kremenek66c486f2012-08-22 06:26:15 +00001632 Result = svalBuilder.conjureSymbolVal(0, CE, LCtx, C.blockCount());
Jordy Rosee64f3112010-08-16 07:51:42 +00001633 }
1634
1635 // Set the return value.
Ted Kremenek5eca4822012-01-06 22:09:28 +00001636 state = state->BindExpr(CE, LCtx, Result);
Anna Zaks0bd6b112011-10-26 21:06:34 +00001637 C.addTransition(state);
Jordy Rosee64f3112010-08-16 07:51:42 +00001638}
1639
Lenny Maiorani318dd922011-04-12 17:08:43 +00001640void CStringChecker::evalStrcmp(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001641 if (CE->getNumArgs() < 2)
1642 return;
1643
Jordy Roseadc42d42011-06-16 07:13:34 +00001644 //int strcmp(const char *s1, const char *s2);
Lenny Maioranibd1d16a2011-04-28 15:09:11 +00001645 evalStrcmpCommon(C, CE, /* isBounded = */ false, /* ignoreCase = */ false);
Lenny Maiorani357f6ee2011-04-25 22:21:00 +00001646}
Lenny Maiorani318dd922011-04-12 17:08:43 +00001647
Lenny Maiorani357f6ee2011-04-25 22:21:00 +00001648void CStringChecker::evalStrncmp(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001649 if (CE->getNumArgs() < 3)
1650 return;
1651
Jordy Roseadc42d42011-06-16 07:13:34 +00001652 //int strncmp(const char *s1, const char *s2, size_t n);
Lenny Maioranibd1d16a2011-04-28 15:09:11 +00001653 evalStrcmpCommon(C, CE, /* isBounded = */ true, /* ignoreCase = */ false);
1654}
1655
1656void CStringChecker::evalStrcasecmp(CheckerContext &C,
1657 const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001658 if (CE->getNumArgs() < 2)
1659 return;
1660
Jordy Roseadc42d42011-06-16 07:13:34 +00001661 //int strcasecmp(const char *s1, const char *s2);
Lenny Maioranibd1d16a2011-04-28 15:09:11 +00001662 evalStrcmpCommon(C, CE, /* isBounded = */ false, /* ignoreCase = */ true);
Lenny Maiorani357f6ee2011-04-25 22:21:00 +00001663}
1664
Lenny Maiorani454fd2d2011-05-02 19:05:49 +00001665void CStringChecker::evalStrncasecmp(CheckerContext &C,
1666 const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001667 if (CE->getNumArgs() < 3)
1668 return;
1669
Jordy Roseadc42d42011-06-16 07:13:34 +00001670 //int strncasecmp(const char *s1, const char *s2, size_t n);
Lenny Maiorani454fd2d2011-05-02 19:05:49 +00001671 evalStrcmpCommon(C, CE, /* isBounded = */ true, /* ignoreCase = */ true);
1672}
1673
Lenny Maiorani357f6ee2011-04-25 22:21:00 +00001674void CStringChecker::evalStrcmpCommon(CheckerContext &C, const CallExpr *CE,
Lenny Maioranibd1d16a2011-04-28 15:09:11 +00001675 bool isBounded, bool ignoreCase) const {
Jordy Rose9e49d9f2011-06-20 02:06:40 +00001676 CurrentFunctionDescription = "string comparison function";
Ted Kremenek8bef8232012-01-26 21:29:00 +00001677 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001678 const LocationContext *LCtx = C.getLocationContext();
Lenny Maiorani318dd922011-04-12 17:08:43 +00001679
1680 // Check that the first string is non-null
1681 const Expr *s1 = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001682 SVal s1Val = state->getSVal(s1, LCtx);
Lenny Maiorani318dd922011-04-12 17:08:43 +00001683 state = checkNonNull(C, state, s1, s1Val);
1684 if (!state)
1685 return;
1686
1687 // Check that the second string is non-null.
1688 const Expr *s2 = CE->getArg(1);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001689 SVal s2Val = state->getSVal(s2, LCtx);
Lenny Maiorani318dd922011-04-12 17:08:43 +00001690 state = checkNonNull(C, state, s2, s2Val);
1691 if (!state)
1692 return;
1693
1694 // Get the string length of the first string or give up.
1695 SVal s1Length = getCStringLength(C, state, s1, s1Val);
1696 if (s1Length.isUndef())
1697 return;
1698
1699 // Get the string length of the second string or give up.
1700 SVal s2Length = getCStringLength(C, state, s2, s2Val);
1701 if (s2Length.isUndef())
1702 return;
1703
Jordy Roseadc42d42011-06-16 07:13:34 +00001704 // If we know the two buffers are the same, we know the result is 0.
1705 // First, get the two buffers' addresses. Another checker will have already
1706 // made sure they're not undefined.
David Blaikie5251abe2013-02-20 05:52:05 +00001707 DefinedOrUnknownSVal LV = s1Val.castAs<DefinedOrUnknownSVal>();
1708 DefinedOrUnknownSVal RV = s2Val.castAs<DefinedOrUnknownSVal>();
Lenny Maiorani318dd922011-04-12 17:08:43 +00001709
Jordy Roseadc42d42011-06-16 07:13:34 +00001710 // See if they are the same.
Lenny Maiorani318dd922011-04-12 17:08:43 +00001711 SValBuilder &svalBuilder = C.getSValBuilder();
Jordy Roseadc42d42011-06-16 07:13:34 +00001712 DefinedOrUnknownSVal SameBuf = svalBuilder.evalEQ(state, LV, RV);
Ted Kremenek8bef8232012-01-26 21:29:00 +00001713 ProgramStateRef StSameBuf, StNotSameBuf;
Jordy Roseadc42d42011-06-16 07:13:34 +00001714 llvm::tie(StSameBuf, StNotSameBuf) = state->assume(SameBuf);
Lenny Maiorani318dd922011-04-12 17:08:43 +00001715
Jordy Roseadc42d42011-06-16 07:13:34 +00001716 // If the two arguments might be the same buffer, we know the result is 0,
1717 // and we only need to check one size.
1718 if (StSameBuf) {
Ted Kremenek5eca4822012-01-06 22:09:28 +00001719 StSameBuf = StSameBuf->BindExpr(CE, LCtx,
1720 svalBuilder.makeZeroVal(CE->getType()));
Anna Zaks0bd6b112011-10-26 21:06:34 +00001721 C.addTransition(StSameBuf);
Jordy Roseadc42d42011-06-16 07:13:34 +00001722
1723 // If the two arguments are GUARANTEED to be the same, we're done!
1724 if (!StNotSameBuf)
1725 return;
1726 }
1727
1728 assert(StNotSameBuf);
1729 state = StNotSameBuf;
1730
1731 // At this point we can go about comparing the two buffers.
1732 // For now, we only do this if they're both known string literals.
1733
1734 // Attempt to extract string literals from both expressions.
1735 const StringLiteral *s1StrLiteral = getCStringLiteral(C, state, s1, s1Val);
1736 const StringLiteral *s2StrLiteral = getCStringLiteral(C, state, s2, s2Val);
1737 bool canComputeResult = false;
1738
1739 if (s1StrLiteral && s2StrLiteral) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001740 StringRef s1StrRef = s1StrLiteral->getString();
1741 StringRef s2StrRef = s2StrLiteral->getString();
Jordy Roseadc42d42011-06-16 07:13:34 +00001742
1743 if (isBounded) {
1744 // Get the max number of characters to compare.
1745 const Expr *lenExpr = CE->getArg(2);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001746 SVal lenVal = state->getSVal(lenExpr, LCtx);
Jordy Roseadc42d42011-06-16 07:13:34 +00001747
1748 // If the length is known, we can get the right substrings.
1749 if (const llvm::APSInt *len = svalBuilder.getKnownValue(state, lenVal)) {
1750 // Create substrings of each to compare the prefix.
1751 s1StrRef = s1StrRef.substr(0, (size_t)len->getZExtValue());
1752 s2StrRef = s2StrRef.substr(0, (size_t)len->getZExtValue());
1753 canComputeResult = true;
1754 }
1755 } else {
1756 // This is a normal, unbounded strcmp.
1757 canComputeResult = true;
1758 }
1759
1760 if (canComputeResult) {
1761 // Real strcmp stops at null characters.
1762 size_t s1Term = s1StrRef.find('\0');
Chris Lattner5f9e2722011-07-23 10:55:15 +00001763 if (s1Term != StringRef::npos)
Jordy Roseadc42d42011-06-16 07:13:34 +00001764 s1StrRef = s1StrRef.substr(0, s1Term);
1765
1766 size_t s2Term = s2StrRef.find('\0');
Chris Lattner5f9e2722011-07-23 10:55:15 +00001767 if (s2Term != StringRef::npos)
Jordy Roseadc42d42011-06-16 07:13:34 +00001768 s2StrRef = s2StrRef.substr(0, s2Term);
1769
1770 // Use StringRef's comparison methods to compute the actual result.
1771 int result;
1772
1773 if (ignoreCase) {
1774 // Compare string 1 to string 2 the same way strcasecmp() does.
1775 result = s1StrRef.compare_lower(s2StrRef);
1776 } else {
1777 // Compare string 1 to string 2 the same way strcmp() does.
1778 result = s1StrRef.compare(s2StrRef);
1779 }
1780
1781 // Build the SVal of the comparison and bind the return value.
1782 SVal resultVal = svalBuilder.makeIntVal(result, CE->getType());
Ted Kremenek5eca4822012-01-06 22:09:28 +00001783 state = state->BindExpr(CE, LCtx, resultVal);
Jordy Roseadc42d42011-06-16 07:13:34 +00001784 }
1785 }
1786
1787 if (!canComputeResult) {
1788 // Conjure a symbolic value. It's the best we can do.
Ted Kremenek66c486f2012-08-22 06:26:15 +00001789 SVal resultVal = svalBuilder.conjureSymbolVal(0, CE, LCtx, C.blockCount());
Ted Kremenek5eca4822012-01-06 22:09:28 +00001790 state = state->BindExpr(CE, LCtx, resultVal);
Jordy Roseadc42d42011-06-16 07:13:34 +00001791 }
1792
1793 // Record this as a possible path.
Anna Zaks0bd6b112011-10-26 21:06:34 +00001794 C.addTransition(state);
Lenny Maiorani318dd922011-04-12 17:08:43 +00001795}
1796
Jordan Roseaf226212013-04-22 23:18:42 +00001797void CStringChecker::evalStrsep(CheckerContext &C, const CallExpr *CE) const {
1798 //char *strsep(char **stringp, const char *delim);
1799 if (CE->getNumArgs() < 2)
1800 return;
1801
1802 // Sanity: does the search string parameter match the return type?
1803 const Expr *SearchStrPtr = CE->getArg(0);
1804 QualType CharPtrTy = SearchStrPtr->getType()->getPointeeType();
1805 if (CharPtrTy.isNull() ||
1806 CE->getType().getUnqualifiedType() != CharPtrTy.getUnqualifiedType())
1807 return;
1808
1809 CurrentFunctionDescription = "strsep()";
1810 ProgramStateRef State = C.getState();
1811 const LocationContext *LCtx = C.getLocationContext();
1812
1813 // Check that the search string pointer is non-null (though it may point to
1814 // a null string).
1815 SVal SearchStrVal = State->getSVal(SearchStrPtr, LCtx);
1816 State = checkNonNull(C, State, SearchStrPtr, SearchStrVal);
1817 if (!State)
1818 return;
1819
1820 // Check that the delimiter string is non-null.
1821 const Expr *DelimStr = CE->getArg(1);
1822 SVal DelimStrVal = State->getSVal(DelimStr, LCtx);
1823 State = checkNonNull(C, State, DelimStr, DelimStrVal);
1824 if (!State)
1825 return;
1826
1827 SValBuilder &SVB = C.getSValBuilder();
1828 SVal Result;
1829 if (Optional<Loc> SearchStrLoc = SearchStrVal.getAs<Loc>()) {
1830 // Get the current value of the search string pointer, as a char*.
1831 Result = State->getSVal(*SearchStrLoc, CharPtrTy);
1832
1833 // Invalidate the search string, representing the change of one delimiter
1834 // character to NUL.
Anton Yartsevb7a747b2013-11-17 09:18:48 +00001835 State = InvalidateBuffer(C, State, SearchStrPtr, Result,
1836 /*IsSourceBuffer*/false);
Jordan Roseaf226212013-04-22 23:18:42 +00001837
1838 // Overwrite the search string pointer. The new value is either an address
1839 // further along in the same string, or NULL if there are no more tokens.
1840 State = State->bindLoc(*SearchStrLoc,
1841 SVB.conjureSymbolVal(getTag(), CE, LCtx, CharPtrTy,
1842 C.blockCount()));
1843 } else {
1844 assert(SearchStrVal.isUnknown());
1845 // Conjure a symbolic value. It's the best we can do.
1846 Result = SVB.conjureSymbolVal(0, CE, LCtx, C.blockCount());
1847 }
1848
1849 // Set the return value, and finish.
1850 State = State->BindExpr(CE, LCtx, Result);
1851 C.addTransition(State);
1852}
1853
1854
Jordy Rosed325ffb2010-07-08 23:57:29 +00001855//===----------------------------------------------------------------------===//
Jordy Rosea5261542010-08-14 21:02:52 +00001856// The driver method, and other Checker callbacks.
Jordy Rosed325ffb2010-07-08 23:57:29 +00001857//===----------------------------------------------------------------------===//
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001858
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001859bool CStringChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
Anna Zaks998e2752012-02-17 22:35:26 +00001860 const FunctionDecl *FDecl = C.getCalleeDecl(CE);
1861
1862 if (!FDecl)
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001863 return false;
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001864
Jordan Roseaf226212013-04-22 23:18:42 +00001865 // FIXME: Poorly-factored string switches are slow.
Anna Zaks998e2752012-02-17 22:35:26 +00001866 FnCheck evalFunction = 0;
1867 if (C.isCLibraryFunction(FDecl, "memcpy"))
1868 evalFunction = &CStringChecker::evalMemcpy;
1869 else if (C.isCLibraryFunction(FDecl, "mempcpy"))
1870 evalFunction = &CStringChecker::evalMempcpy;
1871 else if (C.isCLibraryFunction(FDecl, "memcmp"))
1872 evalFunction = &CStringChecker::evalMemcmp;
1873 else if (C.isCLibraryFunction(FDecl, "memmove"))
1874 evalFunction = &CStringChecker::evalMemmove;
1875 else if (C.isCLibraryFunction(FDecl, "strcpy"))
1876 evalFunction = &CStringChecker::evalStrcpy;
1877 else if (C.isCLibraryFunction(FDecl, "strncpy"))
1878 evalFunction = &CStringChecker::evalStrncpy;
1879 else if (C.isCLibraryFunction(FDecl, "stpcpy"))
1880 evalFunction = &CStringChecker::evalStpcpy;
1881 else if (C.isCLibraryFunction(FDecl, "strcat"))
1882 evalFunction = &CStringChecker::evalStrcat;
1883 else if (C.isCLibraryFunction(FDecl, "strncat"))
1884 evalFunction = &CStringChecker::evalStrncat;
1885 else if (C.isCLibraryFunction(FDecl, "strlen"))
1886 evalFunction = &CStringChecker::evalstrLength;
1887 else if (C.isCLibraryFunction(FDecl, "strnlen"))
1888 evalFunction = &CStringChecker::evalstrnLength;
1889 else if (C.isCLibraryFunction(FDecl, "strcmp"))
1890 evalFunction = &CStringChecker::evalStrcmp;
1891 else if (C.isCLibraryFunction(FDecl, "strncmp"))
1892 evalFunction = &CStringChecker::evalStrncmp;
1893 else if (C.isCLibraryFunction(FDecl, "strcasecmp"))
1894 evalFunction = &CStringChecker::evalStrcasecmp;
1895 else if (C.isCLibraryFunction(FDecl, "strncasecmp"))
1896 evalFunction = &CStringChecker::evalStrncasecmp;
Jordan Roseaf226212013-04-22 23:18:42 +00001897 else if (C.isCLibraryFunction(FDecl, "strsep"))
1898 evalFunction = &CStringChecker::evalStrsep;
Anna Zaks998e2752012-02-17 22:35:26 +00001899 else if (C.isCLibraryFunction(FDecl, "bcopy"))
1900 evalFunction = &CStringChecker::evalBcopy;
1901 else if (C.isCLibraryFunction(FDecl, "bcmp"))
1902 evalFunction = &CStringChecker::evalMemcmp;
1903
Jordy Rosed325ffb2010-07-08 23:57:29 +00001904 // If the callee isn't a string function, let another checker handle it.
Ted Kremenek9c149532010-12-01 21:57:22 +00001905 if (!evalFunction)
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001906 return false;
1907
Jordy Rose9e49d9f2011-06-20 02:06:40 +00001908 // Make sure each function sets its own description.
1909 // (But don't bother in a release build.)
1910 assert(!(CurrentFunctionDescription = NULL));
1911
Jordy Rosed325ffb2010-07-08 23:57:29 +00001912 // Check and evaluate the call.
Ted Kremenek9c149532010-12-01 21:57:22 +00001913 (this->*evalFunction)(C, CE);
Anna Zaks57300762012-02-07 00:56:14 +00001914
1915 // If the evaluate call resulted in no change, chain to the next eval call
1916 // handler.
1917 // Note, the custom CString evaluation calls assume that basic safety
1918 // properties are held. However, if the user chooses to turn off some of these
1919 // checks, we ignore the issues and leave the call evaluation to a generic
1920 // handler.
1921 if (!C.isDifferent())
1922 return false;
1923
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001924 return true;
1925}
Jordy Rosea5261542010-08-14 21:02:52 +00001926
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001927void CStringChecker::checkPreStmt(const DeclStmt *DS, CheckerContext &C) const {
Jordy Rosea5261542010-08-14 21:02:52 +00001928 // Record string length for char a[] = "abc";
Ted Kremenek8bef8232012-01-26 21:29:00 +00001929 ProgramStateRef state = C.getState();
Jordy Rosea5261542010-08-14 21:02:52 +00001930
1931 for (DeclStmt::const_decl_iterator I = DS->decl_begin(), E = DS->decl_end();
1932 I != E; ++I) {
1933 const VarDecl *D = dyn_cast<VarDecl>(*I);
1934 if (!D)
1935 continue;
1936
1937 // FIXME: Handle array fields of structs.
1938 if (!D->getType()->isArrayType())
1939 continue;
1940
1941 const Expr *Init = D->getInit();
1942 if (!Init)
1943 continue;
1944 if (!isa<StringLiteral>(Init))
1945 continue;
1946
Anna Zaks39ac1872011-10-26 21:06:44 +00001947 Loc VarLoc = state->getLValue(D, C.getLocationContext());
Jordy Rosea5261542010-08-14 21:02:52 +00001948 const MemRegion *MR = VarLoc.getAsRegion();
1949 if (!MR)
1950 continue;
1951
Ted Kremenek5eca4822012-01-06 22:09:28 +00001952 SVal StrVal = state->getSVal(Init, C.getLocationContext());
Jordy Rosea5261542010-08-14 21:02:52 +00001953 assert(StrVal.isValid() && "Initializer string is unknown or undefined");
David Blaikie5251abe2013-02-20 05:52:05 +00001954 DefinedOrUnknownSVal strLength =
1955 getCStringLength(C, state, Init, StrVal).castAs<DefinedOrUnknownSVal>();
Jordy Rosea5261542010-08-14 21:02:52 +00001956
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001957 state = state->set<CStringLength>(MR, strLength);
Jordy Rosea5261542010-08-14 21:02:52 +00001958 }
1959
Anna Zaks0bd6b112011-10-26 21:06:34 +00001960 C.addTransition(state);
Jordy Rosea5261542010-08-14 21:02:52 +00001961}
1962
Ted Kremenek8bef8232012-01-26 21:29:00 +00001963bool CStringChecker::wantsRegionChangeUpdate(ProgramStateRef state) const {
Jordan Rose166d5022012-11-02 01:54:06 +00001964 CStringLengthTy Entries = state->get<CStringLength>();
Jordy Rosea5261542010-08-14 21:02:52 +00001965 return !Entries.isEmpty();
1966}
1967
Ted Kremenek8bef8232012-01-26 21:29:00 +00001968ProgramStateRef
1969CStringChecker::checkRegionChanges(ProgramStateRef state,
Anna Zaksbf53dfa2012-12-20 00:38:25 +00001970 const InvalidatedSymbols *,
Jordy Rose537716a2011-08-27 22:51:26 +00001971 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00001972 ArrayRef<const MemRegion *> Regions,
Jordan Rose740d4902012-07-02 19:27:35 +00001973 const CallEvent *Call) const {
Jordan Rose166d5022012-11-02 01:54:06 +00001974 CStringLengthTy Entries = state->get<CStringLength>();
Jordy Rosea5261542010-08-14 21:02:52 +00001975 if (Entries.isEmpty())
1976 return state;
1977
1978 llvm::SmallPtrSet<const MemRegion *, 8> Invalidated;
1979 llvm::SmallPtrSet<const MemRegion *, 32> SuperRegions;
1980
1981 // First build sets for the changed regions and their super-regions.
Jordy Rose537716a2011-08-27 22:51:26 +00001982 for (ArrayRef<const MemRegion *>::iterator
1983 I = Regions.begin(), E = Regions.end(); I != E; ++I) {
1984 const MemRegion *MR = *I;
Jordy Rosea5261542010-08-14 21:02:52 +00001985 Invalidated.insert(MR);
1986
1987 SuperRegions.insert(MR);
1988 while (const SubRegion *SR = dyn_cast<SubRegion>(MR)) {
1989 MR = SR->getSuperRegion();
1990 SuperRegions.insert(MR);
1991 }
1992 }
1993
Jordan Rose166d5022012-11-02 01:54:06 +00001994 CStringLengthTy::Factory &F = state->get_context<CStringLength>();
Jordy Rosea5261542010-08-14 21:02:52 +00001995
1996 // Then loop over the entries in the current state.
Jordan Rose166d5022012-11-02 01:54:06 +00001997 for (CStringLengthTy::iterator I = Entries.begin(),
Jordy Rosea5261542010-08-14 21:02:52 +00001998 E = Entries.end(); I != E; ++I) {
1999 const MemRegion *MR = I.getKey();
2000
2001 // Is this entry for a super-region of a changed region?
2002 if (SuperRegions.count(MR)) {
Ted Kremenek3baf6722010-11-24 00:54:37 +00002003 Entries = F.remove(Entries, MR);
Jordy Rosea5261542010-08-14 21:02:52 +00002004 continue;
2005 }
2006
2007 // Is this entry for a sub-region of a changed region?
2008 const MemRegion *Super = MR;
2009 while (const SubRegion *SR = dyn_cast<SubRegion>(Super)) {
2010 Super = SR->getSuperRegion();
2011 if (Invalidated.count(Super)) {
Ted Kremenek3baf6722010-11-24 00:54:37 +00002012 Entries = F.remove(Entries, MR);
Jordy Rosea5261542010-08-14 21:02:52 +00002013 break;
2014 }
2015 }
2016 }
2017
2018 return state->set<CStringLength>(Entries);
2019}
2020
Ted Kremenek8bef8232012-01-26 21:29:00 +00002021void CStringChecker::checkLiveSymbols(ProgramStateRef state,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00002022 SymbolReaper &SR) const {
Jordy Rosea5261542010-08-14 21:02:52 +00002023 // Mark all symbols in our string length map as valid.
Jordan Rose166d5022012-11-02 01:54:06 +00002024 CStringLengthTy Entries = state->get<CStringLength>();
Jordy Rosea5261542010-08-14 21:02:52 +00002025
Jordan Rose166d5022012-11-02 01:54:06 +00002026 for (CStringLengthTy::iterator I = Entries.begin(), E = Entries.end();
Jordy Rosea5261542010-08-14 21:02:52 +00002027 I != E; ++I) {
2028 SVal Len = I.getData();
Jordy Rosed5af0e12011-06-15 05:52:56 +00002029
Anna Zaks1d1d5152011-12-06 23:12:33 +00002030 for (SymExpr::symbol_iterator si = Len.symbol_begin(),
2031 se = Len.symbol_end(); si != se; ++si)
Jordy Rosed5af0e12011-06-15 05:52:56 +00002032 SR.markInUse(*si);
Jordy Rosea5261542010-08-14 21:02:52 +00002033 }
2034}
2035
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00002036void CStringChecker::checkDeadSymbols(SymbolReaper &SR,
2037 CheckerContext &C) const {
Jordy Rosea5261542010-08-14 21:02:52 +00002038 if (!SR.hasDeadSymbols())
2039 return;
2040
Ted Kremenek8bef8232012-01-26 21:29:00 +00002041 ProgramStateRef state = C.getState();
Jordan Rose166d5022012-11-02 01:54:06 +00002042 CStringLengthTy Entries = state->get<CStringLength>();
Jordy Rosea5261542010-08-14 21:02:52 +00002043 if (Entries.isEmpty())
2044 return;
2045
Jordan Rose166d5022012-11-02 01:54:06 +00002046 CStringLengthTy::Factory &F = state->get_context<CStringLength>();
2047 for (CStringLengthTy::iterator I = Entries.begin(), E = Entries.end();
Jordy Rosea5261542010-08-14 21:02:52 +00002048 I != E; ++I) {
2049 SVal Len = I.getData();
2050 if (SymbolRef Sym = Len.getAsSymbol()) {
2051 if (SR.isDead(Sym))
Ted Kremenek3baf6722010-11-24 00:54:37 +00002052 Entries = F.remove(Entries, I.getKey());
Jordy Rosea5261542010-08-14 21:02:52 +00002053 }
2054 }
2055
2056 state = state->set<CStringLength>(Entries);
Anna Zaks0bd6b112011-10-26 21:06:34 +00002057 C.addTransition(state);
Jordy Rosea5261542010-08-14 21:02:52 +00002058}
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00002059
Anna Zaks57300762012-02-07 00:56:14 +00002060#define REGISTER_CHECKER(name) \
2061void ento::register##name(CheckerManager &mgr) {\
Pavel Labath3b8f77d2013-06-12 07:45:04 +00002062 mgr.registerChecker<CStringChecker>()->Filter.Check##name = true; \
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00002063}
Anna Zaks57300762012-02-07 00:56:14 +00002064
2065REGISTER_CHECKER(CStringNullArg)
2066REGISTER_CHECKER(CStringOutOfBounds)
2067REGISTER_CHECKER(CStringBufferOverlap)
2068REGISTER_CHECKER(CStringNotNullTerm)
Anna Zaksf0dfc9c2012-02-17 22:35:31 +00002069
2070void ento::registerCStringCheckerBasic(CheckerManager &Mgr) {
2071 registerCStringNullArg(Mgr);
2072}