blob: e642c2974ea1153bd3f76321de8b63b374cafbc9 [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,
144 ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000145 const Expr *Ex, SVal V);
Jordy Rosee64f3112010-08-16 07:51:42 +0000146
Ted Kremenek9c378f72011-08-12 23:37:29 +0000147 static bool SummarizeRegion(raw_ostream &os, ASTContext &Ctx,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000148 const MemRegion *MR);
Jordy Rose19c5dd12010-07-27 01:37:31 +0000149
150 // Re-usable checks
Ted Kremenek8bef8232012-01-26 21:29:00 +0000151 ProgramStateRef checkNonNull(CheckerContext &C,
152 ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000153 const Expr *S,
154 SVal l) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000155 ProgramStateRef CheckLocation(CheckerContext &C,
156 ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000157 const Expr *S,
158 SVal l,
159 const char *message = NULL) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000160 ProgramStateRef CheckBufferAccess(CheckerContext &C,
161 ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000162 const Expr *Size,
163 const Expr *FirstBuf,
164 const Expr *SecondBuf,
165 const char *firstMessage = NULL,
166 const char *secondMessage = NULL,
167 bool WarnAboutSize = false) const;
168
Ted Kremenek8bef8232012-01-26 21:29:00 +0000169 ProgramStateRef CheckBufferAccess(CheckerContext &C,
170 ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000171 const Expr *Size,
172 const Expr *Buf,
173 const char *message = NULL,
174 bool WarnAboutSize = false) const {
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000175 // This is a convenience override.
Jordy Rose5e5f1502011-06-20 03:49:16 +0000176 return CheckBufferAccess(C, state, Size, Buf, NULL, message, NULL,
177 WarnAboutSize);
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000178 }
Ted Kremenek8bef8232012-01-26 21:29:00 +0000179 ProgramStateRef CheckOverlap(CheckerContext &C,
180 ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000181 const Expr *Size,
182 const Expr *First,
183 const Expr *Second) const;
184 void emitOverlapBug(CheckerContext &C,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000185 ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000186 const Stmt *First,
187 const Stmt *Second) const;
188
Ted Kremenek8bef8232012-01-26 21:29:00 +0000189 ProgramStateRef checkAdditionOverflow(CheckerContext &C,
190 ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000191 NonLoc left,
192 NonLoc right) const;
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000193};
Jordy Rosea5261542010-08-14 21:02:52 +0000194
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000195} //end anonymous namespace
196
Jordan Rose166d5022012-11-02 01:54:06 +0000197REGISTER_MAP_WITH_PROGRAMSTATE(CStringLength, const MemRegion *, SVal)
Jordy Rosea5261542010-08-14 21:02:52 +0000198
Jordy Rosed325ffb2010-07-08 23:57:29 +0000199//===----------------------------------------------------------------------===//
200// Individual checks and utility methods.
201//===----------------------------------------------------------------------===//
202
Ted Kremenek8bef8232012-01-26 21:29:00 +0000203std::pair<ProgramStateRef , ProgramStateRef >
204CStringChecker::assumeZero(CheckerContext &C, ProgramStateRef state, SVal V,
Jordy Rosed325ffb2010-07-08 23:57:29 +0000205 QualType Ty) {
David Blaikiedc84cd52013-02-20 22:23:23 +0000206 Optional<DefinedSVal> val = V.getAs<DefinedSVal>();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000207 if (!val)
Ted Kremenek8bef8232012-01-26 21:29:00 +0000208 return std::pair<ProgramStateRef , ProgramStateRef >(state, state);
Jordy Rosea6b808c2010-07-07 07:48:06 +0000209
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000210 SValBuilder &svalBuilder = C.getSValBuilder();
211 DefinedOrUnknownSVal zero = svalBuilder.makeZeroVal(Ty);
212 return state->assume(svalBuilder.evalEQ(state, *val, zero));
Jordy Rosed325ffb2010-07-08 23:57:29 +0000213}
Jordy Rosea6b808c2010-07-07 07:48:06 +0000214
Ted Kremenek8bef8232012-01-26 21:29:00 +0000215ProgramStateRef CStringChecker::checkNonNull(CheckerContext &C,
216 ProgramStateRef state,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000217 const Expr *S, SVal l) const {
Jordy Rosed325ffb2010-07-08 23:57:29 +0000218 // If a previous check has failed, propagate the failure.
219 if (!state)
220 return NULL;
221
Ted Kremenek8bef8232012-01-26 21:29:00 +0000222 ProgramStateRef stateNull, stateNonNull;
Ted Kremenek28f47b92010-12-01 22:16:56 +0000223 llvm::tie(stateNull, stateNonNull) = assumeZero(C, state, l, S->getType());
Jordy Rosed325ffb2010-07-08 23:57:29 +0000224
225 if (stateNull && !stateNonNull) {
Anna Zaks57300762012-02-07 00:56:14 +0000226 if (!Filter.CheckCStringNullArg)
227 return NULL;
228
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000229 ExplodedNode *N = C.generateSink(stateNull);
Jordy Rosea6b808c2010-07-07 07:48:06 +0000230 if (!N)
231 return NULL;
232
Jordy Rosed325ffb2010-07-08 23:57:29 +0000233 if (!BT_Null)
Jordan Roseedcc1992013-10-04 00:25:24 +0000234 BT_Null.reset(new BuiltinBug(categories::UnixAPI,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000235 "Null pointer argument in call to byte string function"));
Jordy Rosea6b808c2010-07-07 07:48:06 +0000236
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000237 SmallString<80> buf;
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000238 llvm::raw_svector_ostream os(buf);
239 assert(CurrentFunctionDescription);
240 os << "Null pointer argument in call to " << CurrentFunctionDescription;
241
Jordy Rosea6b808c2010-07-07 07:48:06 +0000242 // Generate a report for this bug.
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000243 BuiltinBug *BT = static_cast<BuiltinBug*>(BT_Null.get());
Anna Zakse172e8b2011-08-17 23:00:25 +0000244 BugReport *report = new BugReport(*BT, os.str(), N);
Jordy Rosea6b808c2010-07-07 07:48:06 +0000245
246 report->addRange(S->getSourceRange());
Jordan Rosea1f81bb2012-08-28 00:50:51 +0000247 bugreporter::trackNullOrUndefValue(N, S, *report);
Jordan Rose785950e2012-11-02 01:53:40 +0000248 C.emitReport(report);
Jordy Rosea6b808c2010-07-07 07:48:06 +0000249 return NULL;
250 }
251
252 // From here on, assume that the value is non-null.
Jordy Rosed325ffb2010-07-08 23:57:29 +0000253 assert(stateNonNull);
254 return stateNonNull;
Jordy Rosea6b808c2010-07-07 07:48:06 +0000255}
256
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000257// FIXME: This was originally copied from ArrayBoundChecker.cpp. Refactor?
Ted Kremenek8bef8232012-01-26 21:29:00 +0000258ProgramStateRef CStringChecker::CheckLocation(CheckerContext &C,
259 ProgramStateRef state,
Jordy Rosee64f3112010-08-16 07:51:42 +0000260 const Expr *S, SVal l,
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000261 const char *warningMsg) const {
Jordy Rosed325ffb2010-07-08 23:57:29 +0000262 // If a previous check has failed, propagate the failure.
263 if (!state)
264 return NULL;
265
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000266 // Check for out of bound array element access.
267 const MemRegion *R = l.getAsRegion();
268 if (!R)
269 return state;
270
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000271 const ElementRegion *ER = dyn_cast<ElementRegion>(R);
272 if (!ER)
273 return state;
274
Zhongxing Xu018220c2010-08-11 06:10:55 +0000275 assert(ER->getValueType() == C.getASTContext().CharTy &&
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000276 "CheckLocation should only be called with char* ElementRegions");
277
278 // Get the size of the array.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000279 const SubRegion *superReg = cast<SubRegion>(ER->getSuperRegion());
280 SValBuilder &svalBuilder = C.getSValBuilder();
Jordy Rose1e022412011-06-16 05:51:02 +0000281 SVal Extent =
282 svalBuilder.convertToArrayIndex(superReg->getExtent(svalBuilder));
David Blaikie5251abe2013-02-20 05:52:05 +0000283 DefinedOrUnknownSVal Size = Extent.castAs<DefinedOrUnknownSVal>();
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000284
285 // Get the index of the accessed element.
David Blaikie7a95de62013-02-21 22:23:56 +0000286 DefinedOrUnknownSVal Idx = ER->getIndex().castAs<DefinedOrUnknownSVal>();
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000287
Ted Kremenek8bef8232012-01-26 21:29:00 +0000288 ProgramStateRef StInBound = state->assumeInBound(Idx, Size, true);
289 ProgramStateRef StOutBound = state->assumeInBound(Idx, Size, false);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000290 if (StOutBound && !StInBound) {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000291 ExplodedNode *N = C.generateSink(StOutBound);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000292 if (!N)
293 return NULL;
294
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000295 if (!BT_Bounds) {
296 BT_Bounds.reset(new BuiltinBug("Out-of-bound array access",
297 "Byte string function accesses out-of-bound array element"));
298 }
299 BuiltinBug *BT = static_cast<BuiltinBug*>(BT_Bounds.get());
300
301 // Generate a report for this bug.
Anna Zakse172e8b2011-08-17 23:00:25 +0000302 BugReport *report;
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000303 if (warningMsg) {
Anna Zakse172e8b2011-08-17 23:00:25 +0000304 report = new BugReport(*BT, warningMsg, N);
Jordy Rosee64f3112010-08-16 07:51:42 +0000305 } else {
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000306 assert(CurrentFunctionDescription);
307 assert(CurrentFunctionDescription[0] != '\0');
308
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000309 SmallString<80> buf;
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000310 llvm::raw_svector_ostream os(buf);
Jordan Rose223f0ff2013-02-09 10:09:43 +0000311 os << toUppercase(CurrentFunctionDescription[0])
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000312 << &CurrentFunctionDescription[1]
313 << " accesses out-of-bound array element";
Anna Zakse172e8b2011-08-17 23:00:25 +0000314 report = new BugReport(*BT, os.str(), N);
Jordy Rosee64f3112010-08-16 07:51:42 +0000315 }
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000316
317 // FIXME: It would be nice to eventually make this diagnostic more clear,
318 // e.g., by referencing the original declaration or by saying *why* this
319 // reference is outside the range.
320
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000321 report->addRange(S->getSourceRange());
Jordan Rose785950e2012-11-02 01:53:40 +0000322 C.emitReport(report);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000323 return NULL;
324 }
325
326 // Array bound check succeeded. From this point forward the array bound
327 // should always succeed.
328 return StInBound;
329}
330
Ted Kremenek8bef8232012-01-26 21:29:00 +0000331ProgramStateRef CStringChecker::CheckBufferAccess(CheckerContext &C,
332 ProgramStateRef state,
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000333 const Expr *Size,
334 const Expr *FirstBuf,
Jordy Rosee64f3112010-08-16 07:51:42 +0000335 const Expr *SecondBuf,
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000336 const char *firstMessage,
Jordy Rose5e5f1502011-06-20 03:49:16 +0000337 const char *secondMessage,
338 bool WarnAboutSize) const {
Jordy Rosed325ffb2010-07-08 23:57:29 +0000339 // If a previous check has failed, propagate the failure.
340 if (!state)
341 return NULL;
342
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000343 SValBuilder &svalBuilder = C.getSValBuilder();
Jordy Rose1e022412011-06-16 05:51:02 +0000344 ASTContext &Ctx = svalBuilder.getContext();
Ted Kremenek5eca4822012-01-06 22:09:28 +0000345 const LocationContext *LCtx = C.getLocationContext();
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000346
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000347 QualType sizeTy = Size->getType();
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000348 QualType PtrTy = Ctx.getPointerType(Ctx.CharTy);
349
Jordy Rosea6b808c2010-07-07 07:48:06 +0000350 // Check that the first buffer is non-null.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000351 SVal BufVal = state->getSVal(FirstBuf, LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000352 state = checkNonNull(C, state, FirstBuf, BufVal);
Jordy Rosea6b808c2010-07-07 07:48:06 +0000353 if (!state)
354 return NULL;
355
Anna Zaks57300762012-02-07 00:56:14 +0000356 // If out-of-bounds checking is turned off, skip the rest.
357 if (!Filter.CheckCStringOutOfBounds)
358 return state;
359
Jordy Rosed325ffb2010-07-08 23:57:29 +0000360 // Get the access length and make sure it is known.
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000361 // FIXME: This assumes the caller has already checked that the access length
362 // is positive. And that it's unsigned.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000363 SVal LengthVal = state->getSVal(Size, LCtx);
David Blaikiedc84cd52013-02-20 22:23:23 +0000364 Optional<NonLoc> Length = LengthVal.getAs<NonLoc>();
Jordy Rosed325ffb2010-07-08 23:57:29 +0000365 if (!Length)
366 return state;
367
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000368 // Compute the offset of the last element to be accessed: size-1.
David Blaikie5251abe2013-02-20 05:52:05 +0000369 NonLoc One = svalBuilder.makeIntVal(1, sizeTy).castAs<NonLoc>();
370 NonLoc LastOffset = svalBuilder
371 .evalBinOpNN(state, BO_Sub, *Length, One, sizeTy).castAs<NonLoc>();
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000372
Chris Lattnerfc8f0e12011-04-15 05:22:18 +0000373 // Check that the first buffer is sufficiently long.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000374 SVal BufStart = svalBuilder.evalCast(BufVal, PtrTy, FirstBuf->getType());
David Blaikiedc84cd52013-02-20 22:23:23 +0000375 if (Optional<Loc> BufLoc = BufStart.getAs<Loc>()) {
Jordy Rose5e5f1502011-06-20 03:49:16 +0000376 const Expr *warningExpr = (WarnAboutSize ? Size : FirstBuf);
377
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000378 SVal BufEnd = svalBuilder.evalBinOpLN(state, BO_Add, *BufLoc,
379 LastOffset, PtrTy);
Jordy Rose5e5f1502011-06-20 03:49:16 +0000380 state = CheckLocation(C, state, warningExpr, BufEnd, firstMessage);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000381
Jordy Roseb6a40262010-08-05 23:11:30 +0000382 // If the buffer isn't large enough, abort.
383 if (!state)
384 return NULL;
385 }
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000386
387 // If there's a second buffer, check it as well.
388 if (SecondBuf) {
Ted Kremenek5eca4822012-01-06 22:09:28 +0000389 BufVal = state->getSVal(SecondBuf, LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000390 state = checkNonNull(C, state, SecondBuf, BufVal);
Jordy Rosea6b808c2010-07-07 07:48:06 +0000391 if (!state)
392 return NULL;
393
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000394 BufStart = svalBuilder.evalCast(BufVal, PtrTy, SecondBuf->getType());
David Blaikiedc84cd52013-02-20 22:23:23 +0000395 if (Optional<Loc> BufLoc = BufStart.getAs<Loc>()) {
Jordy Rose5e5f1502011-06-20 03:49:16 +0000396 const Expr *warningExpr = (WarnAboutSize ? Size : SecondBuf);
397
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000398 SVal BufEnd = svalBuilder.evalBinOpLN(state, BO_Add, *BufLoc,
399 LastOffset, PtrTy);
Jordy Rose5e5f1502011-06-20 03:49:16 +0000400 state = CheckLocation(C, state, warningExpr, BufEnd, secondMessage);
Jordy Roseb6a40262010-08-05 23:11:30 +0000401 }
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000402 }
403
404 // Large enough or not, return this state!
405 return state;
406}
407
Ted Kremenek8bef8232012-01-26 21:29:00 +0000408ProgramStateRef CStringChecker::CheckOverlap(CheckerContext &C,
409 ProgramStateRef state,
Jordy Rosed325ffb2010-07-08 23:57:29 +0000410 const Expr *Size,
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000411 const Expr *First,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000412 const Expr *Second) const {
Anna Zaks57300762012-02-07 00:56:14 +0000413 if (!Filter.CheckCStringBufferOverlap)
414 return state;
415
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000416 // Do a simple check for overlap: if the two arguments are from the same
417 // buffer, see if the end of the first is greater than the start of the second
418 // or vice versa.
419
Jordy Rosed325ffb2010-07-08 23:57:29 +0000420 // If a previous check has failed, propagate the failure.
421 if (!state)
422 return NULL;
423
Ted Kremenek8bef8232012-01-26 21:29:00 +0000424 ProgramStateRef stateTrue, stateFalse;
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000425
426 // Get the buffer values and make sure they're known locations.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000427 const LocationContext *LCtx = C.getLocationContext();
428 SVal firstVal = state->getSVal(First, LCtx);
429 SVal secondVal = state->getSVal(Second, LCtx);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000430
David Blaikiedc84cd52013-02-20 22:23:23 +0000431 Optional<Loc> firstLoc = firstVal.getAs<Loc>();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000432 if (!firstLoc)
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000433 return state;
434
David Blaikiedc84cd52013-02-20 22:23:23 +0000435 Optional<Loc> secondLoc = secondVal.getAs<Loc>();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000436 if (!secondLoc)
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000437 return state;
438
439 // Are the two values the same?
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000440 SValBuilder &svalBuilder = C.getSValBuilder();
441 llvm::tie(stateTrue, stateFalse) =
442 state->assume(svalBuilder.evalEQ(state, *firstLoc, *secondLoc));
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000443
444 if (stateTrue && !stateFalse) {
445 // If the values are known to be equal, that's automatically an overlap.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000446 emitOverlapBug(C, stateTrue, First, Second);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000447 return NULL;
448 }
449
Ted Kremenek28f47b92010-12-01 22:16:56 +0000450 // assume the two expressions are not equal.
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000451 assert(stateFalse);
452 state = stateFalse;
453
454 // Which value comes first?
Jordy Roseee2fde12011-06-16 05:56:50 +0000455 QualType cmpTy = svalBuilder.getConditionType();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000456 SVal reverse = svalBuilder.evalBinOpLL(state, BO_GT,
457 *firstLoc, *secondLoc, cmpTy);
David Blaikiedc84cd52013-02-20 22:23:23 +0000458 Optional<DefinedOrUnknownSVal> reverseTest =
David Blaikie5251abe2013-02-20 05:52:05 +0000459 reverse.getAs<DefinedOrUnknownSVal>();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000460 if (!reverseTest)
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000461 return state;
462
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000463 llvm::tie(stateTrue, stateFalse) = state->assume(*reverseTest);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000464 if (stateTrue) {
465 if (stateFalse) {
466 // If we don't know which one comes first, we can't perform this test.
467 return state;
468 } else {
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000469 // Switch the values so that firstVal is before secondVal.
David Blaikie5251abe2013-02-20 05:52:05 +0000470 std::swap(firstLoc, secondLoc);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000471
472 // Switch the Exprs as well, so that they still correspond.
David Blaikie5251abe2013-02-20 05:52:05 +0000473 std::swap(First, Second);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000474 }
475 }
476
477 // Get the length, and make sure it too is known.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000478 SVal LengthVal = state->getSVal(Size, LCtx);
David Blaikiedc84cd52013-02-20 22:23:23 +0000479 Optional<NonLoc> Length = LengthVal.getAs<NonLoc>();
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000480 if (!Length)
481 return state;
482
483 // Convert the first buffer's start address to char*.
484 // Bail out if the cast fails.
Jordy Roseee2fde12011-06-16 05:56:50 +0000485 ASTContext &Ctx = svalBuilder.getContext();
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000486 QualType CharPtrTy = Ctx.getPointerType(Ctx.CharTy);
Jordy Rose1e022412011-06-16 05:51:02 +0000487 SVal FirstStart = svalBuilder.evalCast(*firstLoc, CharPtrTy,
488 First->getType());
David Blaikiedc84cd52013-02-20 22:23:23 +0000489 Optional<Loc> FirstStartLoc = FirstStart.getAs<Loc>();
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000490 if (!FirstStartLoc)
491 return state;
492
493 // Compute the end of the first buffer. Bail out if THAT fails.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000494 SVal FirstEnd = svalBuilder.evalBinOpLN(state, BO_Add,
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000495 *FirstStartLoc, *Length, CharPtrTy);
David Blaikiedc84cd52013-02-20 22:23:23 +0000496 Optional<Loc> FirstEndLoc = FirstEnd.getAs<Loc>();
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000497 if (!FirstEndLoc)
498 return state;
499
500 // Is the end of the first buffer past the start of the second buffer?
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000501 SVal Overlap = svalBuilder.evalBinOpLL(state, BO_GT,
502 *FirstEndLoc, *secondLoc, cmpTy);
David Blaikiedc84cd52013-02-20 22:23:23 +0000503 Optional<DefinedOrUnknownSVal> OverlapTest =
David Blaikie5251abe2013-02-20 05:52:05 +0000504 Overlap.getAs<DefinedOrUnknownSVal>();
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000505 if (!OverlapTest)
506 return state;
507
Ted Kremenek28f47b92010-12-01 22:16:56 +0000508 llvm::tie(stateTrue, stateFalse) = state->assume(*OverlapTest);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000509
510 if (stateTrue && !stateFalse) {
511 // Overlap!
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000512 emitOverlapBug(C, stateTrue, First, Second);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000513 return NULL;
514 }
515
Ted Kremenek28f47b92010-12-01 22:16:56 +0000516 // assume the two expressions don't overlap.
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000517 assert(stateFalse);
518 return stateFalse;
519}
520
Ted Kremenek8bef8232012-01-26 21:29:00 +0000521void CStringChecker::emitOverlapBug(CheckerContext &C, ProgramStateRef state,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000522 const Stmt *First, const Stmt *Second) const {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000523 ExplodedNode *N = C.generateSink(state);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000524 if (!N)
525 return;
526
527 if (!BT_Overlap)
Jordan Roseedcc1992013-10-04 00:25:24 +0000528 BT_Overlap.reset(new BugType(categories::UnixAPI, "Improper arguments"));
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000529
530 // Generate a report for this bug.
Anna Zakse172e8b2011-08-17 23:00:25 +0000531 BugReport *report =
532 new BugReport(*BT_Overlap,
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000533 "Arguments must not be overlapping buffers", N);
534 report->addRange(First->getSourceRange());
535 report->addRange(Second->getSourceRange());
536
Jordan Rose785950e2012-11-02 01:53:40 +0000537 C.emitReport(report);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000538}
539
Ted Kremenek8bef8232012-01-26 21:29:00 +0000540ProgramStateRef CStringChecker::checkAdditionOverflow(CheckerContext &C,
541 ProgramStateRef state,
Jordy Rosed5af0e12011-06-15 05:52:56 +0000542 NonLoc left,
543 NonLoc right) const {
Anna Zaks57300762012-02-07 00:56:14 +0000544 // If out-of-bounds checking is turned off, skip the rest.
545 if (!Filter.CheckCStringOutOfBounds)
546 return state;
547
Jordy Rosed5af0e12011-06-15 05:52:56 +0000548 // If a previous check has failed, propagate the failure.
549 if (!state)
550 return NULL;
551
552 SValBuilder &svalBuilder = C.getSValBuilder();
553 BasicValueFactory &BVF = svalBuilder.getBasicValueFactory();
554
555 QualType sizeTy = svalBuilder.getContext().getSizeType();
556 const llvm::APSInt &maxValInt = BVF.getMaxValue(sizeTy);
557 NonLoc maxVal = svalBuilder.makeIntVal(maxValInt);
558
Anna Zakse3d250e2011-12-11 18:43:40 +0000559 SVal maxMinusRight;
David Blaikie5251abe2013-02-20 05:52:05 +0000560 if (right.getAs<nonloc::ConcreteInt>()) {
Anna Zakse3d250e2011-12-11 18:43:40 +0000561 maxMinusRight = svalBuilder.evalBinOpNN(state, BO_Sub, maxVal, right,
562 sizeTy);
563 } else {
Jordy Rosed5af0e12011-06-15 05:52:56 +0000564 // Try switching the operands. (The order of these two assignments is
565 // important!)
566 maxMinusRight = svalBuilder.evalBinOpNN(state, BO_Sub, maxVal, left,
567 sizeTy);
568 left = right;
569 }
570
David Blaikiedc84cd52013-02-20 22:23:23 +0000571 if (Optional<NonLoc> maxMinusRightNL = maxMinusRight.getAs<NonLoc>()) {
Jordy Rosed5af0e12011-06-15 05:52:56 +0000572 QualType cmpTy = svalBuilder.getConditionType();
573 // If left > max - right, we have an overflow.
574 SVal willOverflow = svalBuilder.evalBinOpNN(state, BO_GT, left,
575 *maxMinusRightNL, cmpTy);
576
Ted Kremenek8bef8232012-01-26 21:29:00 +0000577 ProgramStateRef stateOverflow, stateOkay;
Jordy Rosed5af0e12011-06-15 05:52:56 +0000578 llvm::tie(stateOverflow, stateOkay) =
David Blaikie5251abe2013-02-20 05:52:05 +0000579 state->assume(willOverflow.castAs<DefinedOrUnknownSVal>());
Jordy Rosed5af0e12011-06-15 05:52:56 +0000580
581 if (stateOverflow && !stateOkay) {
582 // We have an overflow. Emit a bug report.
583 ExplodedNode *N = C.generateSink(stateOverflow);
584 if (!N)
585 return NULL;
586
587 if (!BT_AdditionOverflow)
588 BT_AdditionOverflow.reset(new BuiltinBug("API",
589 "Sum of expressions causes overflow"));
590
Jordy Rosed5af0e12011-06-15 05:52:56 +0000591 // This isn't a great error message, but this should never occur in real
592 // code anyway -- you'd have to create a buffer longer than a size_t can
593 // represent, which is sort of a contradiction.
Jordy Rose8cc24912011-06-20 03:51:53 +0000594 const char *warning =
595 "This expression will create a string whose length is too big to "
596 "be represented as a size_t";
Jordy Rosed5af0e12011-06-15 05:52:56 +0000597
598 // Generate a report for this bug.
Jordy Rose8cc24912011-06-20 03:51:53 +0000599 BugReport *report = new BugReport(*BT_AdditionOverflow, warning, N);
Jordan Rose785950e2012-11-02 01:53:40 +0000600 C.emitReport(report);
Jordy Rosed5af0e12011-06-15 05:52:56 +0000601
602 return NULL;
603 }
604
605 // From now on, assume an overflow didn't occur.
606 assert(stateOkay);
607 state = stateOkay;
608 }
609
610 return state;
611}
612
Ted Kremenek8bef8232012-01-26 21:29:00 +0000613ProgramStateRef CStringChecker::setCStringLength(ProgramStateRef state,
Jordy Rosee64f3112010-08-16 07:51:42 +0000614 const MemRegion *MR,
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000615 SVal strLength) {
616 assert(!strLength.isUndef() && "Attempt to set an undefined string length");
Jordy Rosee64f3112010-08-16 07:51:42 +0000617
618 MR = MR->StripCasts();
619
620 switch (MR->getKind()) {
621 case MemRegion::StringRegionKind:
622 // FIXME: This can happen if we strcpy() into a string region. This is
623 // undefined [C99 6.4.5p6], but we should still warn about it.
624 return state;
625
626 case MemRegion::SymbolicRegionKind:
627 case MemRegion::AllocaRegionKind:
628 case MemRegion::VarRegionKind:
629 case MemRegion::FieldRegionKind:
630 case MemRegion::ObjCIvarRegionKind:
Jordy Rose210c05b2011-06-15 05:14:03 +0000631 // These are the types we can currently track string lengths for.
632 break;
Jordy Rosee64f3112010-08-16 07:51:42 +0000633
634 case MemRegion::ElementRegionKind:
635 // FIXME: Handle element regions by upper-bounding the parent region's
636 // string length.
637 return state;
638
639 default:
640 // Other regions (mostly non-data) can't have a reliable C string length.
641 // For now, just ignore the change.
642 // FIXME: These are rare but not impossible. We should output some kind of
643 // warning for things like strcpy((char[]){'a', 0}, "b");
644 return state;
645 }
Jordy Rose210c05b2011-06-15 05:14:03 +0000646
647 if (strLength.isUnknown())
648 return state->remove<CStringLength>(MR);
649
650 return state->set<CStringLength>(MR, strLength);
Jordy Rosee64f3112010-08-16 07:51:42 +0000651}
652
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000653SVal CStringChecker::getCStringLengthForRegion(CheckerContext &C,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000654 ProgramStateRef &state,
Jordy Rosea5261542010-08-14 21:02:52 +0000655 const Expr *Ex,
Jordy Rosed5af0e12011-06-15 05:52:56 +0000656 const MemRegion *MR,
657 bool hypothetical) {
658 if (!hypothetical) {
659 // If there's a recorded length, go ahead and return it.
660 const SVal *Recorded = state->get<CStringLength>(MR);
661 if (Recorded)
662 return *Recorded;
663 }
Jordan Rosea728e922013-08-19 16:27:34 +0000664
Jordy Rosea5261542010-08-14 21:02:52 +0000665 // Otherwise, get a new symbol and update the state.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000666 SValBuilder &svalBuilder = C.getSValBuilder();
667 QualType sizeTy = svalBuilder.getContext().getSizeType();
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000668 SVal strLength = svalBuilder.getMetadataSymbolVal(CStringChecker::getTag(),
Ted Kremenek66c486f2012-08-22 06:26:15 +0000669 MR, Ex, sizeTy,
670 C.blockCount());
Jordy Rosed5af0e12011-06-15 05:52:56 +0000671
Jordan Rosea728e922013-08-19 16:27:34 +0000672 if (!hypothetical) {
673 if (Optional<NonLoc> strLn = strLength.getAs<NonLoc>()) {
674 // In case of unbounded calls strlen etc bound the range to SIZE_MAX/4
675 BasicValueFactory &BVF = svalBuilder.getBasicValueFactory();
676 const llvm::APSInt &maxValInt = BVF.getMaxValue(sizeTy);
677 llvm::APSInt fourInt = APSIntType(maxValInt).getValue(4);
678 const llvm::APSInt *maxLengthInt = BVF.evalAPSInt(BO_Div, maxValInt,
679 fourInt);
680 NonLoc maxLength = svalBuilder.makeIntVal(*maxLengthInt);
681 SVal evalLength = svalBuilder.evalBinOpNN(state, BO_LE, *strLn,
682 maxLength, sizeTy);
683 state = state->assume(evalLength.castAs<DefinedOrUnknownSVal>(), true);
684 }
Jordy Rosed5af0e12011-06-15 05:52:56 +0000685 state = state->set<CStringLength>(MR, strLength);
Jordan Rosea728e922013-08-19 16:27:34 +0000686 }
Jordy Rosed5af0e12011-06-15 05:52:56 +0000687
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000688 return strLength;
Jordy Rosea5261542010-08-14 21:02:52 +0000689}
690
Ted Kremenek8bef8232012-01-26 21:29:00 +0000691SVal CStringChecker::getCStringLength(CheckerContext &C, ProgramStateRef &state,
Jordy Rosed5af0e12011-06-15 05:52:56 +0000692 const Expr *Ex, SVal Buf,
693 bool hypothetical) const {
Jordy Rose19c5dd12010-07-27 01:37:31 +0000694 const MemRegion *MR = Buf.getAsRegion();
695 if (!MR) {
696 // If we can't get a region, see if it's something we /know/ isn't a
697 // C string. In the context of locations, the only time we can issue such
698 // a warning is for labels.
David Blaikiedc84cd52013-02-20 22:23:23 +0000699 if (Optional<loc::GotoLabel> Label = Buf.getAs<loc::GotoLabel>()) {
Anna Zaks57300762012-02-07 00:56:14 +0000700 if (!Filter.CheckCStringNotNullTerm)
701 return UndefinedVal();
702
Anna Zaks0bd6b112011-10-26 21:06:34 +0000703 if (ExplodedNode *N = C.addTransition(state)) {
Jordy Rose19c5dd12010-07-27 01:37:31 +0000704 if (!BT_NotCString)
Jordan Roseedcc1992013-10-04 00:25:24 +0000705 BT_NotCString.reset(new BuiltinBug(categories::UnixAPI,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000706 "Argument is not a null-terminated string."));
Jordy Rose19c5dd12010-07-27 01:37:31 +0000707
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000708 SmallString<120> buf;
Jordy Rose19c5dd12010-07-27 01:37:31 +0000709 llvm::raw_svector_ostream os(buf);
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000710 assert(CurrentFunctionDescription);
711 os << "Argument to " << CurrentFunctionDescription
712 << " is the address of the label '" << Label->getLabel()->getName()
Jordy Rose19c5dd12010-07-27 01:37:31 +0000713 << "', which is not a null-terminated string";
714
715 // Generate a report for this bug.
Anna Zakse172e8b2011-08-17 23:00:25 +0000716 BugReport *report = new BugReport(*BT_NotCString,
Jordy Rose19c5dd12010-07-27 01:37:31 +0000717 os.str(), N);
718
719 report->addRange(Ex->getSourceRange());
Jordan Rose785950e2012-11-02 01:53:40 +0000720 C.emitReport(report);
Jordy Rose19c5dd12010-07-27 01:37:31 +0000721 }
Jordy Rose19c5dd12010-07-27 01:37:31 +0000722 return UndefinedVal();
Anna Zaks57300762012-02-07 00:56:14 +0000723
Jordy Rose19c5dd12010-07-27 01:37:31 +0000724 }
725
Jordy Rosea5261542010-08-14 21:02:52 +0000726 // If it's not a region and not a label, give up.
727 return UnknownVal();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000728 }
729
Jordy Rosea5261542010-08-14 21:02:52 +0000730 // If we have a region, strip casts from it and see if we can figure out
731 // its length. For anything we can't figure out, just return UnknownVal.
732 MR = MR->StripCasts();
733
734 switch (MR->getKind()) {
735 case MemRegion::StringRegionKind: {
736 // Modifying the contents of string regions is undefined [C99 6.4.5p6],
737 // so we can assume that the byte length is the correct C string length.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000738 SValBuilder &svalBuilder = C.getSValBuilder();
739 QualType sizeTy = svalBuilder.getContext().getSizeType();
740 const StringLiteral *strLit = cast<StringRegion>(MR)->getStringLiteral();
741 return svalBuilder.makeIntVal(strLit->getByteLength(), sizeTy);
Jordy Rosea5261542010-08-14 21:02:52 +0000742 }
743 case MemRegion::SymbolicRegionKind:
744 case MemRegion::AllocaRegionKind:
745 case MemRegion::VarRegionKind:
746 case MemRegion::FieldRegionKind:
747 case MemRegion::ObjCIvarRegionKind:
Jordy Rosed5af0e12011-06-15 05:52:56 +0000748 return getCStringLengthForRegion(C, state, Ex, MR, hypothetical);
Jordy Rosea5261542010-08-14 21:02:52 +0000749 case MemRegion::CompoundLiteralRegionKind:
750 // FIXME: Can we track this? Is it necessary?
751 return UnknownVal();
752 case MemRegion::ElementRegionKind:
753 // FIXME: How can we handle this? It's not good enough to subtract the
754 // offset from the base string length; consider "123\x00567" and &a[5].
755 return UnknownVal();
756 default:
757 // Other regions (mostly non-data) can't have a reliable C string length.
758 // In this case, an error is emitted and UndefinedVal is returned.
759 // The caller should always be prepared to handle this case.
Anna Zaks57300762012-02-07 00:56:14 +0000760 if (!Filter.CheckCStringNotNullTerm)
761 return UndefinedVal();
762
Anna Zaks0bd6b112011-10-26 21:06:34 +0000763 if (ExplodedNode *N = C.addTransition(state)) {
Jordy Rosea5261542010-08-14 21:02:52 +0000764 if (!BT_NotCString)
Jordan Roseedcc1992013-10-04 00:25:24 +0000765 BT_NotCString.reset(new BuiltinBug(categories::UnixAPI,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000766 "Argument is not a null-terminated string."));
Jordy Rosea5261542010-08-14 21:02:52 +0000767
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000768 SmallString<120> buf;
Jordy Rosea5261542010-08-14 21:02:52 +0000769 llvm::raw_svector_ostream os(buf);
770
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000771 assert(CurrentFunctionDescription);
772 os << "Argument to " << CurrentFunctionDescription << " is ";
Jordy Rosea5261542010-08-14 21:02:52 +0000773
774 if (SummarizeRegion(os, C.getASTContext(), MR))
775 os << ", which is not a null-terminated string";
776 else
777 os << "not a null-terminated string";
778
779 // Generate a report for this bug.
Anna Zakse172e8b2011-08-17 23:00:25 +0000780 BugReport *report = new BugReport(*BT_NotCString,
Jordy Rosea5261542010-08-14 21:02:52 +0000781 os.str(), N);
782
783 report->addRange(Ex->getSourceRange());
Jordan Rose785950e2012-11-02 01:53:40 +0000784 C.emitReport(report);
Jordy Rosea5261542010-08-14 21:02:52 +0000785 }
786
787 return UndefinedVal();
788 }
Jordy Rose19c5dd12010-07-27 01:37:31 +0000789}
790
Lenny Maiorani318dd922011-04-12 17:08:43 +0000791const StringLiteral *CStringChecker::getCStringLiteral(CheckerContext &C,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000792 ProgramStateRef &state, const Expr *expr, SVal val) const {
Lenny Maiorani318dd922011-04-12 17:08:43 +0000793
794 // Get the memory region pointed to by the val.
795 const MemRegion *bufRegion = val.getAsRegion();
796 if (!bufRegion)
797 return NULL;
798
799 // Strip casts off the memory region.
800 bufRegion = bufRegion->StripCasts();
801
802 // Cast the memory region to a string region.
803 const StringRegion *strRegion= dyn_cast<StringRegion>(bufRegion);
804 if (!strRegion)
805 return NULL;
806
807 // Return the actual string in the string region.
808 return strRegion->getStringLiteral();
809}
810
Ted Kremenek8bef8232012-01-26 21:29:00 +0000811ProgramStateRef CStringChecker::InvalidateBuffer(CheckerContext &C,
812 ProgramStateRef state,
Jordy Rosee64f3112010-08-16 07:51:42 +0000813 const Expr *E, SVal V) {
David Blaikiedc84cd52013-02-20 22:23:23 +0000814 Optional<Loc> L = V.getAs<Loc>();
Jordy Rosee64f3112010-08-16 07:51:42 +0000815 if (!L)
816 return state;
817
818 // FIXME: This is a simplified version of what's in CFRefCount.cpp -- it makes
819 // some assumptions about the value that CFRefCount can't. Even so, it should
820 // probably be refactored.
David Blaikiedc84cd52013-02-20 22:23:23 +0000821 if (Optional<loc::MemRegionVal> MR = L->getAs<loc::MemRegionVal>()) {
Jordy Rosee64f3112010-08-16 07:51:42 +0000822 const MemRegion *R = MR->getRegion()->StripCasts();
823
824 // Are we dealing with an ElementRegion? If so, we should be invalidating
825 // the super-region.
826 if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
827 R = ER->getSuperRegion();
828 // FIXME: What about layers of ElementRegions?
829 }
830
831 // Invalidate this region.
Ted Kremenek3133f792012-02-17 23:13:45 +0000832 const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
Anna Zaksbf53dfa2012-12-20 00:38:25 +0000833 return state->invalidateRegions(R, E, C.blockCount(), LCtx,
Anna Zaks64eb0702013-01-16 01:35:54 +0000834 /*CausesPointerEscape*/ false);
Jordy Rosee64f3112010-08-16 07:51:42 +0000835 }
836
837 // If we have a non-region value by chance, just remove the binding.
838 // FIXME: is this necessary or correct? This handles the non-Region
839 // cases. Is it ever valid to store to these?
Ted Kremenek56a46b52012-08-22 06:37:46 +0000840 return state->killBinding(*L);
Jordy Rosee64f3112010-08-16 07:51:42 +0000841}
842
Ted Kremenek9c378f72011-08-12 23:37:29 +0000843bool CStringChecker::SummarizeRegion(raw_ostream &os, ASTContext &Ctx,
Jordy Rose19c5dd12010-07-27 01:37:31 +0000844 const MemRegion *MR) {
Ted Kremenek96979342011-08-12 20:02:48 +0000845 const TypedValueRegion *TVR = dyn_cast<TypedValueRegion>(MR);
Jordy Rose19c5dd12010-07-27 01:37:31 +0000846
Jordy Rose096aef92011-08-12 21:41:07 +0000847 switch (MR->getKind()) {
Jordy Rose19c5dd12010-07-27 01:37:31 +0000848 case MemRegion::FunctionTextRegionKind: {
Anna Zaks5fc1d0c2012-09-17 19:13:56 +0000849 const NamedDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000850 if (FD)
Benjamin Kramerb8989f22011-10-14 18:45:37 +0000851 os << "the address of the function '" << *FD << '\'';
Jordy Rose19c5dd12010-07-27 01:37:31 +0000852 else
853 os << "the address of a function";
854 return true;
855 }
856 case MemRegion::BlockTextRegionKind:
857 os << "block text";
858 return true;
859 case MemRegion::BlockDataRegionKind:
860 os << "a block";
861 return true;
862 case MemRegion::CXXThisRegionKind:
Zhongxing Xu02fe28c2010-11-26 08:52:48 +0000863 case MemRegion::CXXTempObjectRegionKind:
Ted Kremenek96979342011-08-12 20:02:48 +0000864 os << "a C++ temp object of type " << TVR->getValueType().getAsString();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000865 return true;
866 case MemRegion::VarRegionKind:
Ted Kremenek96979342011-08-12 20:02:48 +0000867 os << "a variable of type" << TVR->getValueType().getAsString();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000868 return true;
869 case MemRegion::FieldRegionKind:
Ted Kremenek96979342011-08-12 20:02:48 +0000870 os << "a field of type " << TVR->getValueType().getAsString();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000871 return true;
872 case MemRegion::ObjCIvarRegionKind:
Ted Kremenek96979342011-08-12 20:02:48 +0000873 os << "an instance variable of type " << TVR->getValueType().getAsString();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000874 return true;
875 default:
876 return false;
877 }
878}
879
Jordy Rosed325ffb2010-07-08 23:57:29 +0000880//===----------------------------------------------------------------------===//
Ted Kremenek9c149532010-12-01 21:57:22 +0000881// evaluation of individual function calls.
Jordy Rosed325ffb2010-07-08 23:57:29 +0000882//===----------------------------------------------------------------------===//
883
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000884void CStringChecker::evalCopyCommon(CheckerContext &C,
885 const CallExpr *CE,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000886 ProgramStateRef state,
Jordy Rosed325ffb2010-07-08 23:57:29 +0000887 const Expr *Size, const Expr *Dest,
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000888 const Expr *Source, bool Restricted,
889 bool IsMempcpy) const {
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000890 CurrentFunctionDescription = "memory copy function";
891
Jordy Rosed325ffb2010-07-08 23:57:29 +0000892 // See if the size argument is zero.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000893 const LocationContext *LCtx = C.getLocationContext();
894 SVal sizeVal = state->getSVal(Size, LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000895 QualType sizeTy = Size->getType();
Jordy Rosed325ffb2010-07-08 23:57:29 +0000896
Ted Kremenek8bef8232012-01-26 21:29:00 +0000897 ProgramStateRef stateZeroSize, stateNonZeroSize;
Jordy Rose1e022412011-06-16 05:51:02 +0000898 llvm::tie(stateZeroSize, stateNonZeroSize) =
899 assumeZero(C, state, sizeVal, sizeTy);
Jordy Rosed325ffb2010-07-08 23:57:29 +0000900
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000901 // Get the value of the Dest.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000902 SVal destVal = state->getSVal(Dest, LCtx);
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000903
904 // If the size is zero, there won't be any actual memory access, so
905 // just bind the return value to the destination buffer and return.
Anna Zaksdd160f32012-05-03 18:21:28 +0000906 if (stateZeroSize && !stateNonZeroSize) {
Ted Kremenek5eca4822012-01-06 22:09:28 +0000907 stateZeroSize = stateZeroSize->BindExpr(CE, LCtx, destVal);
Anna Zaks0bd6b112011-10-26 21:06:34 +0000908 C.addTransition(stateZeroSize);
Anna Zaksdd160f32012-05-03 18:21:28 +0000909 return;
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000910 }
Jordy Rosed325ffb2010-07-08 23:57:29 +0000911
912 // If the size can be nonzero, we have to check the other arguments.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000913 if (stateNonZeroSize) {
Jordy Rose22d27172011-06-04 00:04:22 +0000914 state = stateNonZeroSize;
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000915
916 // Ensure the destination is not null. If it is NULL there will be a
917 // NULL pointer dereference.
918 state = checkNonNull(C, state, Dest, destVal);
919 if (!state)
920 return;
921
922 // Get the value of the Src.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000923 SVal srcVal = state->getSVal(Source, LCtx);
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000924
925 // Ensure the source is not null. If it is NULL there will be a
926 // NULL pointer dereference.
927 state = checkNonNull(C, state, Source, srcVal);
928 if (!state)
929 return;
930
Jordy Rose7182b962011-06-04 01:50:25 +0000931 // Ensure the accesses are valid and that the buffers do not overlap.
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000932 const char * const writeWarning =
933 "Memory copy function overflows destination buffer";
Jordy Rosee64f3112010-08-16 07:51:42 +0000934 state = CheckBufferAccess(C, state, Size, Dest, Source,
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000935 writeWarning, /* sourceWarning = */ NULL);
Jordy Rosed325ffb2010-07-08 23:57:29 +0000936 if (Restricted)
937 state = CheckOverlap(C, state, Size, Dest, Source);
Jordy Rosee64f3112010-08-16 07:51:42 +0000938
Jordy Rose7182b962011-06-04 01:50:25 +0000939 if (!state)
940 return;
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000941
Jordy Rose7182b962011-06-04 01:50:25 +0000942 // If this is mempcpy, get the byte after the last byte copied and
943 // bind the expr.
944 if (IsMempcpy) {
David Blaikie5251abe2013-02-20 05:52:05 +0000945 loc::MemRegionVal destRegVal = destVal.castAs<loc::MemRegionVal>();
Jordy Rose7182b962011-06-04 01:50:25 +0000946
947 // Get the length to copy.
David Blaikiedc84cd52013-02-20 22:23:23 +0000948 if (Optional<NonLoc> lenValNonLoc = sizeVal.getAs<NonLoc>()) {
Jordy Rose7182b962011-06-04 01:50:25 +0000949 // Get the byte after the last byte copied.
950 SVal lastElement = C.getSValBuilder().evalBinOpLN(state, BO_Add,
David Blaikie5251abe2013-02-20 05:52:05 +0000951 destRegVal,
Jordy Rose7182b962011-06-04 01:50:25 +0000952 *lenValNonLoc,
953 Dest->getType());
954
955 // The byte after the last byte copied is the return value.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000956 state = state->BindExpr(CE, LCtx, lastElement);
Jordy Rose3f8bb2f2011-06-04 01:47:27 +0000957 } else {
Jordy Rose7182b962011-06-04 01:50:25 +0000958 // If we don't know how much we copied, we can at least
959 // conjure a return value for later.
Ted Kremenek66c486f2012-08-22 06:26:15 +0000960 SVal result = C.getSValBuilder().conjureSymbolVal(0, CE, LCtx,
961 C.blockCount());
Ted Kremenek5eca4822012-01-06 22:09:28 +0000962 state = state->BindExpr(CE, LCtx, result);
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000963 }
964
Jordy Rose7182b962011-06-04 01:50:25 +0000965 } else {
966 // All other copies return the destination buffer.
967 // (Well, bcopy() has a void return type, but this won't hurt.)
Ted Kremenek5eca4822012-01-06 22:09:28 +0000968 state = state->BindExpr(CE, LCtx, destVal);
Jordy Rosee64f3112010-08-16 07:51:42 +0000969 }
Jordy Rose7182b962011-06-04 01:50:25 +0000970
971 // Invalidate the destination.
972 // FIXME: Even if we can't perfectly model the copy, we should see if we
973 // can use LazyCompoundVals to copy the source values into the destination.
974 // This would probably remove any existing bindings past the end of the
975 // copied region, but that's still an improvement over blank invalidation.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000976 state = InvalidateBuffer(C, state, Dest,
977 state->getSVal(Dest, C.getLocationContext()));
Anna Zaks0bd6b112011-10-26 21:06:34 +0000978 C.addTransition(state);
Jordy Rosed325ffb2010-07-08 23:57:29 +0000979 }
980}
981
982
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000983void CStringChecker::evalMemcpy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +0000984 if (CE->getNumArgs() < 3)
985 return;
986
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000987 // void *memcpy(void *restrict dst, const void *restrict src, size_t n);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000988 // The return value is the address of the destination buffer.
Jordy Rosed325ffb2010-07-08 23:57:29 +0000989 const Expr *Dest = CE->getArg(0);
Ted Kremenek8bef8232012-01-26 21:29:00 +0000990 ProgramStateRef state = C.getState();
Jordy Rose3f8bb2f2011-06-04 01:47:27 +0000991
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000992 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1), true);
993}
994
995void CStringChecker::evalMempcpy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +0000996 if (CE->getNumArgs() < 3)
997 return;
998
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000999 // void *mempcpy(void *restrict dst, const void *restrict src, size_t n);
1000 // The return value is a pointer to the byte following the last written byte.
1001 const Expr *Dest = CE->getArg(0);
Ted Kremenek8bef8232012-01-26 21:29:00 +00001002 ProgramStateRef state = C.getState();
Lenny Maioranib8b875b2011-03-31 21:36:53 +00001003
1004 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1), true, true);
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001005}
1006
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001007void CStringChecker::evalMemmove(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001008 if (CE->getNumArgs() < 3)
1009 return;
1010
Jordy Rosed325ffb2010-07-08 23:57:29 +00001011 // void *memmove(void *dst, const void *src, size_t n);
1012 // The return value is the address of the destination buffer.
1013 const Expr *Dest = CE->getArg(0);
Ted Kremenek8bef8232012-01-26 21:29:00 +00001014 ProgramStateRef state = C.getState();
Jordy Rose3f8bb2f2011-06-04 01:47:27 +00001015
Lenny Maioranib8b875b2011-03-31 21:36:53 +00001016 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1));
Jordy Rosed325ffb2010-07-08 23:57:29 +00001017}
1018
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001019void CStringChecker::evalBcopy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001020 if (CE->getNumArgs() < 3)
1021 return;
1022
Jordy Rosed325ffb2010-07-08 23:57:29 +00001023 // void bcopy(const void *src, void *dst, size_t n);
Lenny Maioranib8b875b2011-03-31 21:36:53 +00001024 evalCopyCommon(C, CE, C.getState(),
1025 CE->getArg(2), CE->getArg(1), CE->getArg(0));
Jordy Rosed325ffb2010-07-08 23:57:29 +00001026}
1027
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001028void CStringChecker::evalMemcmp(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001029 if (CE->getNumArgs() < 3)
1030 return;
1031
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001032 // int memcmp(const void *s1, const void *s2, size_t n);
Jordy Rose9e49d9f2011-06-20 02:06:40 +00001033 CurrentFunctionDescription = "memory comparison function";
1034
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001035 const Expr *Left = CE->getArg(0);
1036 const Expr *Right = CE->getArg(1);
1037 const Expr *Size = CE->getArg(2);
1038
Ted Kremenek8bef8232012-01-26 21:29:00 +00001039 ProgramStateRef state = C.getState();
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001040 SValBuilder &svalBuilder = C.getSValBuilder();
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001041
Jordy Rosed325ffb2010-07-08 23:57:29 +00001042 // See if the size argument is zero.
Ted Kremenek5eca4822012-01-06 22:09:28 +00001043 const LocationContext *LCtx = C.getLocationContext();
1044 SVal sizeVal = state->getSVal(Size, LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001045 QualType sizeTy = Size->getType();
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001046
Ted Kremenek8bef8232012-01-26 21:29:00 +00001047 ProgramStateRef stateZeroSize, stateNonZeroSize;
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001048 llvm::tie(stateZeroSize, stateNonZeroSize) =
1049 assumeZero(C, state, sizeVal, sizeTy);
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001050
Jordy Rosed325ffb2010-07-08 23:57:29 +00001051 // If the size can be zero, the result will be 0 in that case, and we don't
1052 // have to check either of the buffers.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001053 if (stateZeroSize) {
1054 state = stateZeroSize;
Ted Kremenek5eca4822012-01-06 22:09:28 +00001055 state = state->BindExpr(CE, LCtx,
1056 svalBuilder.makeZeroVal(CE->getType()));
Anna Zaks0bd6b112011-10-26 21:06:34 +00001057 C.addTransition(state);
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001058 }
1059
Jordy Rosed325ffb2010-07-08 23:57:29 +00001060 // If the size can be nonzero, we have to check the other arguments.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001061 if (stateNonZeroSize) {
1062 state = stateNonZeroSize;
Jordy Rosed325ffb2010-07-08 23:57:29 +00001063 // If we know the two buffers are the same, we know the result is 0.
1064 // First, get the two buffers' addresses. Another checker will have already
1065 // made sure they're not undefined.
Ted Kremenek5eca4822012-01-06 22:09:28 +00001066 DefinedOrUnknownSVal LV =
David Blaikie5251abe2013-02-20 05:52:05 +00001067 state->getSVal(Left, LCtx).castAs<DefinedOrUnknownSVal>();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001068 DefinedOrUnknownSVal RV =
David Blaikie5251abe2013-02-20 05:52:05 +00001069 state->getSVal(Right, LCtx).castAs<DefinedOrUnknownSVal>();
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001070
Jordy Rosed325ffb2010-07-08 23:57:29 +00001071 // See if they are the same.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001072 DefinedOrUnknownSVal SameBuf = svalBuilder.evalEQ(state, LV, RV);
Ted Kremenek8bef8232012-01-26 21:29:00 +00001073 ProgramStateRef StSameBuf, StNotSameBuf;
Ted Kremenek28f47b92010-12-01 22:16:56 +00001074 llvm::tie(StSameBuf, StNotSameBuf) = state->assume(SameBuf);
Jordy Rosed325ffb2010-07-08 23:57:29 +00001075
Jordy Rose1e022412011-06-16 05:51:02 +00001076 // If the two arguments might be the same buffer, we know the result is 0,
Jordy Rosed325ffb2010-07-08 23:57:29 +00001077 // and we only need to check one size.
1078 if (StSameBuf) {
1079 state = StSameBuf;
1080 state = CheckBufferAccess(C, state, Size, Left);
1081 if (state) {
Ted Kremenek5eca4822012-01-06 22:09:28 +00001082 state = StSameBuf->BindExpr(CE, LCtx,
1083 svalBuilder.makeZeroVal(CE->getType()));
Anna Zaks0bd6b112011-10-26 21:06:34 +00001084 C.addTransition(state);
Jordy Rosed325ffb2010-07-08 23:57:29 +00001085 }
1086 }
1087
1088 // If the two arguments might be different buffers, we have to check the
1089 // size of both of them.
1090 if (StNotSameBuf) {
1091 state = StNotSameBuf;
1092 state = CheckBufferAccess(C, state, Size, Left, Right);
1093 if (state) {
1094 // The return value is the comparison result, which we don't know.
Ted Kremenek66c486f2012-08-22 06:26:15 +00001095 SVal CmpV = svalBuilder.conjureSymbolVal(0, CE, LCtx, C.blockCount());
Ted Kremenek5eca4822012-01-06 22:09:28 +00001096 state = state->BindExpr(CE, LCtx, CmpV);
Anna Zaks0bd6b112011-10-26 21:06:34 +00001097 C.addTransition(state);
Jordy Rosed325ffb2010-07-08 23:57:29 +00001098 }
1099 }
1100 }
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001101}
1102
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001103void CStringChecker::evalstrLength(CheckerContext &C,
1104 const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001105 if (CE->getNumArgs() < 1)
1106 return;
1107
Jordy Rose19c5dd12010-07-27 01:37:31 +00001108 // size_t strlen(const char *s);
Ted Kremenekbe4242c2011-02-22 04:55:05 +00001109 evalstrLengthCommon(C, CE, /* IsStrnlen = */ false);
1110}
1111
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001112void CStringChecker::evalstrnLength(CheckerContext &C,
1113 const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001114 if (CE->getNumArgs() < 2)
1115 return;
1116
Ted Kremenekbe4242c2011-02-22 04:55:05 +00001117 // size_t strnlen(const char *s, size_t maxlen);
1118 evalstrLengthCommon(C, CE, /* IsStrnlen = */ true);
1119}
1120
1121void CStringChecker::evalstrLengthCommon(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001122 bool IsStrnlen) const {
Jordy Rose9e49d9f2011-06-20 02:06:40 +00001123 CurrentFunctionDescription = "string length function";
Ted Kremenek8bef8232012-01-26 21:29:00 +00001124 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001125 const LocationContext *LCtx = C.getLocationContext();
Jordy Rose793bff32011-06-14 01:15:31 +00001126
1127 if (IsStrnlen) {
1128 const Expr *maxlenExpr = CE->getArg(1);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001129 SVal maxlenVal = state->getSVal(maxlenExpr, LCtx);
Jordy Rose793bff32011-06-14 01:15:31 +00001130
Ted Kremenek8bef8232012-01-26 21:29:00 +00001131 ProgramStateRef stateZeroSize, stateNonZeroSize;
Jordy Rose793bff32011-06-14 01:15:31 +00001132 llvm::tie(stateZeroSize, stateNonZeroSize) =
1133 assumeZero(C, state, maxlenVal, maxlenExpr->getType());
1134
1135 // If the size can be zero, the result will be 0 in that case, and we don't
1136 // have to check the string itself.
1137 if (stateZeroSize) {
1138 SVal zero = C.getSValBuilder().makeZeroVal(CE->getType());
Ted Kremenek5eca4822012-01-06 22:09:28 +00001139 stateZeroSize = stateZeroSize->BindExpr(CE, LCtx, zero);
Anna Zaks0bd6b112011-10-26 21:06:34 +00001140 C.addTransition(stateZeroSize);
Jordy Rose793bff32011-06-14 01:15:31 +00001141 }
1142
1143 // If the size is GUARANTEED to be zero, we're done!
1144 if (!stateNonZeroSize)
1145 return;
1146
1147 // Otherwise, record the assumption that the size is nonzero.
1148 state = stateNonZeroSize;
1149 }
1150
1151 // Check that the string argument is non-null.
Jordy Rose19c5dd12010-07-27 01:37:31 +00001152 const Expr *Arg = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001153 SVal ArgVal = state->getSVal(Arg, LCtx);
Jordy Rose19c5dd12010-07-27 01:37:31 +00001154
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001155 state = checkNonNull(C, state, Arg, ArgVal);
Jordy Rose19c5dd12010-07-27 01:37:31 +00001156
Jordy Rosebd32bee2011-06-14 01:26:48 +00001157 if (!state)
1158 return;
Jordy Rosea5261542010-08-14 21:02:52 +00001159
Jordy Rosebd32bee2011-06-14 01:26:48 +00001160 SVal strLength = getCStringLength(C, state, Arg, ArgVal);
Jordy Rosea5261542010-08-14 21:02:52 +00001161
Jordy Rosebd32bee2011-06-14 01:26:48 +00001162 // If the argument isn't a valid C string, there's no valid state to
1163 // transition to.
1164 if (strLength.isUndef())
1165 return;
Jordy Rose793bff32011-06-14 01:15:31 +00001166
Jordy Rosebd32bee2011-06-14 01:26:48 +00001167 DefinedOrUnknownSVal result = UnknownVal();
Jordy Rose793bff32011-06-14 01:15:31 +00001168
Jordy Rosebd32bee2011-06-14 01:26:48 +00001169 // If the check is for strnlen() then bind the return value to no more than
1170 // the maxlen value.
1171 if (IsStrnlen) {
Jordy Roseee2fde12011-06-16 05:56:50 +00001172 QualType cmpTy = C.getSValBuilder().getConditionType();
Jordy Rose793bff32011-06-14 01:15:31 +00001173
Jordy Rosebd32bee2011-06-14 01:26:48 +00001174 // It's a little unfortunate to be getting this again,
1175 // but it's not that expensive...
1176 const Expr *maxlenExpr = CE->getArg(1);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001177 SVal maxlenVal = state->getSVal(maxlenExpr, LCtx);
Ted Kremenekbe4242c2011-02-22 04:55:05 +00001178
David Blaikiedc84cd52013-02-20 22:23:23 +00001179 Optional<NonLoc> strLengthNL = strLength.getAs<NonLoc>();
1180 Optional<NonLoc> maxlenValNL = maxlenVal.getAs<NonLoc>();
Ted Kremenekbe4242c2011-02-22 04:55:05 +00001181
Jordy Rosebd32bee2011-06-14 01:26:48 +00001182 if (strLengthNL && maxlenValNL) {
Ted Kremenek8bef8232012-01-26 21:29:00 +00001183 ProgramStateRef stateStringTooLong, stateStringNotTooLong;
Jordy Rose793bff32011-06-14 01:15:31 +00001184
Jordy Rosebd32bee2011-06-14 01:26:48 +00001185 // Check if the strLength is greater than the maxlen.
1186 llvm::tie(stateStringTooLong, stateStringNotTooLong) =
David Blaikie5251abe2013-02-20 05:52:05 +00001187 state->assume(C.getSValBuilder().evalBinOpNN(
1188 state, BO_GT, *strLengthNL, *maxlenValNL, cmpTy)
1189 .castAs<DefinedOrUnknownSVal>());
Jordy Rose793bff32011-06-14 01:15:31 +00001190
Jordy Rosebd32bee2011-06-14 01:26:48 +00001191 if (stateStringTooLong && !stateStringNotTooLong) {
1192 // If the string is longer than maxlen, return maxlen.
1193 result = *maxlenValNL;
1194 } else if (stateStringNotTooLong && !stateStringTooLong) {
1195 // If the string is shorter than maxlen, return its length.
1196 result = *strLengthNL;
Ted Kremenekbe4242c2011-02-22 04:55:05 +00001197 }
1198 }
1199
Jordy Rosebd32bee2011-06-14 01:26:48 +00001200 if (result.isUnknown()) {
1201 // If we don't have enough information for a comparison, there's
1202 // no guarantee the full string length will actually be returned.
1203 // All we know is the return value is the min of the string length
1204 // and the limit. This is better than nothing.
Ted Kremenek66c486f2012-08-22 06:26:15 +00001205 result = C.getSValBuilder().conjureSymbolVal(0, CE, LCtx, C.blockCount());
David Blaikie5251abe2013-02-20 05:52:05 +00001206 NonLoc resultNL = result.castAs<NonLoc>();
Jordy Rosebd32bee2011-06-14 01:26:48 +00001207
1208 if (strLengthNL) {
David Blaikie5251abe2013-02-20 05:52:05 +00001209 state = state->assume(C.getSValBuilder().evalBinOpNN(
1210 state, BO_LE, resultNL, *strLengthNL, cmpTy)
1211 .castAs<DefinedOrUnknownSVal>(), true);
Jordy Rosebd32bee2011-06-14 01:26:48 +00001212 }
1213
1214 if (maxlenValNL) {
David Blaikie5251abe2013-02-20 05:52:05 +00001215 state = state->assume(C.getSValBuilder().evalBinOpNN(
1216 state, BO_LE, resultNL, *maxlenValNL, cmpTy)
1217 .castAs<DefinedOrUnknownSVal>(), true);
Jordy Rosebd32bee2011-06-14 01:26:48 +00001218 }
1219 }
1220
1221 } else {
1222 // This is a plain strlen(), not strnlen().
David Blaikie5251abe2013-02-20 05:52:05 +00001223 result = strLength.castAs<DefinedOrUnknownSVal>();
Jordy Rosebd32bee2011-06-14 01:26:48 +00001224
1225 // If we don't know the length of the string, conjure a return
1226 // value, so it can be used in constraints, at least.
1227 if (result.isUnknown()) {
Ted Kremenek66c486f2012-08-22 06:26:15 +00001228 result = C.getSValBuilder().conjureSymbolVal(0, CE, LCtx, C.blockCount());
Jordy Rosebd32bee2011-06-14 01:26:48 +00001229 }
Jordy Rose19c5dd12010-07-27 01:37:31 +00001230 }
Jordy Rosebd32bee2011-06-14 01:26:48 +00001231
1232 // Bind the return value.
1233 assert(!result.isUnknown() && "Should have conjured a value by now");
Ted Kremenek5eca4822012-01-06 22:09:28 +00001234 state = state->BindExpr(CE, LCtx, result);
Anna Zaks0bd6b112011-10-26 21:06:34 +00001235 C.addTransition(state);
Jordy Rose19c5dd12010-07-27 01:37:31 +00001236}
1237
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001238void CStringChecker::evalStrcpy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001239 if (CE->getNumArgs() < 2)
1240 return;
1241
Jordy Rosee64f3112010-08-16 07:51:42 +00001242 // char *strcpy(char *restrict dst, const char *restrict src);
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001243 evalStrcpyCommon(C, CE,
1244 /* returnEnd = */ false,
1245 /* isBounded = */ false,
1246 /* isAppending = */ false);
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001247}
1248
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001249void CStringChecker::evalStrncpy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001250 if (CE->getNumArgs() < 3)
1251 return;
1252
Jordy Rosec1525862011-06-04 00:05:23 +00001253 // char *strncpy(char *restrict dst, const char *restrict src, size_t n);
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001254 evalStrcpyCommon(C, CE,
1255 /* returnEnd = */ false,
1256 /* isBounded = */ true,
1257 /* isAppending = */ false);
Jordy Rosee64f3112010-08-16 07:51:42 +00001258}
1259
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001260void CStringChecker::evalStpcpy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001261 if (CE->getNumArgs() < 2)
1262 return;
1263
Jordy Rosee64f3112010-08-16 07:51:42 +00001264 // char *stpcpy(char *restrict dst, const char *restrict src);
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001265 evalStrcpyCommon(C, CE,
1266 /* returnEnd = */ true,
1267 /* isBounded = */ false,
1268 /* isAppending = */ false);
1269}
1270
1271void CStringChecker::evalStrcat(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001272 if (CE->getNumArgs() < 2)
1273 return;
1274
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001275 //char *strcat(char *restrict s1, const char *restrict s2);
1276 evalStrcpyCommon(C, CE,
1277 /* returnEnd = */ false,
1278 /* isBounded = */ false,
1279 /* isAppending = */ true);
1280}
1281
1282void CStringChecker::evalStrncat(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001283 if (CE->getNumArgs() < 3)
1284 return;
1285
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001286 //char *strncat(char *restrict s1, const char *restrict s2, size_t n);
1287 evalStrcpyCommon(C, CE,
1288 /* returnEnd = */ false,
1289 /* isBounded = */ true,
1290 /* isAppending = */ true);
Jordy Rosee64f3112010-08-16 07:51:42 +00001291}
1292
Ted Kremenek9c149532010-12-01 21:57:22 +00001293void CStringChecker::evalStrcpyCommon(CheckerContext &C, const CallExpr *CE,
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001294 bool returnEnd, bool isBounded,
1295 bool isAppending) const {
Jordy Rose9e49d9f2011-06-20 02:06:40 +00001296 CurrentFunctionDescription = "string copy function";
Ted Kremenek8bef8232012-01-26 21:29:00 +00001297 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001298 const LocationContext *LCtx = C.getLocationContext();
Jordy Rosee64f3112010-08-16 07:51:42 +00001299
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001300 // Check that the destination is non-null.
Jordy Rosee64f3112010-08-16 07:51:42 +00001301 const Expr *Dst = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001302 SVal DstVal = state->getSVal(Dst, LCtx);
Jordy Rosee64f3112010-08-16 07:51:42 +00001303
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001304 state = checkNonNull(C, state, Dst, DstVal);
Jordy Rosee64f3112010-08-16 07:51:42 +00001305 if (!state)
1306 return;
1307
1308 // Check that the source is non-null.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001309 const Expr *srcExpr = CE->getArg(1);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001310 SVal srcVal = state->getSVal(srcExpr, LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001311 state = checkNonNull(C, state, srcExpr, srcVal);
Jordy Rosee64f3112010-08-16 07:51:42 +00001312 if (!state)
1313 return;
1314
1315 // Get the string length of the source.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001316 SVal strLength = getCStringLength(C, state, srcExpr, srcVal);
Jordy Rosee64f3112010-08-16 07:51:42 +00001317
1318 // If the source isn't a valid C string, give up.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001319 if (strLength.isUndef())
Jordy Rosee64f3112010-08-16 07:51:42 +00001320 return;
1321
Jordy Rosed5af0e12011-06-15 05:52:56 +00001322 SValBuilder &svalBuilder = C.getSValBuilder();
1323 QualType cmpTy = svalBuilder.getConditionType();
Jordy Rose8912aae2011-06-20 21:55:40 +00001324 QualType sizeTy = svalBuilder.getContext().getSizeType();
Jordy Rosed5af0e12011-06-15 05:52:56 +00001325
Jordy Rose8912aae2011-06-20 21:55:40 +00001326 // These two values allow checking two kinds of errors:
1327 // - actual overflows caused by a source that doesn't fit in the destination
1328 // - potential overflows caused by a bound that could exceed the destination
Jordy Rosed5af0e12011-06-15 05:52:56 +00001329 SVal amountCopied = UnknownVal();
Jordy Rose8912aae2011-06-20 21:55:40 +00001330 SVal maxLastElementIndex = UnknownVal();
1331 const char *boundWarning = NULL;
Jordy Rosed5af0e12011-06-15 05:52:56 +00001332
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001333 // If the function is strncpy, strncat, etc... it is bounded.
1334 if (isBounded) {
1335 // Get the max number of characters to copy.
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001336 const Expr *lenExpr = CE->getArg(2);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001337 SVal lenVal = state->getSVal(lenExpr, LCtx);
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001338
Jordy Rosed5af0e12011-06-15 05:52:56 +00001339 // Protect against misdeclared strncpy().
Jordy Rose8912aae2011-06-20 21:55:40 +00001340 lenVal = svalBuilder.evalCast(lenVal, sizeTy, lenExpr->getType());
Jordy Rosed5af0e12011-06-15 05:52:56 +00001341
David Blaikiedc84cd52013-02-20 22:23:23 +00001342 Optional<NonLoc> strLengthNL = strLength.getAs<NonLoc>();
1343 Optional<NonLoc> lenValNL = lenVal.getAs<NonLoc>();
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001344
Jordy Rosed5af0e12011-06-15 05:52:56 +00001345 // If we know both values, we might be able to figure out how much
1346 // we're copying.
1347 if (strLengthNL && lenValNL) {
Ted Kremenek8bef8232012-01-26 21:29:00 +00001348 ProgramStateRef stateSourceTooLong, stateSourceNotTooLong;
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001349
Jordy Rosed5af0e12011-06-15 05:52:56 +00001350 // Check if the max number to copy is less than the length of the src.
Jordy Rose8912aae2011-06-20 21:55:40 +00001351 // If the bound is equal to the source length, strncpy won't null-
1352 // terminate the result!
David Blaikie5251abe2013-02-20 05:52:05 +00001353 llvm::tie(stateSourceTooLong, stateSourceNotTooLong) = state->assume(
1354 svalBuilder.evalBinOpNN(state, BO_GE, *strLengthNL, *lenValNL, cmpTy)
1355 .castAs<DefinedOrUnknownSVal>());
Jordy Rosed5af0e12011-06-15 05:52:56 +00001356
1357 if (stateSourceTooLong && !stateSourceNotTooLong) {
1358 // Max number to copy is less than the length of the src, so the actual
1359 // strLength copied is the max number arg.
1360 state = stateSourceTooLong;
1361 amountCopied = lenVal;
1362
1363 } else if (!stateSourceTooLong && stateSourceNotTooLong) {
1364 // The source buffer entirely fits in the bound.
1365 state = stateSourceNotTooLong;
1366 amountCopied = strLength;
1367 }
1368 }
1369
Jordy Rose5e5f1502011-06-20 03:49:16 +00001370 // We still want to know if the bound is known to be too large.
Jordy Rose8912aae2011-06-20 21:55:40 +00001371 if (lenValNL) {
1372 if (isAppending) {
1373 // For strncat, the check is strlen(dst) + lenVal < sizeof(dst)
1374
1375 // Get the string length of the destination. If the destination is
1376 // memory that can't have a string length, we shouldn't be copying
1377 // into it anyway.
1378 SVal dstStrLength = getCStringLength(C, state, Dst, DstVal);
1379 if (dstStrLength.isUndef())
1380 return;
1381
David Blaikiedc84cd52013-02-20 22:23:23 +00001382 if (Optional<NonLoc> dstStrLengthNL = dstStrLength.getAs<NonLoc>()) {
Jordy Rose8912aae2011-06-20 21:55:40 +00001383 maxLastElementIndex = svalBuilder.evalBinOpNN(state, BO_Add,
1384 *lenValNL,
1385 *dstStrLengthNL,
1386 sizeTy);
1387 boundWarning = "Size argument is greater than the free space in the "
1388 "destination buffer";
1389 }
1390
1391 } else {
1392 // For strncpy, this is just checking that lenVal <= sizeof(dst)
1393 // (Yes, strncpy and strncat differ in how they treat termination.
1394 // strncat ALWAYS terminates, but strncpy doesn't.)
Jordy Rose6e4244e2012-05-14 17:58:35 +00001395
1396 // We need a special case for when the copy size is zero, in which
1397 // case strncpy will do no work at all. Our bounds check uses n-1
1398 // as the last element accessed, so n == 0 is problematic.
1399 ProgramStateRef StateZeroSize, StateNonZeroSize;
1400 llvm::tie(StateZeroSize, StateNonZeroSize) =
1401 assumeZero(C, state, *lenValNL, sizeTy);
1402
1403 // If the size is known to be zero, we're done.
1404 if (StateZeroSize && !StateNonZeroSize) {
1405 StateZeroSize = StateZeroSize->BindExpr(CE, LCtx, DstVal);
1406 C.addTransition(StateZeroSize);
1407 return;
1408 }
1409
1410 // Otherwise, go ahead and figure out the last element we'll touch.
1411 // We don't record the non-zero assumption here because we can't
1412 // be sure. We won't warn on a possible zero.
David Blaikie5251abe2013-02-20 05:52:05 +00001413 NonLoc one = svalBuilder.makeIntVal(1, sizeTy).castAs<NonLoc>();
Jordy Rose8912aae2011-06-20 21:55:40 +00001414 maxLastElementIndex = svalBuilder.evalBinOpNN(state, BO_Sub, *lenValNL,
1415 one, sizeTy);
1416 boundWarning = "Size argument is greater than the length of the "
1417 "destination buffer";
1418 }
1419 }
Jordy Rose5e5f1502011-06-20 03:49:16 +00001420
Jordy Rosed5af0e12011-06-15 05:52:56 +00001421 // If we couldn't pin down the copy length, at least bound it.
Jordy Rose8912aae2011-06-20 21:55:40 +00001422 // FIXME: We should actually run this code path for append as well, but
1423 // right now it creates problems with constraints (since we can end up
1424 // trying to pass constraints from symbol to symbol).
1425 if (amountCopied.isUnknown() && !isAppending) {
Jordy Rosed5af0e12011-06-15 05:52:56 +00001426 // Try to get a "hypothetical" string length symbol, which we can later
1427 // set as a real value if that turns out to be the case.
1428 amountCopied = getCStringLength(C, state, lenExpr, srcVal, true);
1429 assert(!amountCopied.isUndef());
1430
David Blaikiedc84cd52013-02-20 22:23:23 +00001431 if (Optional<NonLoc> amountCopiedNL = amountCopied.getAs<NonLoc>()) {
Jordy Rosed5af0e12011-06-15 05:52:56 +00001432 if (lenValNL) {
1433 // amountCopied <= lenVal
1434 SVal copiedLessThanBound = svalBuilder.evalBinOpNN(state, BO_LE,
1435 *amountCopiedNL,
1436 *lenValNL,
1437 cmpTy);
David Blaikie5251abe2013-02-20 05:52:05 +00001438 state = state->assume(
1439 copiedLessThanBound.castAs<DefinedOrUnknownSVal>(), true);
Jordy Rosed5af0e12011-06-15 05:52:56 +00001440 if (!state)
1441 return;
1442 }
1443
1444 if (strLengthNL) {
1445 // amountCopied <= strlen(source)
1446 SVal copiedLessThanSrc = svalBuilder.evalBinOpNN(state, BO_LE,
1447 *amountCopiedNL,
1448 *strLengthNL,
1449 cmpTy);
David Blaikie5251abe2013-02-20 05:52:05 +00001450 state = state->assume(
1451 copiedLessThanSrc.castAs<DefinedOrUnknownSVal>(), true);
Jordy Rosed5af0e12011-06-15 05:52:56 +00001452 if (!state)
1453 return;
1454 }
1455 }
1456 }
1457
1458 } else {
1459 // The function isn't bounded. The amount copied should match the length
1460 // of the source buffer.
1461 amountCopied = strLength;
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001462 }
1463
Jordy Rosed5af0e12011-06-15 05:52:56 +00001464 assert(state);
1465
1466 // This represents the number of characters copied into the destination
1467 // buffer. (It may not actually be the strlen if the destination buffer
1468 // is not terminated.)
1469 SVal finalStrLength = UnknownVal();
1470
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001471 // If this is an appending function (strcat, strncat...) then set the
1472 // string length to strlen(src) + strlen(dst) since the buffer will
1473 // ultimately contain both.
1474 if (isAppending) {
Jordy Rose1e022412011-06-16 05:51:02 +00001475 // Get the string length of the destination. If the destination is memory
1476 // that can't have a string length, we shouldn't be copying into it anyway.
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001477 SVal dstStrLength = getCStringLength(C, state, Dst, DstVal);
1478 if (dstStrLength.isUndef())
1479 return;
1480
David Blaikiedc84cd52013-02-20 22:23:23 +00001481 Optional<NonLoc> srcStrLengthNL = amountCopied.getAs<NonLoc>();
1482 Optional<NonLoc> dstStrLengthNL = dstStrLength.getAs<NonLoc>();
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001483
Jordy Rosed5af0e12011-06-15 05:52:56 +00001484 // If we know both string lengths, we might know the final string length.
1485 if (srcStrLengthNL && dstStrLengthNL) {
1486 // Make sure the two lengths together don't overflow a size_t.
1487 state = checkAdditionOverflow(C, state, *srcStrLengthNL, *dstStrLengthNL);
1488 if (!state)
1489 return;
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001490
Jordy Rosed5af0e12011-06-15 05:52:56 +00001491 finalStrLength = svalBuilder.evalBinOpNN(state, BO_Add, *srcStrLengthNL,
1492 *dstStrLengthNL, sizeTy);
1493 }
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001494
Jordy Rosed5af0e12011-06-15 05:52:56 +00001495 // If we couldn't get a single value for the final string length,
1496 // we can at least bound it by the individual lengths.
1497 if (finalStrLength.isUnknown()) {
1498 // Try to get a "hypothetical" string length symbol, which we can later
1499 // set as a real value if that turns out to be the case.
1500 finalStrLength = getCStringLength(C, state, CE, DstVal, true);
1501 assert(!finalStrLength.isUndef());
1502
David Blaikiedc84cd52013-02-20 22:23:23 +00001503 if (Optional<NonLoc> finalStrLengthNL = finalStrLength.getAs<NonLoc>()) {
Jordy Rosed5af0e12011-06-15 05:52:56 +00001504 if (srcStrLengthNL) {
1505 // finalStrLength >= srcStrLength
1506 SVal sourceInResult = svalBuilder.evalBinOpNN(state, BO_GE,
1507 *finalStrLengthNL,
1508 *srcStrLengthNL,
1509 cmpTy);
David Blaikie5251abe2013-02-20 05:52:05 +00001510 state = state->assume(sourceInResult.castAs<DefinedOrUnknownSVal>(),
Jordy Rosed5af0e12011-06-15 05:52:56 +00001511 true);
1512 if (!state)
1513 return;
1514 }
1515
1516 if (dstStrLengthNL) {
1517 // finalStrLength >= dstStrLength
1518 SVal destInResult = svalBuilder.evalBinOpNN(state, BO_GE,
1519 *finalStrLengthNL,
1520 *dstStrLengthNL,
1521 cmpTy);
David Blaikie5251abe2013-02-20 05:52:05 +00001522 state =
1523 state->assume(destInResult.castAs<DefinedOrUnknownSVal>(), true);
Jordy Rosed5af0e12011-06-15 05:52:56 +00001524 if (!state)
1525 return;
1526 }
1527 }
1528 }
1529
1530 } else {
1531 // Otherwise, this is a copy-over function (strcpy, strncpy, ...), and
1532 // the final string length will match the input string length.
1533 finalStrLength = amountCopied;
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001534 }
1535
Jordy Rosed5af0e12011-06-15 05:52:56 +00001536 // The final result of the function will either be a pointer past the last
1537 // copied element, or a pointer to the start of the destination buffer.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001538 SVal Result = (returnEnd ? UnknownVal() : DstVal);
Jordy Rosee64f3112010-08-16 07:51:42 +00001539
Jordy Rosed5af0e12011-06-15 05:52:56 +00001540 assert(state);
1541
Jordy Rosee64f3112010-08-16 07:51:42 +00001542 // If the destination is a MemRegion, try to check for a buffer overflow and
1543 // record the new string length.
David Blaikiedc84cd52013-02-20 22:23:23 +00001544 if (Optional<loc::MemRegionVal> dstRegVal =
David Blaikie5251abe2013-02-20 05:52:05 +00001545 DstVal.getAs<loc::MemRegionVal>()) {
Jordy Rose8912aae2011-06-20 21:55:40 +00001546 QualType ptrTy = Dst->getType();
1547
1548 // If we have an exact value on a bounded copy, use that to check for
1549 // overflows, rather than our estimate about how much is actually copied.
1550 if (boundWarning) {
David Blaikiedc84cd52013-02-20 22:23:23 +00001551 if (Optional<NonLoc> maxLastNL = maxLastElementIndex.getAs<NonLoc>()) {
Jordy Rose8912aae2011-06-20 21:55:40 +00001552 SVal maxLastElement = svalBuilder.evalBinOpLN(state, BO_Add, *dstRegVal,
1553 *maxLastNL, ptrTy);
1554 state = CheckLocation(C, state, CE->getArg(2), maxLastElement,
1555 boundWarning);
1556 if (!state)
1557 return;
1558 }
1559 }
1560
1561 // Then, if the final length is known...
David Blaikiedc84cd52013-02-20 22:23:23 +00001562 if (Optional<NonLoc> knownStrLength = finalStrLength.getAs<NonLoc>()) {
Jordy Rosed5af0e12011-06-15 05:52:56 +00001563 SVal lastElement = svalBuilder.evalBinOpLN(state, BO_Add, *dstRegVal,
Jordy Rose8912aae2011-06-20 21:55:40 +00001564 *knownStrLength, ptrTy);
Jordy Rosee64f3112010-08-16 07:51:42 +00001565
Jordy Rose8912aae2011-06-20 21:55:40 +00001566 // ...and we haven't checked the bound, we'll check the actual copy.
1567 if (!boundWarning) {
1568 const char * const warningMsg =
1569 "String copy function overflows destination buffer";
1570 state = CheckLocation(C, state, Dst, lastElement, warningMsg);
1571 if (!state)
1572 return;
1573 }
Jordy Rosee64f3112010-08-16 07:51:42 +00001574
1575 // If this is a stpcpy-style copy, the last element is the return value.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001576 if (returnEnd)
1577 Result = lastElement;
Jordy Rosee64f3112010-08-16 07:51:42 +00001578 }
1579
1580 // Invalidate the destination. This must happen before we set the C string
1581 // length because invalidation will clear the length.
1582 // FIXME: Even if we can't perfectly model the copy, we should see if we
1583 // can use LazyCompoundVals to copy the source values into the destination.
1584 // This would probably remove any existing bindings past the end of the
1585 // string, but that's still an improvement over blank invalidation.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001586 state = InvalidateBuffer(C, state, Dst, *dstRegVal);
Jordy Rosee64f3112010-08-16 07:51:42 +00001587
Jordy Rose5e5f1502011-06-20 03:49:16 +00001588 // Set the C string length of the destination, if we know it.
Jordy Rose8912aae2011-06-20 21:55:40 +00001589 if (isBounded && !isAppending) {
1590 // strncpy is annoying in that it doesn't guarantee to null-terminate
1591 // the result string. If the original string didn't fit entirely inside
1592 // the bound (including the null-terminator), we don't know how long the
1593 // result is.
1594 if (amountCopied != strLength)
1595 finalStrLength = UnknownVal();
1596 }
1597 state = setCStringLength(state, dstRegVal->getRegion(), finalStrLength);
Jordy Rosee64f3112010-08-16 07:51:42 +00001598 }
1599
Jordy Rosed5af0e12011-06-15 05:52:56 +00001600 assert(state);
1601
Jordy Rosee64f3112010-08-16 07:51:42 +00001602 // If this is a stpcpy-style copy, but we were unable to check for a buffer
1603 // overflow, we still need a result. Conjure a return value.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001604 if (returnEnd && Result.isUnknown()) {
Ted Kremenek66c486f2012-08-22 06:26:15 +00001605 Result = svalBuilder.conjureSymbolVal(0, CE, LCtx, C.blockCount());
Jordy Rosee64f3112010-08-16 07:51:42 +00001606 }
1607
1608 // Set the return value.
Ted Kremenek5eca4822012-01-06 22:09:28 +00001609 state = state->BindExpr(CE, LCtx, Result);
Anna Zaks0bd6b112011-10-26 21:06:34 +00001610 C.addTransition(state);
Jordy Rosee64f3112010-08-16 07:51:42 +00001611}
1612
Lenny Maiorani318dd922011-04-12 17:08:43 +00001613void CStringChecker::evalStrcmp(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001614 if (CE->getNumArgs() < 2)
1615 return;
1616
Jordy Roseadc42d42011-06-16 07:13:34 +00001617 //int strcmp(const char *s1, const char *s2);
Lenny Maioranibd1d16a2011-04-28 15:09:11 +00001618 evalStrcmpCommon(C, CE, /* isBounded = */ false, /* ignoreCase = */ false);
Lenny Maiorani357f6ee2011-04-25 22:21:00 +00001619}
Lenny Maiorani318dd922011-04-12 17:08:43 +00001620
Lenny Maiorani357f6ee2011-04-25 22:21:00 +00001621void CStringChecker::evalStrncmp(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001622 if (CE->getNumArgs() < 3)
1623 return;
1624
Jordy Roseadc42d42011-06-16 07:13:34 +00001625 //int strncmp(const char *s1, const char *s2, size_t n);
Lenny Maioranibd1d16a2011-04-28 15:09:11 +00001626 evalStrcmpCommon(C, CE, /* isBounded = */ true, /* ignoreCase = */ false);
1627}
1628
1629void CStringChecker::evalStrcasecmp(CheckerContext &C,
1630 const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001631 if (CE->getNumArgs() < 2)
1632 return;
1633
Jordy Roseadc42d42011-06-16 07:13:34 +00001634 //int strcasecmp(const char *s1, const char *s2);
Lenny Maioranibd1d16a2011-04-28 15:09:11 +00001635 evalStrcmpCommon(C, CE, /* isBounded = */ false, /* ignoreCase = */ true);
Lenny Maiorani357f6ee2011-04-25 22:21:00 +00001636}
1637
Lenny Maiorani454fd2d2011-05-02 19:05:49 +00001638void CStringChecker::evalStrncasecmp(CheckerContext &C,
1639 const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001640 if (CE->getNumArgs() < 3)
1641 return;
1642
Jordy Roseadc42d42011-06-16 07:13:34 +00001643 //int strncasecmp(const char *s1, const char *s2, size_t n);
Lenny Maiorani454fd2d2011-05-02 19:05:49 +00001644 evalStrcmpCommon(C, CE, /* isBounded = */ true, /* ignoreCase = */ true);
1645}
1646
Lenny Maiorani357f6ee2011-04-25 22:21:00 +00001647void CStringChecker::evalStrcmpCommon(CheckerContext &C, const CallExpr *CE,
Lenny Maioranibd1d16a2011-04-28 15:09:11 +00001648 bool isBounded, bool ignoreCase) const {
Jordy Rose9e49d9f2011-06-20 02:06:40 +00001649 CurrentFunctionDescription = "string comparison function";
Ted Kremenek8bef8232012-01-26 21:29:00 +00001650 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001651 const LocationContext *LCtx = C.getLocationContext();
Lenny Maiorani318dd922011-04-12 17:08:43 +00001652
1653 // Check that the first string is non-null
1654 const Expr *s1 = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001655 SVal s1Val = state->getSVal(s1, LCtx);
Lenny Maiorani318dd922011-04-12 17:08:43 +00001656 state = checkNonNull(C, state, s1, s1Val);
1657 if (!state)
1658 return;
1659
1660 // Check that the second string is non-null.
1661 const Expr *s2 = CE->getArg(1);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001662 SVal s2Val = state->getSVal(s2, LCtx);
Lenny Maiorani318dd922011-04-12 17:08:43 +00001663 state = checkNonNull(C, state, s2, s2Val);
1664 if (!state)
1665 return;
1666
1667 // Get the string length of the first string or give up.
1668 SVal s1Length = getCStringLength(C, state, s1, s1Val);
1669 if (s1Length.isUndef())
1670 return;
1671
1672 // Get the string length of the second string or give up.
1673 SVal s2Length = getCStringLength(C, state, s2, s2Val);
1674 if (s2Length.isUndef())
1675 return;
1676
Jordy Roseadc42d42011-06-16 07:13:34 +00001677 // If we know the two buffers are the same, we know the result is 0.
1678 // First, get the two buffers' addresses. Another checker will have already
1679 // made sure they're not undefined.
David Blaikie5251abe2013-02-20 05:52:05 +00001680 DefinedOrUnknownSVal LV = s1Val.castAs<DefinedOrUnknownSVal>();
1681 DefinedOrUnknownSVal RV = s2Val.castAs<DefinedOrUnknownSVal>();
Lenny Maiorani318dd922011-04-12 17:08:43 +00001682
Jordy Roseadc42d42011-06-16 07:13:34 +00001683 // See if they are the same.
Lenny Maiorani318dd922011-04-12 17:08:43 +00001684 SValBuilder &svalBuilder = C.getSValBuilder();
Jordy Roseadc42d42011-06-16 07:13:34 +00001685 DefinedOrUnknownSVal SameBuf = svalBuilder.evalEQ(state, LV, RV);
Ted Kremenek8bef8232012-01-26 21:29:00 +00001686 ProgramStateRef StSameBuf, StNotSameBuf;
Jordy Roseadc42d42011-06-16 07:13:34 +00001687 llvm::tie(StSameBuf, StNotSameBuf) = state->assume(SameBuf);
Lenny Maiorani318dd922011-04-12 17:08:43 +00001688
Jordy Roseadc42d42011-06-16 07:13:34 +00001689 // If the two arguments might be the same buffer, we know the result is 0,
1690 // and we only need to check one size.
1691 if (StSameBuf) {
Ted Kremenek5eca4822012-01-06 22:09:28 +00001692 StSameBuf = StSameBuf->BindExpr(CE, LCtx,
1693 svalBuilder.makeZeroVal(CE->getType()));
Anna Zaks0bd6b112011-10-26 21:06:34 +00001694 C.addTransition(StSameBuf);
Jordy Roseadc42d42011-06-16 07:13:34 +00001695
1696 // If the two arguments are GUARANTEED to be the same, we're done!
1697 if (!StNotSameBuf)
1698 return;
1699 }
1700
1701 assert(StNotSameBuf);
1702 state = StNotSameBuf;
1703
1704 // At this point we can go about comparing the two buffers.
1705 // For now, we only do this if they're both known string literals.
1706
1707 // Attempt to extract string literals from both expressions.
1708 const StringLiteral *s1StrLiteral = getCStringLiteral(C, state, s1, s1Val);
1709 const StringLiteral *s2StrLiteral = getCStringLiteral(C, state, s2, s2Val);
1710 bool canComputeResult = false;
1711
1712 if (s1StrLiteral && s2StrLiteral) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001713 StringRef s1StrRef = s1StrLiteral->getString();
1714 StringRef s2StrRef = s2StrLiteral->getString();
Jordy Roseadc42d42011-06-16 07:13:34 +00001715
1716 if (isBounded) {
1717 // Get the max number of characters to compare.
1718 const Expr *lenExpr = CE->getArg(2);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001719 SVal lenVal = state->getSVal(lenExpr, LCtx);
Jordy Roseadc42d42011-06-16 07:13:34 +00001720
1721 // If the length is known, we can get the right substrings.
1722 if (const llvm::APSInt *len = svalBuilder.getKnownValue(state, lenVal)) {
1723 // Create substrings of each to compare the prefix.
1724 s1StrRef = s1StrRef.substr(0, (size_t)len->getZExtValue());
1725 s2StrRef = s2StrRef.substr(0, (size_t)len->getZExtValue());
1726 canComputeResult = true;
1727 }
1728 } else {
1729 // This is a normal, unbounded strcmp.
1730 canComputeResult = true;
1731 }
1732
1733 if (canComputeResult) {
1734 // Real strcmp stops at null characters.
1735 size_t s1Term = s1StrRef.find('\0');
Chris Lattner5f9e2722011-07-23 10:55:15 +00001736 if (s1Term != StringRef::npos)
Jordy Roseadc42d42011-06-16 07:13:34 +00001737 s1StrRef = s1StrRef.substr(0, s1Term);
1738
1739 size_t s2Term = s2StrRef.find('\0');
Chris Lattner5f9e2722011-07-23 10:55:15 +00001740 if (s2Term != StringRef::npos)
Jordy Roseadc42d42011-06-16 07:13:34 +00001741 s2StrRef = s2StrRef.substr(0, s2Term);
1742
1743 // Use StringRef's comparison methods to compute the actual result.
1744 int result;
1745
1746 if (ignoreCase) {
1747 // Compare string 1 to string 2 the same way strcasecmp() does.
1748 result = s1StrRef.compare_lower(s2StrRef);
1749 } else {
1750 // Compare string 1 to string 2 the same way strcmp() does.
1751 result = s1StrRef.compare(s2StrRef);
1752 }
1753
1754 // Build the SVal of the comparison and bind the return value.
1755 SVal resultVal = svalBuilder.makeIntVal(result, CE->getType());
Ted Kremenek5eca4822012-01-06 22:09:28 +00001756 state = state->BindExpr(CE, LCtx, resultVal);
Jordy Roseadc42d42011-06-16 07:13:34 +00001757 }
1758 }
1759
1760 if (!canComputeResult) {
1761 // Conjure a symbolic value. It's the best we can do.
Ted Kremenek66c486f2012-08-22 06:26:15 +00001762 SVal resultVal = svalBuilder.conjureSymbolVal(0, CE, LCtx, C.blockCount());
Ted Kremenek5eca4822012-01-06 22:09:28 +00001763 state = state->BindExpr(CE, LCtx, resultVal);
Jordy Roseadc42d42011-06-16 07:13:34 +00001764 }
1765
1766 // Record this as a possible path.
Anna Zaks0bd6b112011-10-26 21:06:34 +00001767 C.addTransition(state);
Lenny Maiorani318dd922011-04-12 17:08:43 +00001768}
1769
Jordan Roseaf226212013-04-22 23:18:42 +00001770void CStringChecker::evalStrsep(CheckerContext &C, const CallExpr *CE) const {
1771 //char *strsep(char **stringp, const char *delim);
1772 if (CE->getNumArgs() < 2)
1773 return;
1774
1775 // Sanity: does the search string parameter match the return type?
1776 const Expr *SearchStrPtr = CE->getArg(0);
1777 QualType CharPtrTy = SearchStrPtr->getType()->getPointeeType();
1778 if (CharPtrTy.isNull() ||
1779 CE->getType().getUnqualifiedType() != CharPtrTy.getUnqualifiedType())
1780 return;
1781
1782 CurrentFunctionDescription = "strsep()";
1783 ProgramStateRef State = C.getState();
1784 const LocationContext *LCtx = C.getLocationContext();
1785
1786 // Check that the search string pointer is non-null (though it may point to
1787 // a null string).
1788 SVal SearchStrVal = State->getSVal(SearchStrPtr, LCtx);
1789 State = checkNonNull(C, State, SearchStrPtr, SearchStrVal);
1790 if (!State)
1791 return;
1792
1793 // Check that the delimiter string is non-null.
1794 const Expr *DelimStr = CE->getArg(1);
1795 SVal DelimStrVal = State->getSVal(DelimStr, LCtx);
1796 State = checkNonNull(C, State, DelimStr, DelimStrVal);
1797 if (!State)
1798 return;
1799
1800 SValBuilder &SVB = C.getSValBuilder();
1801 SVal Result;
1802 if (Optional<Loc> SearchStrLoc = SearchStrVal.getAs<Loc>()) {
1803 // Get the current value of the search string pointer, as a char*.
1804 Result = State->getSVal(*SearchStrLoc, CharPtrTy);
1805
1806 // Invalidate the search string, representing the change of one delimiter
1807 // character to NUL.
1808 State = InvalidateBuffer(C, State, SearchStrPtr, Result);
1809
1810 // Overwrite the search string pointer. The new value is either an address
1811 // further along in the same string, or NULL if there are no more tokens.
1812 State = State->bindLoc(*SearchStrLoc,
1813 SVB.conjureSymbolVal(getTag(), CE, LCtx, CharPtrTy,
1814 C.blockCount()));
1815 } else {
1816 assert(SearchStrVal.isUnknown());
1817 // Conjure a symbolic value. It's the best we can do.
1818 Result = SVB.conjureSymbolVal(0, CE, LCtx, C.blockCount());
1819 }
1820
1821 // Set the return value, and finish.
1822 State = State->BindExpr(CE, LCtx, Result);
1823 C.addTransition(State);
1824}
1825
1826
Jordy Rosed325ffb2010-07-08 23:57:29 +00001827//===----------------------------------------------------------------------===//
Jordy Rosea5261542010-08-14 21:02:52 +00001828// The driver method, and other Checker callbacks.
Jordy Rosed325ffb2010-07-08 23:57:29 +00001829//===----------------------------------------------------------------------===//
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001830
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001831bool CStringChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
Anna Zaks998e2752012-02-17 22:35:26 +00001832 const FunctionDecl *FDecl = C.getCalleeDecl(CE);
1833
1834 if (!FDecl)
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001835 return false;
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001836
Jordan Roseaf226212013-04-22 23:18:42 +00001837 // FIXME: Poorly-factored string switches are slow.
Anna Zaks998e2752012-02-17 22:35:26 +00001838 FnCheck evalFunction = 0;
1839 if (C.isCLibraryFunction(FDecl, "memcpy"))
1840 evalFunction = &CStringChecker::evalMemcpy;
1841 else if (C.isCLibraryFunction(FDecl, "mempcpy"))
1842 evalFunction = &CStringChecker::evalMempcpy;
1843 else if (C.isCLibraryFunction(FDecl, "memcmp"))
1844 evalFunction = &CStringChecker::evalMemcmp;
1845 else if (C.isCLibraryFunction(FDecl, "memmove"))
1846 evalFunction = &CStringChecker::evalMemmove;
1847 else if (C.isCLibraryFunction(FDecl, "strcpy"))
1848 evalFunction = &CStringChecker::evalStrcpy;
1849 else if (C.isCLibraryFunction(FDecl, "strncpy"))
1850 evalFunction = &CStringChecker::evalStrncpy;
1851 else if (C.isCLibraryFunction(FDecl, "stpcpy"))
1852 evalFunction = &CStringChecker::evalStpcpy;
1853 else if (C.isCLibraryFunction(FDecl, "strcat"))
1854 evalFunction = &CStringChecker::evalStrcat;
1855 else if (C.isCLibraryFunction(FDecl, "strncat"))
1856 evalFunction = &CStringChecker::evalStrncat;
1857 else if (C.isCLibraryFunction(FDecl, "strlen"))
1858 evalFunction = &CStringChecker::evalstrLength;
1859 else if (C.isCLibraryFunction(FDecl, "strnlen"))
1860 evalFunction = &CStringChecker::evalstrnLength;
1861 else if (C.isCLibraryFunction(FDecl, "strcmp"))
1862 evalFunction = &CStringChecker::evalStrcmp;
1863 else if (C.isCLibraryFunction(FDecl, "strncmp"))
1864 evalFunction = &CStringChecker::evalStrncmp;
1865 else if (C.isCLibraryFunction(FDecl, "strcasecmp"))
1866 evalFunction = &CStringChecker::evalStrcasecmp;
1867 else if (C.isCLibraryFunction(FDecl, "strncasecmp"))
1868 evalFunction = &CStringChecker::evalStrncasecmp;
Jordan Roseaf226212013-04-22 23:18:42 +00001869 else if (C.isCLibraryFunction(FDecl, "strsep"))
1870 evalFunction = &CStringChecker::evalStrsep;
Anna Zaks998e2752012-02-17 22:35:26 +00001871 else if (C.isCLibraryFunction(FDecl, "bcopy"))
1872 evalFunction = &CStringChecker::evalBcopy;
1873 else if (C.isCLibraryFunction(FDecl, "bcmp"))
1874 evalFunction = &CStringChecker::evalMemcmp;
1875
Jordy Rosed325ffb2010-07-08 23:57:29 +00001876 // If the callee isn't a string function, let another checker handle it.
Ted Kremenek9c149532010-12-01 21:57:22 +00001877 if (!evalFunction)
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001878 return false;
1879
Jordy Rose9e49d9f2011-06-20 02:06:40 +00001880 // Make sure each function sets its own description.
1881 // (But don't bother in a release build.)
1882 assert(!(CurrentFunctionDescription = NULL));
1883
Jordy Rosed325ffb2010-07-08 23:57:29 +00001884 // Check and evaluate the call.
Ted Kremenek9c149532010-12-01 21:57:22 +00001885 (this->*evalFunction)(C, CE);
Anna Zaks57300762012-02-07 00:56:14 +00001886
1887 // If the evaluate call resulted in no change, chain to the next eval call
1888 // handler.
1889 // Note, the custom CString evaluation calls assume that basic safety
1890 // properties are held. However, if the user chooses to turn off some of these
1891 // checks, we ignore the issues and leave the call evaluation to a generic
1892 // handler.
1893 if (!C.isDifferent())
1894 return false;
1895
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001896 return true;
1897}
Jordy Rosea5261542010-08-14 21:02:52 +00001898
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001899void CStringChecker::checkPreStmt(const DeclStmt *DS, CheckerContext &C) const {
Jordy Rosea5261542010-08-14 21:02:52 +00001900 // Record string length for char a[] = "abc";
Ted Kremenek8bef8232012-01-26 21:29:00 +00001901 ProgramStateRef state = C.getState();
Jordy Rosea5261542010-08-14 21:02:52 +00001902
1903 for (DeclStmt::const_decl_iterator I = DS->decl_begin(), E = DS->decl_end();
1904 I != E; ++I) {
1905 const VarDecl *D = dyn_cast<VarDecl>(*I);
1906 if (!D)
1907 continue;
1908
1909 // FIXME: Handle array fields of structs.
1910 if (!D->getType()->isArrayType())
1911 continue;
1912
1913 const Expr *Init = D->getInit();
1914 if (!Init)
1915 continue;
1916 if (!isa<StringLiteral>(Init))
1917 continue;
1918
Anna Zaks39ac1872011-10-26 21:06:44 +00001919 Loc VarLoc = state->getLValue(D, C.getLocationContext());
Jordy Rosea5261542010-08-14 21:02:52 +00001920 const MemRegion *MR = VarLoc.getAsRegion();
1921 if (!MR)
1922 continue;
1923
Ted Kremenek5eca4822012-01-06 22:09:28 +00001924 SVal StrVal = state->getSVal(Init, C.getLocationContext());
Jordy Rosea5261542010-08-14 21:02:52 +00001925 assert(StrVal.isValid() && "Initializer string is unknown or undefined");
David Blaikie5251abe2013-02-20 05:52:05 +00001926 DefinedOrUnknownSVal strLength =
1927 getCStringLength(C, state, Init, StrVal).castAs<DefinedOrUnknownSVal>();
Jordy Rosea5261542010-08-14 21:02:52 +00001928
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001929 state = state->set<CStringLength>(MR, strLength);
Jordy Rosea5261542010-08-14 21:02:52 +00001930 }
1931
Anna Zaks0bd6b112011-10-26 21:06:34 +00001932 C.addTransition(state);
Jordy Rosea5261542010-08-14 21:02:52 +00001933}
1934
Ted Kremenek8bef8232012-01-26 21:29:00 +00001935bool CStringChecker::wantsRegionChangeUpdate(ProgramStateRef state) const {
Jordan Rose166d5022012-11-02 01:54:06 +00001936 CStringLengthTy Entries = state->get<CStringLength>();
Jordy Rosea5261542010-08-14 21:02:52 +00001937 return !Entries.isEmpty();
1938}
1939
Ted Kremenek8bef8232012-01-26 21:29:00 +00001940ProgramStateRef
1941CStringChecker::checkRegionChanges(ProgramStateRef state,
Anna Zaksbf53dfa2012-12-20 00:38:25 +00001942 const InvalidatedSymbols *,
Jordy Rose537716a2011-08-27 22:51:26 +00001943 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00001944 ArrayRef<const MemRegion *> Regions,
Jordan Rose740d4902012-07-02 19:27:35 +00001945 const CallEvent *Call) const {
Jordan Rose166d5022012-11-02 01:54:06 +00001946 CStringLengthTy Entries = state->get<CStringLength>();
Jordy Rosea5261542010-08-14 21:02:52 +00001947 if (Entries.isEmpty())
1948 return state;
1949
1950 llvm::SmallPtrSet<const MemRegion *, 8> Invalidated;
1951 llvm::SmallPtrSet<const MemRegion *, 32> SuperRegions;
1952
1953 // First build sets for the changed regions and their super-regions.
Jordy Rose537716a2011-08-27 22:51:26 +00001954 for (ArrayRef<const MemRegion *>::iterator
1955 I = Regions.begin(), E = Regions.end(); I != E; ++I) {
1956 const MemRegion *MR = *I;
Jordy Rosea5261542010-08-14 21:02:52 +00001957 Invalidated.insert(MR);
1958
1959 SuperRegions.insert(MR);
1960 while (const SubRegion *SR = dyn_cast<SubRegion>(MR)) {
1961 MR = SR->getSuperRegion();
1962 SuperRegions.insert(MR);
1963 }
1964 }
1965
Jordan Rose166d5022012-11-02 01:54:06 +00001966 CStringLengthTy::Factory &F = state->get_context<CStringLength>();
Jordy Rosea5261542010-08-14 21:02:52 +00001967
1968 // Then loop over the entries in the current state.
Jordan Rose166d5022012-11-02 01:54:06 +00001969 for (CStringLengthTy::iterator I = Entries.begin(),
Jordy Rosea5261542010-08-14 21:02:52 +00001970 E = Entries.end(); I != E; ++I) {
1971 const MemRegion *MR = I.getKey();
1972
1973 // Is this entry for a super-region of a changed region?
1974 if (SuperRegions.count(MR)) {
Ted Kremenek3baf6722010-11-24 00:54:37 +00001975 Entries = F.remove(Entries, MR);
Jordy Rosea5261542010-08-14 21:02:52 +00001976 continue;
1977 }
1978
1979 // Is this entry for a sub-region of a changed region?
1980 const MemRegion *Super = MR;
1981 while (const SubRegion *SR = dyn_cast<SubRegion>(Super)) {
1982 Super = SR->getSuperRegion();
1983 if (Invalidated.count(Super)) {
Ted Kremenek3baf6722010-11-24 00:54:37 +00001984 Entries = F.remove(Entries, MR);
Jordy Rosea5261542010-08-14 21:02:52 +00001985 break;
1986 }
1987 }
1988 }
1989
1990 return state->set<CStringLength>(Entries);
1991}
1992
Ted Kremenek8bef8232012-01-26 21:29:00 +00001993void CStringChecker::checkLiveSymbols(ProgramStateRef state,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001994 SymbolReaper &SR) const {
Jordy Rosea5261542010-08-14 21:02:52 +00001995 // Mark all symbols in our string length map as valid.
Jordan Rose166d5022012-11-02 01:54:06 +00001996 CStringLengthTy Entries = state->get<CStringLength>();
Jordy Rosea5261542010-08-14 21:02:52 +00001997
Jordan Rose166d5022012-11-02 01:54:06 +00001998 for (CStringLengthTy::iterator I = Entries.begin(), E = Entries.end();
Jordy Rosea5261542010-08-14 21:02:52 +00001999 I != E; ++I) {
2000 SVal Len = I.getData();
Jordy Rosed5af0e12011-06-15 05:52:56 +00002001
Anna Zaks1d1d5152011-12-06 23:12:33 +00002002 for (SymExpr::symbol_iterator si = Len.symbol_begin(),
2003 se = Len.symbol_end(); si != se; ++si)
Jordy Rosed5af0e12011-06-15 05:52:56 +00002004 SR.markInUse(*si);
Jordy Rosea5261542010-08-14 21:02:52 +00002005 }
2006}
2007
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00002008void CStringChecker::checkDeadSymbols(SymbolReaper &SR,
2009 CheckerContext &C) const {
Jordy Rosea5261542010-08-14 21:02:52 +00002010 if (!SR.hasDeadSymbols())
2011 return;
2012
Ted Kremenek8bef8232012-01-26 21:29:00 +00002013 ProgramStateRef state = C.getState();
Jordan Rose166d5022012-11-02 01:54:06 +00002014 CStringLengthTy Entries = state->get<CStringLength>();
Jordy Rosea5261542010-08-14 21:02:52 +00002015 if (Entries.isEmpty())
2016 return;
2017
Jordan Rose166d5022012-11-02 01:54:06 +00002018 CStringLengthTy::Factory &F = state->get_context<CStringLength>();
2019 for (CStringLengthTy::iterator I = Entries.begin(), E = Entries.end();
Jordy Rosea5261542010-08-14 21:02:52 +00002020 I != E; ++I) {
2021 SVal Len = I.getData();
2022 if (SymbolRef Sym = Len.getAsSymbol()) {
2023 if (SR.isDead(Sym))
Ted Kremenek3baf6722010-11-24 00:54:37 +00002024 Entries = F.remove(Entries, I.getKey());
Jordy Rosea5261542010-08-14 21:02:52 +00002025 }
2026 }
2027
2028 state = state->set<CStringLength>(Entries);
Anna Zaks0bd6b112011-10-26 21:06:34 +00002029 C.addTransition(state);
Jordy Rosea5261542010-08-14 21:02:52 +00002030}
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00002031
Anna Zaks57300762012-02-07 00:56:14 +00002032#define REGISTER_CHECKER(name) \
2033void ento::register##name(CheckerManager &mgr) {\
Pavel Labath3b8f77d2013-06-12 07:45:04 +00002034 mgr.registerChecker<CStringChecker>()->Filter.Check##name = true; \
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00002035}
Anna Zaks57300762012-02-07 00:56:14 +00002036
2037REGISTER_CHECKER(CStringNullArg)
2038REGISTER_CHECKER(CStringOutOfBounds)
2039REGISTER_CHECKER(CStringBufferOverlap)
2040REGISTER_CHECKER(CStringNotNullTerm)
Anna Zaksf0dfc9c2012-02-17 22:35:31 +00002041
2042void ento::registerCStringCheckerBasic(CheckerManager &Mgr) {
2043 registerCStringNullArg(Mgr);
2044}