blob: aa1ca6f2f809d5dddeae2eec5b043f52f261fb96 [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)
Anna Zaks57300762012-02-07 00:56:14 +0000234 BT_Null.reset(new BuiltinBug("Unix API",
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)
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000528 BT_Overlap.reset(new BugType("Unix API", "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 }
Jordy Rosea5261542010-08-14 21:02:52 +0000664
665 // 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
672 if (!hypothetical)
673 state = state->set<CStringLength>(MR, strLength);
674
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000675 return strLength;
Jordy Rosea5261542010-08-14 21:02:52 +0000676}
677
Ted Kremenek8bef8232012-01-26 21:29:00 +0000678SVal CStringChecker::getCStringLength(CheckerContext &C, ProgramStateRef &state,
Jordy Rosed5af0e12011-06-15 05:52:56 +0000679 const Expr *Ex, SVal Buf,
680 bool hypothetical) const {
Jordy Rose19c5dd12010-07-27 01:37:31 +0000681 const MemRegion *MR = Buf.getAsRegion();
682 if (!MR) {
683 // If we can't get a region, see if it's something we /know/ isn't a
684 // C string. In the context of locations, the only time we can issue such
685 // a warning is for labels.
David Blaikiedc84cd52013-02-20 22:23:23 +0000686 if (Optional<loc::GotoLabel> Label = Buf.getAs<loc::GotoLabel>()) {
Anna Zaks57300762012-02-07 00:56:14 +0000687 if (!Filter.CheckCStringNotNullTerm)
688 return UndefinedVal();
689
Anna Zaks0bd6b112011-10-26 21:06:34 +0000690 if (ExplodedNode *N = C.addTransition(state)) {
Jordy Rose19c5dd12010-07-27 01:37:31 +0000691 if (!BT_NotCString)
Anna Zaks57300762012-02-07 00:56:14 +0000692 BT_NotCString.reset(new BuiltinBug("Unix API",
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000693 "Argument is not a null-terminated string."));
Jordy Rose19c5dd12010-07-27 01:37:31 +0000694
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000695 SmallString<120> buf;
Jordy Rose19c5dd12010-07-27 01:37:31 +0000696 llvm::raw_svector_ostream os(buf);
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000697 assert(CurrentFunctionDescription);
698 os << "Argument to " << CurrentFunctionDescription
699 << " is the address of the label '" << Label->getLabel()->getName()
Jordy Rose19c5dd12010-07-27 01:37:31 +0000700 << "', which is not a null-terminated string";
701
702 // Generate a report for this bug.
Anna Zakse172e8b2011-08-17 23:00:25 +0000703 BugReport *report = new BugReport(*BT_NotCString,
Jordy Rose19c5dd12010-07-27 01:37:31 +0000704 os.str(), N);
705
706 report->addRange(Ex->getSourceRange());
Jordan Rose785950e2012-11-02 01:53:40 +0000707 C.emitReport(report);
Jordy Rose19c5dd12010-07-27 01:37:31 +0000708 }
Jordy Rose19c5dd12010-07-27 01:37:31 +0000709 return UndefinedVal();
Anna Zaks57300762012-02-07 00:56:14 +0000710
Jordy Rose19c5dd12010-07-27 01:37:31 +0000711 }
712
Jordy Rosea5261542010-08-14 21:02:52 +0000713 // If it's not a region and not a label, give up.
714 return UnknownVal();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000715 }
716
Jordy Rosea5261542010-08-14 21:02:52 +0000717 // If we have a region, strip casts from it and see if we can figure out
718 // its length. For anything we can't figure out, just return UnknownVal.
719 MR = MR->StripCasts();
720
721 switch (MR->getKind()) {
722 case MemRegion::StringRegionKind: {
723 // Modifying the contents of string regions is undefined [C99 6.4.5p6],
724 // so we can assume that the byte length is the correct C string length.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000725 SValBuilder &svalBuilder = C.getSValBuilder();
726 QualType sizeTy = svalBuilder.getContext().getSizeType();
727 const StringLiteral *strLit = cast<StringRegion>(MR)->getStringLiteral();
728 return svalBuilder.makeIntVal(strLit->getByteLength(), sizeTy);
Jordy Rosea5261542010-08-14 21:02:52 +0000729 }
730 case MemRegion::SymbolicRegionKind:
731 case MemRegion::AllocaRegionKind:
732 case MemRegion::VarRegionKind:
733 case MemRegion::FieldRegionKind:
734 case MemRegion::ObjCIvarRegionKind:
Jordy Rosed5af0e12011-06-15 05:52:56 +0000735 return getCStringLengthForRegion(C, state, Ex, MR, hypothetical);
Jordy Rosea5261542010-08-14 21:02:52 +0000736 case MemRegion::CompoundLiteralRegionKind:
737 // FIXME: Can we track this? Is it necessary?
738 return UnknownVal();
739 case MemRegion::ElementRegionKind:
740 // FIXME: How can we handle this? It's not good enough to subtract the
741 // offset from the base string length; consider "123\x00567" and &a[5].
742 return UnknownVal();
743 default:
744 // Other regions (mostly non-data) can't have a reliable C string length.
745 // In this case, an error is emitted and UndefinedVal is returned.
746 // The caller should always be prepared to handle this case.
Anna Zaks57300762012-02-07 00:56:14 +0000747 if (!Filter.CheckCStringNotNullTerm)
748 return UndefinedVal();
749
Anna Zaks0bd6b112011-10-26 21:06:34 +0000750 if (ExplodedNode *N = C.addTransition(state)) {
Jordy Rosea5261542010-08-14 21:02:52 +0000751 if (!BT_NotCString)
Anna Zaks57300762012-02-07 00:56:14 +0000752 BT_NotCString.reset(new BuiltinBug("Unix API",
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000753 "Argument is not a null-terminated string."));
Jordy Rosea5261542010-08-14 21:02:52 +0000754
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000755 SmallString<120> buf;
Jordy Rosea5261542010-08-14 21:02:52 +0000756 llvm::raw_svector_ostream os(buf);
757
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000758 assert(CurrentFunctionDescription);
759 os << "Argument to " << CurrentFunctionDescription << " is ";
Jordy Rosea5261542010-08-14 21:02:52 +0000760
761 if (SummarizeRegion(os, C.getASTContext(), MR))
762 os << ", which is not a null-terminated string";
763 else
764 os << "not a null-terminated string";
765
766 // Generate a report for this bug.
Anna Zakse172e8b2011-08-17 23:00:25 +0000767 BugReport *report = new BugReport(*BT_NotCString,
Jordy Rosea5261542010-08-14 21:02:52 +0000768 os.str(), N);
769
770 report->addRange(Ex->getSourceRange());
Jordan Rose785950e2012-11-02 01:53:40 +0000771 C.emitReport(report);
Jordy Rosea5261542010-08-14 21:02:52 +0000772 }
773
774 return UndefinedVal();
775 }
Jordy Rose19c5dd12010-07-27 01:37:31 +0000776}
777
Lenny Maiorani318dd922011-04-12 17:08:43 +0000778const StringLiteral *CStringChecker::getCStringLiteral(CheckerContext &C,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000779 ProgramStateRef &state, const Expr *expr, SVal val) const {
Lenny Maiorani318dd922011-04-12 17:08:43 +0000780
781 // Get the memory region pointed to by the val.
782 const MemRegion *bufRegion = val.getAsRegion();
783 if (!bufRegion)
784 return NULL;
785
786 // Strip casts off the memory region.
787 bufRegion = bufRegion->StripCasts();
788
789 // Cast the memory region to a string region.
790 const StringRegion *strRegion= dyn_cast<StringRegion>(bufRegion);
791 if (!strRegion)
792 return NULL;
793
794 // Return the actual string in the string region.
795 return strRegion->getStringLiteral();
796}
797
Ted Kremenek8bef8232012-01-26 21:29:00 +0000798ProgramStateRef CStringChecker::InvalidateBuffer(CheckerContext &C,
799 ProgramStateRef state,
Jordy Rosee64f3112010-08-16 07:51:42 +0000800 const Expr *E, SVal V) {
David Blaikiedc84cd52013-02-20 22:23:23 +0000801 Optional<Loc> L = V.getAs<Loc>();
Jordy Rosee64f3112010-08-16 07:51:42 +0000802 if (!L)
803 return state;
804
805 // FIXME: This is a simplified version of what's in CFRefCount.cpp -- it makes
806 // some assumptions about the value that CFRefCount can't. Even so, it should
807 // probably be refactored.
David Blaikiedc84cd52013-02-20 22:23:23 +0000808 if (Optional<loc::MemRegionVal> MR = L->getAs<loc::MemRegionVal>()) {
Jordy Rosee64f3112010-08-16 07:51:42 +0000809 const MemRegion *R = MR->getRegion()->StripCasts();
810
811 // Are we dealing with an ElementRegion? If so, we should be invalidating
812 // the super-region.
813 if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
814 R = ER->getSuperRegion();
815 // FIXME: What about layers of ElementRegions?
816 }
817
818 // Invalidate this region.
Ted Kremenek3133f792012-02-17 23:13:45 +0000819 const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
Anna Zaksbf53dfa2012-12-20 00:38:25 +0000820 return state->invalidateRegions(R, E, C.blockCount(), LCtx,
Anna Zaks64eb0702013-01-16 01:35:54 +0000821 /*CausesPointerEscape*/ false);
Jordy Rosee64f3112010-08-16 07:51:42 +0000822 }
823
824 // If we have a non-region value by chance, just remove the binding.
825 // FIXME: is this necessary or correct? This handles the non-Region
826 // cases. Is it ever valid to store to these?
Ted Kremenek56a46b52012-08-22 06:37:46 +0000827 return state->killBinding(*L);
Jordy Rosee64f3112010-08-16 07:51:42 +0000828}
829
Ted Kremenek9c378f72011-08-12 23:37:29 +0000830bool CStringChecker::SummarizeRegion(raw_ostream &os, ASTContext &Ctx,
Jordy Rose19c5dd12010-07-27 01:37:31 +0000831 const MemRegion *MR) {
Ted Kremenek96979342011-08-12 20:02:48 +0000832 const TypedValueRegion *TVR = dyn_cast<TypedValueRegion>(MR);
Jordy Rose19c5dd12010-07-27 01:37:31 +0000833
Jordy Rose096aef92011-08-12 21:41:07 +0000834 switch (MR->getKind()) {
Jordy Rose19c5dd12010-07-27 01:37:31 +0000835 case MemRegion::FunctionTextRegionKind: {
Anna Zaks5fc1d0c2012-09-17 19:13:56 +0000836 const NamedDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000837 if (FD)
Benjamin Kramerb8989f22011-10-14 18:45:37 +0000838 os << "the address of the function '" << *FD << '\'';
Jordy Rose19c5dd12010-07-27 01:37:31 +0000839 else
840 os << "the address of a function";
841 return true;
842 }
843 case MemRegion::BlockTextRegionKind:
844 os << "block text";
845 return true;
846 case MemRegion::BlockDataRegionKind:
847 os << "a block";
848 return true;
849 case MemRegion::CXXThisRegionKind:
Zhongxing Xu02fe28c2010-11-26 08:52:48 +0000850 case MemRegion::CXXTempObjectRegionKind:
Ted Kremenek96979342011-08-12 20:02:48 +0000851 os << "a C++ temp object of type " << TVR->getValueType().getAsString();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000852 return true;
853 case MemRegion::VarRegionKind:
Ted Kremenek96979342011-08-12 20:02:48 +0000854 os << "a variable of type" << TVR->getValueType().getAsString();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000855 return true;
856 case MemRegion::FieldRegionKind:
Ted Kremenek96979342011-08-12 20:02:48 +0000857 os << "a field of type " << TVR->getValueType().getAsString();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000858 return true;
859 case MemRegion::ObjCIvarRegionKind:
Ted Kremenek96979342011-08-12 20:02:48 +0000860 os << "an instance variable of type " << TVR->getValueType().getAsString();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000861 return true;
862 default:
863 return false;
864 }
865}
866
Jordy Rosed325ffb2010-07-08 23:57:29 +0000867//===----------------------------------------------------------------------===//
Ted Kremenek9c149532010-12-01 21:57:22 +0000868// evaluation of individual function calls.
Jordy Rosed325ffb2010-07-08 23:57:29 +0000869//===----------------------------------------------------------------------===//
870
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000871void CStringChecker::evalCopyCommon(CheckerContext &C,
872 const CallExpr *CE,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000873 ProgramStateRef state,
Jordy Rosed325ffb2010-07-08 23:57:29 +0000874 const Expr *Size, const Expr *Dest,
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000875 const Expr *Source, bool Restricted,
876 bool IsMempcpy) const {
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000877 CurrentFunctionDescription = "memory copy function";
878
Jordy Rosed325ffb2010-07-08 23:57:29 +0000879 // See if the size argument is zero.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000880 const LocationContext *LCtx = C.getLocationContext();
881 SVal sizeVal = state->getSVal(Size, LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000882 QualType sizeTy = Size->getType();
Jordy Rosed325ffb2010-07-08 23:57:29 +0000883
Ted Kremenek8bef8232012-01-26 21:29:00 +0000884 ProgramStateRef stateZeroSize, stateNonZeroSize;
Jordy Rose1e022412011-06-16 05:51:02 +0000885 llvm::tie(stateZeroSize, stateNonZeroSize) =
886 assumeZero(C, state, sizeVal, sizeTy);
Jordy Rosed325ffb2010-07-08 23:57:29 +0000887
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000888 // Get the value of the Dest.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000889 SVal destVal = state->getSVal(Dest, LCtx);
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000890
891 // If the size is zero, there won't be any actual memory access, so
892 // just bind the return value to the destination buffer and return.
Anna Zaksdd160f32012-05-03 18:21:28 +0000893 if (stateZeroSize && !stateNonZeroSize) {
Ted Kremenek5eca4822012-01-06 22:09:28 +0000894 stateZeroSize = stateZeroSize->BindExpr(CE, LCtx, destVal);
Anna Zaks0bd6b112011-10-26 21:06:34 +0000895 C.addTransition(stateZeroSize);
Anna Zaksdd160f32012-05-03 18:21:28 +0000896 return;
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000897 }
Jordy Rosed325ffb2010-07-08 23:57:29 +0000898
899 // If the size can be nonzero, we have to check the other arguments.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000900 if (stateNonZeroSize) {
Jordy Rose22d27172011-06-04 00:04:22 +0000901 state = stateNonZeroSize;
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000902
903 // Ensure the destination is not null. If it is NULL there will be a
904 // NULL pointer dereference.
905 state = checkNonNull(C, state, Dest, destVal);
906 if (!state)
907 return;
908
909 // Get the value of the Src.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000910 SVal srcVal = state->getSVal(Source, LCtx);
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000911
912 // Ensure the source is not null. If it is NULL there will be a
913 // NULL pointer dereference.
914 state = checkNonNull(C, state, Source, srcVal);
915 if (!state)
916 return;
917
Jordy Rose7182b962011-06-04 01:50:25 +0000918 // Ensure the accesses are valid and that the buffers do not overlap.
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000919 const char * const writeWarning =
920 "Memory copy function overflows destination buffer";
Jordy Rosee64f3112010-08-16 07:51:42 +0000921 state = CheckBufferAccess(C, state, Size, Dest, Source,
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000922 writeWarning, /* sourceWarning = */ NULL);
Jordy Rosed325ffb2010-07-08 23:57:29 +0000923 if (Restricted)
924 state = CheckOverlap(C, state, Size, Dest, Source);
Jordy Rosee64f3112010-08-16 07:51:42 +0000925
Jordy Rose7182b962011-06-04 01:50:25 +0000926 if (!state)
927 return;
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000928
Jordy Rose7182b962011-06-04 01:50:25 +0000929 // If this is mempcpy, get the byte after the last byte copied and
930 // bind the expr.
931 if (IsMempcpy) {
David Blaikie5251abe2013-02-20 05:52:05 +0000932 loc::MemRegionVal destRegVal = destVal.castAs<loc::MemRegionVal>();
Jordy Rose7182b962011-06-04 01:50:25 +0000933
934 // Get the length to copy.
David Blaikiedc84cd52013-02-20 22:23:23 +0000935 if (Optional<NonLoc> lenValNonLoc = sizeVal.getAs<NonLoc>()) {
Jordy Rose7182b962011-06-04 01:50:25 +0000936 // Get the byte after the last byte copied.
937 SVal lastElement = C.getSValBuilder().evalBinOpLN(state, BO_Add,
David Blaikie5251abe2013-02-20 05:52:05 +0000938 destRegVal,
Jordy Rose7182b962011-06-04 01:50:25 +0000939 *lenValNonLoc,
940 Dest->getType());
941
942 // The byte after the last byte copied is the return value.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000943 state = state->BindExpr(CE, LCtx, lastElement);
Jordy Rose3f8bb2f2011-06-04 01:47:27 +0000944 } else {
Jordy Rose7182b962011-06-04 01:50:25 +0000945 // If we don't know how much we copied, we can at least
946 // conjure a return value for later.
Ted Kremenek66c486f2012-08-22 06:26:15 +0000947 SVal result = C.getSValBuilder().conjureSymbolVal(0, CE, LCtx,
948 C.blockCount());
Ted Kremenek5eca4822012-01-06 22:09:28 +0000949 state = state->BindExpr(CE, LCtx, result);
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000950 }
951
Jordy Rose7182b962011-06-04 01:50:25 +0000952 } else {
953 // All other copies return the destination buffer.
954 // (Well, bcopy() has a void return type, but this won't hurt.)
Ted Kremenek5eca4822012-01-06 22:09:28 +0000955 state = state->BindExpr(CE, LCtx, destVal);
Jordy Rosee64f3112010-08-16 07:51:42 +0000956 }
Jordy Rose7182b962011-06-04 01:50:25 +0000957
958 // Invalidate the destination.
959 // FIXME: Even if we can't perfectly model the copy, we should see if we
960 // can use LazyCompoundVals to copy the source values into the destination.
961 // This would probably remove any existing bindings past the end of the
962 // copied region, but that's still an improvement over blank invalidation.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000963 state = InvalidateBuffer(C, state, Dest,
964 state->getSVal(Dest, C.getLocationContext()));
Anna Zaks0bd6b112011-10-26 21:06:34 +0000965 C.addTransition(state);
Jordy Rosed325ffb2010-07-08 23:57:29 +0000966 }
967}
968
969
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000970void CStringChecker::evalMemcpy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +0000971 if (CE->getNumArgs() < 3)
972 return;
973
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000974 // void *memcpy(void *restrict dst, const void *restrict src, size_t n);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000975 // The return value is the address of the destination buffer.
Jordy Rosed325ffb2010-07-08 23:57:29 +0000976 const Expr *Dest = CE->getArg(0);
Ted Kremenek8bef8232012-01-26 21:29:00 +0000977 ProgramStateRef state = C.getState();
Jordy Rose3f8bb2f2011-06-04 01:47:27 +0000978
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000979 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1), true);
980}
981
982void CStringChecker::evalMempcpy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +0000983 if (CE->getNumArgs() < 3)
984 return;
985
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000986 // void *mempcpy(void *restrict dst, const void *restrict src, size_t n);
987 // The return value is a pointer to the byte following the last written byte.
988 const Expr *Dest = CE->getArg(0);
Ted Kremenek8bef8232012-01-26 21:29:00 +0000989 ProgramStateRef state = C.getState();
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000990
991 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1), true, true);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000992}
993
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000994void CStringChecker::evalMemmove(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +0000995 if (CE->getNumArgs() < 3)
996 return;
997
Jordy Rosed325ffb2010-07-08 23:57:29 +0000998 // void *memmove(void *dst, const void *src, size_t n);
999 // The return value is the address of the destination buffer.
1000 const Expr *Dest = CE->getArg(0);
Ted Kremenek8bef8232012-01-26 21:29:00 +00001001 ProgramStateRef state = C.getState();
Jordy Rose3f8bb2f2011-06-04 01:47:27 +00001002
Lenny Maioranib8b875b2011-03-31 21:36:53 +00001003 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1));
Jordy Rosed325ffb2010-07-08 23:57:29 +00001004}
1005
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001006void CStringChecker::evalBcopy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001007 if (CE->getNumArgs() < 3)
1008 return;
1009
Jordy Rosed325ffb2010-07-08 23:57:29 +00001010 // void bcopy(const void *src, void *dst, size_t n);
Lenny Maioranib8b875b2011-03-31 21:36:53 +00001011 evalCopyCommon(C, CE, C.getState(),
1012 CE->getArg(2), CE->getArg(1), CE->getArg(0));
Jordy Rosed325ffb2010-07-08 23:57:29 +00001013}
1014
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001015void CStringChecker::evalMemcmp(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001016 if (CE->getNumArgs() < 3)
1017 return;
1018
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001019 // int memcmp(const void *s1, const void *s2, size_t n);
Jordy Rose9e49d9f2011-06-20 02:06:40 +00001020 CurrentFunctionDescription = "memory comparison function";
1021
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001022 const Expr *Left = CE->getArg(0);
1023 const Expr *Right = CE->getArg(1);
1024 const Expr *Size = CE->getArg(2);
1025
Ted Kremenek8bef8232012-01-26 21:29:00 +00001026 ProgramStateRef state = C.getState();
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001027 SValBuilder &svalBuilder = C.getSValBuilder();
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001028
Jordy Rosed325ffb2010-07-08 23:57:29 +00001029 // See if the size argument is zero.
Ted Kremenek5eca4822012-01-06 22:09:28 +00001030 const LocationContext *LCtx = C.getLocationContext();
1031 SVal sizeVal = state->getSVal(Size, LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001032 QualType sizeTy = Size->getType();
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001033
Ted Kremenek8bef8232012-01-26 21:29:00 +00001034 ProgramStateRef stateZeroSize, stateNonZeroSize;
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001035 llvm::tie(stateZeroSize, stateNonZeroSize) =
1036 assumeZero(C, state, sizeVal, sizeTy);
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001037
Jordy Rosed325ffb2010-07-08 23:57:29 +00001038 // If the size can be zero, the result will be 0 in that case, and we don't
1039 // have to check either of the buffers.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001040 if (stateZeroSize) {
1041 state = stateZeroSize;
Ted Kremenek5eca4822012-01-06 22:09:28 +00001042 state = state->BindExpr(CE, LCtx,
1043 svalBuilder.makeZeroVal(CE->getType()));
Anna Zaks0bd6b112011-10-26 21:06:34 +00001044 C.addTransition(state);
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001045 }
1046
Jordy Rosed325ffb2010-07-08 23:57:29 +00001047 // If the size can be nonzero, we have to check the other arguments.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001048 if (stateNonZeroSize) {
1049 state = stateNonZeroSize;
Jordy Rosed325ffb2010-07-08 23:57:29 +00001050 // If we know the two buffers are the same, we know the result is 0.
1051 // First, get the two buffers' addresses. Another checker will have already
1052 // made sure they're not undefined.
Ted Kremenek5eca4822012-01-06 22:09:28 +00001053 DefinedOrUnknownSVal LV =
David Blaikie5251abe2013-02-20 05:52:05 +00001054 state->getSVal(Left, LCtx).castAs<DefinedOrUnknownSVal>();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001055 DefinedOrUnknownSVal RV =
David Blaikie5251abe2013-02-20 05:52:05 +00001056 state->getSVal(Right, LCtx).castAs<DefinedOrUnknownSVal>();
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001057
Jordy Rosed325ffb2010-07-08 23:57:29 +00001058 // See if they are the same.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001059 DefinedOrUnknownSVal SameBuf = svalBuilder.evalEQ(state, LV, RV);
Ted Kremenek8bef8232012-01-26 21:29:00 +00001060 ProgramStateRef StSameBuf, StNotSameBuf;
Ted Kremenek28f47b92010-12-01 22:16:56 +00001061 llvm::tie(StSameBuf, StNotSameBuf) = state->assume(SameBuf);
Jordy Rosed325ffb2010-07-08 23:57:29 +00001062
Jordy Rose1e022412011-06-16 05:51:02 +00001063 // If the two arguments might be the same buffer, we know the result is 0,
Jordy Rosed325ffb2010-07-08 23:57:29 +00001064 // and we only need to check one size.
1065 if (StSameBuf) {
1066 state = StSameBuf;
1067 state = CheckBufferAccess(C, state, Size, Left);
1068 if (state) {
Ted Kremenek5eca4822012-01-06 22:09:28 +00001069 state = StSameBuf->BindExpr(CE, LCtx,
1070 svalBuilder.makeZeroVal(CE->getType()));
Anna Zaks0bd6b112011-10-26 21:06:34 +00001071 C.addTransition(state);
Jordy Rosed325ffb2010-07-08 23:57:29 +00001072 }
1073 }
1074
1075 // If the two arguments might be different buffers, we have to check the
1076 // size of both of them.
1077 if (StNotSameBuf) {
1078 state = StNotSameBuf;
1079 state = CheckBufferAccess(C, state, Size, Left, Right);
1080 if (state) {
1081 // The return value is the comparison result, which we don't know.
Ted Kremenek66c486f2012-08-22 06:26:15 +00001082 SVal CmpV = svalBuilder.conjureSymbolVal(0, CE, LCtx, C.blockCount());
Ted Kremenek5eca4822012-01-06 22:09:28 +00001083 state = state->BindExpr(CE, LCtx, CmpV);
Anna Zaks0bd6b112011-10-26 21:06:34 +00001084 C.addTransition(state);
Jordy Rosed325ffb2010-07-08 23:57:29 +00001085 }
1086 }
1087 }
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001088}
1089
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001090void CStringChecker::evalstrLength(CheckerContext &C,
1091 const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001092 if (CE->getNumArgs() < 1)
1093 return;
1094
Jordy Rose19c5dd12010-07-27 01:37:31 +00001095 // size_t strlen(const char *s);
Ted Kremenekbe4242c2011-02-22 04:55:05 +00001096 evalstrLengthCommon(C, CE, /* IsStrnlen = */ false);
1097}
1098
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001099void CStringChecker::evalstrnLength(CheckerContext &C,
1100 const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001101 if (CE->getNumArgs() < 2)
1102 return;
1103
Ted Kremenekbe4242c2011-02-22 04:55:05 +00001104 // size_t strnlen(const char *s, size_t maxlen);
1105 evalstrLengthCommon(C, CE, /* IsStrnlen = */ true);
1106}
1107
1108void CStringChecker::evalstrLengthCommon(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001109 bool IsStrnlen) const {
Jordy Rose9e49d9f2011-06-20 02:06:40 +00001110 CurrentFunctionDescription = "string length function";
Ted Kremenek8bef8232012-01-26 21:29:00 +00001111 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001112 const LocationContext *LCtx = C.getLocationContext();
Jordy Rose793bff32011-06-14 01:15:31 +00001113
1114 if (IsStrnlen) {
1115 const Expr *maxlenExpr = CE->getArg(1);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001116 SVal maxlenVal = state->getSVal(maxlenExpr, LCtx);
Jordy Rose793bff32011-06-14 01:15:31 +00001117
Ted Kremenek8bef8232012-01-26 21:29:00 +00001118 ProgramStateRef stateZeroSize, stateNonZeroSize;
Jordy Rose793bff32011-06-14 01:15:31 +00001119 llvm::tie(stateZeroSize, stateNonZeroSize) =
1120 assumeZero(C, state, maxlenVal, maxlenExpr->getType());
1121
1122 // If the size can be zero, the result will be 0 in that case, and we don't
1123 // have to check the string itself.
1124 if (stateZeroSize) {
1125 SVal zero = C.getSValBuilder().makeZeroVal(CE->getType());
Ted Kremenek5eca4822012-01-06 22:09:28 +00001126 stateZeroSize = stateZeroSize->BindExpr(CE, LCtx, zero);
Anna Zaks0bd6b112011-10-26 21:06:34 +00001127 C.addTransition(stateZeroSize);
Jordy Rose793bff32011-06-14 01:15:31 +00001128 }
1129
1130 // If the size is GUARANTEED to be zero, we're done!
1131 if (!stateNonZeroSize)
1132 return;
1133
1134 // Otherwise, record the assumption that the size is nonzero.
1135 state = stateNonZeroSize;
1136 }
1137
1138 // Check that the string argument is non-null.
Jordy Rose19c5dd12010-07-27 01:37:31 +00001139 const Expr *Arg = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001140 SVal ArgVal = state->getSVal(Arg, LCtx);
Jordy Rose19c5dd12010-07-27 01:37:31 +00001141
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001142 state = checkNonNull(C, state, Arg, ArgVal);
Jordy Rose19c5dd12010-07-27 01:37:31 +00001143
Jordy Rosebd32bee2011-06-14 01:26:48 +00001144 if (!state)
1145 return;
Jordy Rosea5261542010-08-14 21:02:52 +00001146
Jordy Rosebd32bee2011-06-14 01:26:48 +00001147 SVal strLength = getCStringLength(C, state, Arg, ArgVal);
Jordy Rosea5261542010-08-14 21:02:52 +00001148
Jordy Rosebd32bee2011-06-14 01:26:48 +00001149 // If the argument isn't a valid C string, there's no valid state to
1150 // transition to.
1151 if (strLength.isUndef())
1152 return;
Jordy Rose793bff32011-06-14 01:15:31 +00001153
Jordy Rosebd32bee2011-06-14 01:26:48 +00001154 DefinedOrUnknownSVal result = UnknownVal();
Jordy Rose793bff32011-06-14 01:15:31 +00001155
Jordy Rosebd32bee2011-06-14 01:26:48 +00001156 // If the check is for strnlen() then bind the return value to no more than
1157 // the maxlen value.
1158 if (IsStrnlen) {
Jordy Roseee2fde12011-06-16 05:56:50 +00001159 QualType cmpTy = C.getSValBuilder().getConditionType();
Jordy Rose793bff32011-06-14 01:15:31 +00001160
Jordy Rosebd32bee2011-06-14 01:26:48 +00001161 // It's a little unfortunate to be getting this again,
1162 // but it's not that expensive...
1163 const Expr *maxlenExpr = CE->getArg(1);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001164 SVal maxlenVal = state->getSVal(maxlenExpr, LCtx);
Ted Kremenekbe4242c2011-02-22 04:55:05 +00001165
David Blaikiedc84cd52013-02-20 22:23:23 +00001166 Optional<NonLoc> strLengthNL = strLength.getAs<NonLoc>();
1167 Optional<NonLoc> maxlenValNL = maxlenVal.getAs<NonLoc>();
Ted Kremenekbe4242c2011-02-22 04:55:05 +00001168
Jordy Rosebd32bee2011-06-14 01:26:48 +00001169 if (strLengthNL && maxlenValNL) {
Ted Kremenek8bef8232012-01-26 21:29:00 +00001170 ProgramStateRef stateStringTooLong, stateStringNotTooLong;
Jordy Rose793bff32011-06-14 01:15:31 +00001171
Jordy Rosebd32bee2011-06-14 01:26:48 +00001172 // Check if the strLength is greater than the maxlen.
1173 llvm::tie(stateStringTooLong, stateStringNotTooLong) =
David Blaikie5251abe2013-02-20 05:52:05 +00001174 state->assume(C.getSValBuilder().evalBinOpNN(
1175 state, BO_GT, *strLengthNL, *maxlenValNL, cmpTy)
1176 .castAs<DefinedOrUnknownSVal>());
Jordy Rose793bff32011-06-14 01:15:31 +00001177
Jordy Rosebd32bee2011-06-14 01:26:48 +00001178 if (stateStringTooLong && !stateStringNotTooLong) {
1179 // If the string is longer than maxlen, return maxlen.
1180 result = *maxlenValNL;
1181 } else if (stateStringNotTooLong && !stateStringTooLong) {
1182 // If the string is shorter than maxlen, return its length.
1183 result = *strLengthNL;
Ted Kremenekbe4242c2011-02-22 04:55:05 +00001184 }
1185 }
1186
Jordy Rosebd32bee2011-06-14 01:26:48 +00001187 if (result.isUnknown()) {
1188 // If we don't have enough information for a comparison, there's
1189 // no guarantee the full string length will actually be returned.
1190 // All we know is the return value is the min of the string length
1191 // and the limit. This is better than nothing.
Ted Kremenek66c486f2012-08-22 06:26:15 +00001192 result = C.getSValBuilder().conjureSymbolVal(0, CE, LCtx, C.blockCount());
David Blaikie5251abe2013-02-20 05:52:05 +00001193 NonLoc resultNL = result.castAs<NonLoc>();
Jordy Rosebd32bee2011-06-14 01:26:48 +00001194
1195 if (strLengthNL) {
David Blaikie5251abe2013-02-20 05:52:05 +00001196 state = state->assume(C.getSValBuilder().evalBinOpNN(
1197 state, BO_LE, resultNL, *strLengthNL, cmpTy)
1198 .castAs<DefinedOrUnknownSVal>(), true);
Jordy Rosebd32bee2011-06-14 01:26:48 +00001199 }
1200
1201 if (maxlenValNL) {
David Blaikie5251abe2013-02-20 05:52:05 +00001202 state = state->assume(C.getSValBuilder().evalBinOpNN(
1203 state, BO_LE, resultNL, *maxlenValNL, cmpTy)
1204 .castAs<DefinedOrUnknownSVal>(), true);
Jordy Rosebd32bee2011-06-14 01:26:48 +00001205 }
1206 }
1207
1208 } else {
1209 // This is a plain strlen(), not strnlen().
David Blaikie5251abe2013-02-20 05:52:05 +00001210 result = strLength.castAs<DefinedOrUnknownSVal>();
Jordy Rosebd32bee2011-06-14 01:26:48 +00001211
1212 // If we don't know the length of the string, conjure a return
1213 // value, so it can be used in constraints, at least.
1214 if (result.isUnknown()) {
Ted Kremenek66c486f2012-08-22 06:26:15 +00001215 result = C.getSValBuilder().conjureSymbolVal(0, CE, LCtx, C.blockCount());
Jordy Rosebd32bee2011-06-14 01:26:48 +00001216 }
Jordy Rose19c5dd12010-07-27 01:37:31 +00001217 }
Jordy Rosebd32bee2011-06-14 01:26:48 +00001218
1219 // Bind the return value.
1220 assert(!result.isUnknown() && "Should have conjured a value by now");
Ted Kremenek5eca4822012-01-06 22:09:28 +00001221 state = state->BindExpr(CE, LCtx, result);
Anna Zaks0bd6b112011-10-26 21:06:34 +00001222 C.addTransition(state);
Jordy Rose19c5dd12010-07-27 01:37:31 +00001223}
1224
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001225void CStringChecker::evalStrcpy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001226 if (CE->getNumArgs() < 2)
1227 return;
1228
Jordy Rosee64f3112010-08-16 07:51:42 +00001229 // char *strcpy(char *restrict dst, const char *restrict src);
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001230 evalStrcpyCommon(C, CE,
1231 /* returnEnd = */ false,
1232 /* isBounded = */ false,
1233 /* isAppending = */ false);
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001234}
1235
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001236void CStringChecker::evalStrncpy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001237 if (CE->getNumArgs() < 3)
1238 return;
1239
Jordy Rosec1525862011-06-04 00:05:23 +00001240 // char *strncpy(char *restrict dst, const char *restrict src, size_t n);
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001241 evalStrcpyCommon(C, CE,
1242 /* returnEnd = */ false,
1243 /* isBounded = */ true,
1244 /* isAppending = */ false);
Jordy Rosee64f3112010-08-16 07:51:42 +00001245}
1246
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001247void CStringChecker::evalStpcpy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001248 if (CE->getNumArgs() < 2)
1249 return;
1250
Jordy Rosee64f3112010-08-16 07:51:42 +00001251 // char *stpcpy(char *restrict dst, const char *restrict src);
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001252 evalStrcpyCommon(C, CE,
1253 /* returnEnd = */ true,
1254 /* isBounded = */ false,
1255 /* isAppending = */ false);
1256}
1257
1258void CStringChecker::evalStrcat(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001259 if (CE->getNumArgs() < 2)
1260 return;
1261
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001262 //char *strcat(char *restrict s1, const char *restrict s2);
1263 evalStrcpyCommon(C, CE,
1264 /* returnEnd = */ false,
1265 /* isBounded = */ false,
1266 /* isAppending = */ true);
1267}
1268
1269void CStringChecker::evalStrncat(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001270 if (CE->getNumArgs() < 3)
1271 return;
1272
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001273 //char *strncat(char *restrict s1, const char *restrict s2, size_t n);
1274 evalStrcpyCommon(C, CE,
1275 /* returnEnd = */ false,
1276 /* isBounded = */ true,
1277 /* isAppending = */ true);
Jordy Rosee64f3112010-08-16 07:51:42 +00001278}
1279
Ted Kremenek9c149532010-12-01 21:57:22 +00001280void CStringChecker::evalStrcpyCommon(CheckerContext &C, const CallExpr *CE,
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001281 bool returnEnd, bool isBounded,
1282 bool isAppending) const {
Jordy Rose9e49d9f2011-06-20 02:06:40 +00001283 CurrentFunctionDescription = "string copy function";
Ted Kremenek8bef8232012-01-26 21:29:00 +00001284 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001285 const LocationContext *LCtx = C.getLocationContext();
Jordy Rosee64f3112010-08-16 07:51:42 +00001286
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001287 // Check that the destination is non-null.
Jordy Rosee64f3112010-08-16 07:51:42 +00001288 const Expr *Dst = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001289 SVal DstVal = state->getSVal(Dst, LCtx);
Jordy Rosee64f3112010-08-16 07:51:42 +00001290
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001291 state = checkNonNull(C, state, Dst, DstVal);
Jordy Rosee64f3112010-08-16 07:51:42 +00001292 if (!state)
1293 return;
1294
1295 // Check that the source is non-null.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001296 const Expr *srcExpr = CE->getArg(1);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001297 SVal srcVal = state->getSVal(srcExpr, LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001298 state = checkNonNull(C, state, srcExpr, srcVal);
Jordy Rosee64f3112010-08-16 07:51:42 +00001299 if (!state)
1300 return;
1301
1302 // Get the string length of the source.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001303 SVal strLength = getCStringLength(C, state, srcExpr, srcVal);
Jordy Rosee64f3112010-08-16 07:51:42 +00001304
1305 // If the source isn't a valid C string, give up.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001306 if (strLength.isUndef())
Jordy Rosee64f3112010-08-16 07:51:42 +00001307 return;
1308
Jordy Rosed5af0e12011-06-15 05:52:56 +00001309 SValBuilder &svalBuilder = C.getSValBuilder();
1310 QualType cmpTy = svalBuilder.getConditionType();
Jordy Rose8912aae2011-06-20 21:55:40 +00001311 QualType sizeTy = svalBuilder.getContext().getSizeType();
Jordy Rosed5af0e12011-06-15 05:52:56 +00001312
Jordy Rose8912aae2011-06-20 21:55:40 +00001313 // These two values allow checking two kinds of errors:
1314 // - actual overflows caused by a source that doesn't fit in the destination
1315 // - potential overflows caused by a bound that could exceed the destination
Jordy Rosed5af0e12011-06-15 05:52:56 +00001316 SVal amountCopied = UnknownVal();
Jordy Rose8912aae2011-06-20 21:55:40 +00001317 SVal maxLastElementIndex = UnknownVal();
1318 const char *boundWarning = NULL;
Jordy Rosed5af0e12011-06-15 05:52:56 +00001319
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001320 // If the function is strncpy, strncat, etc... it is bounded.
1321 if (isBounded) {
1322 // Get the max number of characters to copy.
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001323 const Expr *lenExpr = CE->getArg(2);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001324 SVal lenVal = state->getSVal(lenExpr, LCtx);
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001325
Jordy Rosed5af0e12011-06-15 05:52:56 +00001326 // Protect against misdeclared strncpy().
Jordy Rose8912aae2011-06-20 21:55:40 +00001327 lenVal = svalBuilder.evalCast(lenVal, sizeTy, lenExpr->getType());
Jordy Rosed5af0e12011-06-15 05:52:56 +00001328
David Blaikiedc84cd52013-02-20 22:23:23 +00001329 Optional<NonLoc> strLengthNL = strLength.getAs<NonLoc>();
1330 Optional<NonLoc> lenValNL = lenVal.getAs<NonLoc>();
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001331
Jordy Rosed5af0e12011-06-15 05:52:56 +00001332 // If we know both values, we might be able to figure out how much
1333 // we're copying.
1334 if (strLengthNL && lenValNL) {
Ted Kremenek8bef8232012-01-26 21:29:00 +00001335 ProgramStateRef stateSourceTooLong, stateSourceNotTooLong;
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001336
Jordy Rosed5af0e12011-06-15 05:52:56 +00001337 // Check if the max number to copy is less than the length of the src.
Jordy Rose8912aae2011-06-20 21:55:40 +00001338 // If the bound is equal to the source length, strncpy won't null-
1339 // terminate the result!
David Blaikie5251abe2013-02-20 05:52:05 +00001340 llvm::tie(stateSourceTooLong, stateSourceNotTooLong) = state->assume(
1341 svalBuilder.evalBinOpNN(state, BO_GE, *strLengthNL, *lenValNL, cmpTy)
1342 .castAs<DefinedOrUnknownSVal>());
Jordy Rosed5af0e12011-06-15 05:52:56 +00001343
1344 if (stateSourceTooLong && !stateSourceNotTooLong) {
1345 // Max number to copy is less than the length of the src, so the actual
1346 // strLength copied is the max number arg.
1347 state = stateSourceTooLong;
1348 amountCopied = lenVal;
1349
1350 } else if (!stateSourceTooLong && stateSourceNotTooLong) {
1351 // The source buffer entirely fits in the bound.
1352 state = stateSourceNotTooLong;
1353 amountCopied = strLength;
1354 }
1355 }
1356
Jordy Rose5e5f1502011-06-20 03:49:16 +00001357 // We still want to know if the bound is known to be too large.
Jordy Rose8912aae2011-06-20 21:55:40 +00001358 if (lenValNL) {
1359 if (isAppending) {
1360 // For strncat, the check is strlen(dst) + lenVal < sizeof(dst)
1361
1362 // Get the string length of the destination. If the destination is
1363 // memory that can't have a string length, we shouldn't be copying
1364 // into it anyway.
1365 SVal dstStrLength = getCStringLength(C, state, Dst, DstVal);
1366 if (dstStrLength.isUndef())
1367 return;
1368
David Blaikiedc84cd52013-02-20 22:23:23 +00001369 if (Optional<NonLoc> dstStrLengthNL = dstStrLength.getAs<NonLoc>()) {
Jordy Rose8912aae2011-06-20 21:55:40 +00001370 maxLastElementIndex = svalBuilder.evalBinOpNN(state, BO_Add,
1371 *lenValNL,
1372 *dstStrLengthNL,
1373 sizeTy);
1374 boundWarning = "Size argument is greater than the free space in the "
1375 "destination buffer";
1376 }
1377
1378 } else {
1379 // For strncpy, this is just checking that lenVal <= sizeof(dst)
1380 // (Yes, strncpy and strncat differ in how they treat termination.
1381 // strncat ALWAYS terminates, but strncpy doesn't.)
Jordy Rose6e4244e2012-05-14 17:58:35 +00001382
1383 // We need a special case for when the copy size is zero, in which
1384 // case strncpy will do no work at all. Our bounds check uses n-1
1385 // as the last element accessed, so n == 0 is problematic.
1386 ProgramStateRef StateZeroSize, StateNonZeroSize;
1387 llvm::tie(StateZeroSize, StateNonZeroSize) =
1388 assumeZero(C, state, *lenValNL, sizeTy);
1389
1390 // If the size is known to be zero, we're done.
1391 if (StateZeroSize && !StateNonZeroSize) {
1392 StateZeroSize = StateZeroSize->BindExpr(CE, LCtx, DstVal);
1393 C.addTransition(StateZeroSize);
1394 return;
1395 }
1396
1397 // Otherwise, go ahead and figure out the last element we'll touch.
1398 // We don't record the non-zero assumption here because we can't
1399 // be sure. We won't warn on a possible zero.
David Blaikie5251abe2013-02-20 05:52:05 +00001400 NonLoc one = svalBuilder.makeIntVal(1, sizeTy).castAs<NonLoc>();
Jordy Rose8912aae2011-06-20 21:55:40 +00001401 maxLastElementIndex = svalBuilder.evalBinOpNN(state, BO_Sub, *lenValNL,
1402 one, sizeTy);
1403 boundWarning = "Size argument is greater than the length of the "
1404 "destination buffer";
1405 }
1406 }
Jordy Rose5e5f1502011-06-20 03:49:16 +00001407
Jordy Rosed5af0e12011-06-15 05:52:56 +00001408 // If we couldn't pin down the copy length, at least bound it.
Jordy Rose8912aae2011-06-20 21:55:40 +00001409 // FIXME: We should actually run this code path for append as well, but
1410 // right now it creates problems with constraints (since we can end up
1411 // trying to pass constraints from symbol to symbol).
1412 if (amountCopied.isUnknown() && !isAppending) {
Jordy Rosed5af0e12011-06-15 05:52:56 +00001413 // Try to get a "hypothetical" string length symbol, which we can later
1414 // set as a real value if that turns out to be the case.
1415 amountCopied = getCStringLength(C, state, lenExpr, srcVal, true);
1416 assert(!amountCopied.isUndef());
1417
David Blaikiedc84cd52013-02-20 22:23:23 +00001418 if (Optional<NonLoc> amountCopiedNL = amountCopied.getAs<NonLoc>()) {
Jordy Rosed5af0e12011-06-15 05:52:56 +00001419 if (lenValNL) {
1420 // amountCopied <= lenVal
1421 SVal copiedLessThanBound = svalBuilder.evalBinOpNN(state, BO_LE,
1422 *amountCopiedNL,
1423 *lenValNL,
1424 cmpTy);
David Blaikie5251abe2013-02-20 05:52:05 +00001425 state = state->assume(
1426 copiedLessThanBound.castAs<DefinedOrUnknownSVal>(), true);
Jordy Rosed5af0e12011-06-15 05:52:56 +00001427 if (!state)
1428 return;
1429 }
1430
1431 if (strLengthNL) {
1432 // amountCopied <= strlen(source)
1433 SVal copiedLessThanSrc = svalBuilder.evalBinOpNN(state, BO_LE,
1434 *amountCopiedNL,
1435 *strLengthNL,
1436 cmpTy);
David Blaikie5251abe2013-02-20 05:52:05 +00001437 state = state->assume(
1438 copiedLessThanSrc.castAs<DefinedOrUnknownSVal>(), true);
Jordy Rosed5af0e12011-06-15 05:52:56 +00001439 if (!state)
1440 return;
1441 }
1442 }
1443 }
1444
1445 } else {
1446 // The function isn't bounded. The amount copied should match the length
1447 // of the source buffer.
1448 amountCopied = strLength;
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001449 }
1450
Jordy Rosed5af0e12011-06-15 05:52:56 +00001451 assert(state);
1452
1453 // This represents the number of characters copied into the destination
1454 // buffer. (It may not actually be the strlen if the destination buffer
1455 // is not terminated.)
1456 SVal finalStrLength = UnknownVal();
1457
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001458 // If this is an appending function (strcat, strncat...) then set the
1459 // string length to strlen(src) + strlen(dst) since the buffer will
1460 // ultimately contain both.
1461 if (isAppending) {
Jordy Rose1e022412011-06-16 05:51:02 +00001462 // Get the string length of the destination. If the destination is memory
1463 // that can't have a string length, we shouldn't be copying into it anyway.
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001464 SVal dstStrLength = getCStringLength(C, state, Dst, DstVal);
1465 if (dstStrLength.isUndef())
1466 return;
1467
David Blaikiedc84cd52013-02-20 22:23:23 +00001468 Optional<NonLoc> srcStrLengthNL = amountCopied.getAs<NonLoc>();
1469 Optional<NonLoc> dstStrLengthNL = dstStrLength.getAs<NonLoc>();
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001470
Jordy Rosed5af0e12011-06-15 05:52:56 +00001471 // If we know both string lengths, we might know the final string length.
1472 if (srcStrLengthNL && dstStrLengthNL) {
1473 // Make sure the two lengths together don't overflow a size_t.
1474 state = checkAdditionOverflow(C, state, *srcStrLengthNL, *dstStrLengthNL);
1475 if (!state)
1476 return;
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001477
Jordy Rosed5af0e12011-06-15 05:52:56 +00001478 finalStrLength = svalBuilder.evalBinOpNN(state, BO_Add, *srcStrLengthNL,
1479 *dstStrLengthNL, sizeTy);
1480 }
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001481
Jordy Rosed5af0e12011-06-15 05:52:56 +00001482 // If we couldn't get a single value for the final string length,
1483 // we can at least bound it by the individual lengths.
1484 if (finalStrLength.isUnknown()) {
1485 // Try to get a "hypothetical" string length symbol, which we can later
1486 // set as a real value if that turns out to be the case.
1487 finalStrLength = getCStringLength(C, state, CE, DstVal, true);
1488 assert(!finalStrLength.isUndef());
1489
David Blaikiedc84cd52013-02-20 22:23:23 +00001490 if (Optional<NonLoc> finalStrLengthNL = finalStrLength.getAs<NonLoc>()) {
Jordy Rosed5af0e12011-06-15 05:52:56 +00001491 if (srcStrLengthNL) {
1492 // finalStrLength >= srcStrLength
1493 SVal sourceInResult = svalBuilder.evalBinOpNN(state, BO_GE,
1494 *finalStrLengthNL,
1495 *srcStrLengthNL,
1496 cmpTy);
David Blaikie5251abe2013-02-20 05:52:05 +00001497 state = state->assume(sourceInResult.castAs<DefinedOrUnknownSVal>(),
Jordy Rosed5af0e12011-06-15 05:52:56 +00001498 true);
1499 if (!state)
1500 return;
1501 }
1502
1503 if (dstStrLengthNL) {
1504 // finalStrLength >= dstStrLength
1505 SVal destInResult = svalBuilder.evalBinOpNN(state, BO_GE,
1506 *finalStrLengthNL,
1507 *dstStrLengthNL,
1508 cmpTy);
David Blaikie5251abe2013-02-20 05:52:05 +00001509 state =
1510 state->assume(destInResult.castAs<DefinedOrUnknownSVal>(), true);
Jordy Rosed5af0e12011-06-15 05:52:56 +00001511 if (!state)
1512 return;
1513 }
1514 }
1515 }
1516
1517 } else {
1518 // Otherwise, this is a copy-over function (strcpy, strncpy, ...), and
1519 // the final string length will match the input string length.
1520 finalStrLength = amountCopied;
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001521 }
1522
Jordy Rosed5af0e12011-06-15 05:52:56 +00001523 // The final result of the function will either be a pointer past the last
1524 // copied element, or a pointer to the start of the destination buffer.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001525 SVal Result = (returnEnd ? UnknownVal() : DstVal);
Jordy Rosee64f3112010-08-16 07:51:42 +00001526
Jordy Rosed5af0e12011-06-15 05:52:56 +00001527 assert(state);
1528
Jordy Rosee64f3112010-08-16 07:51:42 +00001529 // If the destination is a MemRegion, try to check for a buffer overflow and
1530 // record the new string length.
David Blaikiedc84cd52013-02-20 22:23:23 +00001531 if (Optional<loc::MemRegionVal> dstRegVal =
David Blaikie5251abe2013-02-20 05:52:05 +00001532 DstVal.getAs<loc::MemRegionVal>()) {
Jordy Rose8912aae2011-06-20 21:55:40 +00001533 QualType ptrTy = Dst->getType();
1534
1535 // If we have an exact value on a bounded copy, use that to check for
1536 // overflows, rather than our estimate about how much is actually copied.
1537 if (boundWarning) {
David Blaikiedc84cd52013-02-20 22:23:23 +00001538 if (Optional<NonLoc> maxLastNL = maxLastElementIndex.getAs<NonLoc>()) {
Jordy Rose8912aae2011-06-20 21:55:40 +00001539 SVal maxLastElement = svalBuilder.evalBinOpLN(state, BO_Add, *dstRegVal,
1540 *maxLastNL, ptrTy);
1541 state = CheckLocation(C, state, CE->getArg(2), maxLastElement,
1542 boundWarning);
1543 if (!state)
1544 return;
1545 }
1546 }
1547
1548 // Then, if the final length is known...
David Blaikiedc84cd52013-02-20 22:23:23 +00001549 if (Optional<NonLoc> knownStrLength = finalStrLength.getAs<NonLoc>()) {
Jordy Rosed5af0e12011-06-15 05:52:56 +00001550 SVal lastElement = svalBuilder.evalBinOpLN(state, BO_Add, *dstRegVal,
Jordy Rose8912aae2011-06-20 21:55:40 +00001551 *knownStrLength, ptrTy);
Jordy Rosee64f3112010-08-16 07:51:42 +00001552
Jordy Rose8912aae2011-06-20 21:55:40 +00001553 // ...and we haven't checked the bound, we'll check the actual copy.
1554 if (!boundWarning) {
1555 const char * const warningMsg =
1556 "String copy function overflows destination buffer";
1557 state = CheckLocation(C, state, Dst, lastElement, warningMsg);
1558 if (!state)
1559 return;
1560 }
Jordy Rosee64f3112010-08-16 07:51:42 +00001561
1562 // If this is a stpcpy-style copy, the last element is the return value.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001563 if (returnEnd)
1564 Result = lastElement;
Jordy Rosee64f3112010-08-16 07:51:42 +00001565 }
1566
1567 // Invalidate the destination. This must happen before we set the C string
1568 // length because invalidation will clear the length.
1569 // FIXME: Even if we can't perfectly model the copy, we should see if we
1570 // can use LazyCompoundVals to copy the source values into the destination.
1571 // This would probably remove any existing bindings past the end of the
1572 // string, but that's still an improvement over blank invalidation.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001573 state = InvalidateBuffer(C, state, Dst, *dstRegVal);
Jordy Rosee64f3112010-08-16 07:51:42 +00001574
Jordy Rose5e5f1502011-06-20 03:49:16 +00001575 // Set the C string length of the destination, if we know it.
Jordy Rose8912aae2011-06-20 21:55:40 +00001576 if (isBounded && !isAppending) {
1577 // strncpy is annoying in that it doesn't guarantee to null-terminate
1578 // the result string. If the original string didn't fit entirely inside
1579 // the bound (including the null-terminator), we don't know how long the
1580 // result is.
1581 if (amountCopied != strLength)
1582 finalStrLength = UnknownVal();
1583 }
1584 state = setCStringLength(state, dstRegVal->getRegion(), finalStrLength);
Jordy Rosee64f3112010-08-16 07:51:42 +00001585 }
1586
Jordy Rosed5af0e12011-06-15 05:52:56 +00001587 assert(state);
1588
Jordy Rosee64f3112010-08-16 07:51:42 +00001589 // If this is a stpcpy-style copy, but we were unable to check for a buffer
1590 // overflow, we still need a result. Conjure a return value.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001591 if (returnEnd && Result.isUnknown()) {
Ted Kremenek66c486f2012-08-22 06:26:15 +00001592 Result = svalBuilder.conjureSymbolVal(0, CE, LCtx, C.blockCount());
Jordy Rosee64f3112010-08-16 07:51:42 +00001593 }
1594
1595 // Set the return value.
Ted Kremenek5eca4822012-01-06 22:09:28 +00001596 state = state->BindExpr(CE, LCtx, Result);
Anna Zaks0bd6b112011-10-26 21:06:34 +00001597 C.addTransition(state);
Jordy Rosee64f3112010-08-16 07:51:42 +00001598}
1599
Lenny Maiorani318dd922011-04-12 17:08:43 +00001600void CStringChecker::evalStrcmp(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001601 if (CE->getNumArgs() < 2)
1602 return;
1603
Jordy Roseadc42d42011-06-16 07:13:34 +00001604 //int strcmp(const char *s1, const char *s2);
Lenny Maioranibd1d16a2011-04-28 15:09:11 +00001605 evalStrcmpCommon(C, CE, /* isBounded = */ false, /* ignoreCase = */ false);
Lenny Maiorani357f6ee2011-04-25 22:21:00 +00001606}
Lenny Maiorani318dd922011-04-12 17:08:43 +00001607
Lenny Maiorani357f6ee2011-04-25 22:21:00 +00001608void CStringChecker::evalStrncmp(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001609 if (CE->getNumArgs() < 3)
1610 return;
1611
Jordy Roseadc42d42011-06-16 07:13:34 +00001612 //int strncmp(const char *s1, const char *s2, size_t n);
Lenny Maioranibd1d16a2011-04-28 15:09:11 +00001613 evalStrcmpCommon(C, CE, /* isBounded = */ true, /* ignoreCase = */ false);
1614}
1615
1616void CStringChecker::evalStrcasecmp(CheckerContext &C,
1617 const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001618 if (CE->getNumArgs() < 2)
1619 return;
1620
Jordy Roseadc42d42011-06-16 07:13:34 +00001621 //int strcasecmp(const char *s1, const char *s2);
Lenny Maioranibd1d16a2011-04-28 15:09:11 +00001622 evalStrcmpCommon(C, CE, /* isBounded = */ false, /* ignoreCase = */ true);
Lenny Maiorani357f6ee2011-04-25 22:21:00 +00001623}
1624
Lenny Maiorani454fd2d2011-05-02 19:05:49 +00001625void CStringChecker::evalStrncasecmp(CheckerContext &C,
1626 const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001627 if (CE->getNumArgs() < 3)
1628 return;
1629
Jordy Roseadc42d42011-06-16 07:13:34 +00001630 //int strncasecmp(const char *s1, const char *s2, size_t n);
Lenny Maiorani454fd2d2011-05-02 19:05:49 +00001631 evalStrcmpCommon(C, CE, /* isBounded = */ true, /* ignoreCase = */ true);
1632}
1633
Lenny Maiorani357f6ee2011-04-25 22:21:00 +00001634void CStringChecker::evalStrcmpCommon(CheckerContext &C, const CallExpr *CE,
Lenny Maioranibd1d16a2011-04-28 15:09:11 +00001635 bool isBounded, bool ignoreCase) const {
Jordy Rose9e49d9f2011-06-20 02:06:40 +00001636 CurrentFunctionDescription = "string comparison function";
Ted Kremenek8bef8232012-01-26 21:29:00 +00001637 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001638 const LocationContext *LCtx = C.getLocationContext();
Lenny Maiorani318dd922011-04-12 17:08:43 +00001639
1640 // Check that the first string is non-null
1641 const Expr *s1 = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001642 SVal s1Val = state->getSVal(s1, LCtx);
Lenny Maiorani318dd922011-04-12 17:08:43 +00001643 state = checkNonNull(C, state, s1, s1Val);
1644 if (!state)
1645 return;
1646
1647 // Check that the second string is non-null.
1648 const Expr *s2 = CE->getArg(1);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001649 SVal s2Val = state->getSVal(s2, LCtx);
Lenny Maiorani318dd922011-04-12 17:08:43 +00001650 state = checkNonNull(C, state, s2, s2Val);
1651 if (!state)
1652 return;
1653
1654 // Get the string length of the first string or give up.
1655 SVal s1Length = getCStringLength(C, state, s1, s1Val);
1656 if (s1Length.isUndef())
1657 return;
1658
1659 // Get the string length of the second string or give up.
1660 SVal s2Length = getCStringLength(C, state, s2, s2Val);
1661 if (s2Length.isUndef())
1662 return;
1663
Jordy Roseadc42d42011-06-16 07:13:34 +00001664 // If we know the two buffers are the same, we know the result is 0.
1665 // First, get the two buffers' addresses. Another checker will have already
1666 // made sure they're not undefined.
David Blaikie5251abe2013-02-20 05:52:05 +00001667 DefinedOrUnknownSVal LV = s1Val.castAs<DefinedOrUnknownSVal>();
1668 DefinedOrUnknownSVal RV = s2Val.castAs<DefinedOrUnknownSVal>();
Lenny Maiorani318dd922011-04-12 17:08:43 +00001669
Jordy Roseadc42d42011-06-16 07:13:34 +00001670 // See if they are the same.
Lenny Maiorani318dd922011-04-12 17:08:43 +00001671 SValBuilder &svalBuilder = C.getSValBuilder();
Jordy Roseadc42d42011-06-16 07:13:34 +00001672 DefinedOrUnknownSVal SameBuf = svalBuilder.evalEQ(state, LV, RV);
Ted Kremenek8bef8232012-01-26 21:29:00 +00001673 ProgramStateRef StSameBuf, StNotSameBuf;
Jordy Roseadc42d42011-06-16 07:13:34 +00001674 llvm::tie(StSameBuf, StNotSameBuf) = state->assume(SameBuf);
Lenny Maiorani318dd922011-04-12 17:08:43 +00001675
Jordy Roseadc42d42011-06-16 07:13:34 +00001676 // If the two arguments might be the same buffer, we know the result is 0,
1677 // and we only need to check one size.
1678 if (StSameBuf) {
Ted Kremenek5eca4822012-01-06 22:09:28 +00001679 StSameBuf = StSameBuf->BindExpr(CE, LCtx,
1680 svalBuilder.makeZeroVal(CE->getType()));
Anna Zaks0bd6b112011-10-26 21:06:34 +00001681 C.addTransition(StSameBuf);
Jordy Roseadc42d42011-06-16 07:13:34 +00001682
1683 // If the two arguments are GUARANTEED to be the same, we're done!
1684 if (!StNotSameBuf)
1685 return;
1686 }
1687
1688 assert(StNotSameBuf);
1689 state = StNotSameBuf;
1690
1691 // At this point we can go about comparing the two buffers.
1692 // For now, we only do this if they're both known string literals.
1693
1694 // Attempt to extract string literals from both expressions.
1695 const StringLiteral *s1StrLiteral = getCStringLiteral(C, state, s1, s1Val);
1696 const StringLiteral *s2StrLiteral = getCStringLiteral(C, state, s2, s2Val);
1697 bool canComputeResult = false;
1698
1699 if (s1StrLiteral && s2StrLiteral) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001700 StringRef s1StrRef = s1StrLiteral->getString();
1701 StringRef s2StrRef = s2StrLiteral->getString();
Jordy Roseadc42d42011-06-16 07:13:34 +00001702
1703 if (isBounded) {
1704 // Get the max number of characters to compare.
1705 const Expr *lenExpr = CE->getArg(2);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001706 SVal lenVal = state->getSVal(lenExpr, LCtx);
Jordy Roseadc42d42011-06-16 07:13:34 +00001707
1708 // If the length is known, we can get the right substrings.
1709 if (const llvm::APSInt *len = svalBuilder.getKnownValue(state, lenVal)) {
1710 // Create substrings of each to compare the prefix.
1711 s1StrRef = s1StrRef.substr(0, (size_t)len->getZExtValue());
1712 s2StrRef = s2StrRef.substr(0, (size_t)len->getZExtValue());
1713 canComputeResult = true;
1714 }
1715 } else {
1716 // This is a normal, unbounded strcmp.
1717 canComputeResult = true;
1718 }
1719
1720 if (canComputeResult) {
1721 // Real strcmp stops at null characters.
1722 size_t s1Term = s1StrRef.find('\0');
Chris Lattner5f9e2722011-07-23 10:55:15 +00001723 if (s1Term != StringRef::npos)
Jordy Roseadc42d42011-06-16 07:13:34 +00001724 s1StrRef = s1StrRef.substr(0, s1Term);
1725
1726 size_t s2Term = s2StrRef.find('\0');
Chris Lattner5f9e2722011-07-23 10:55:15 +00001727 if (s2Term != StringRef::npos)
Jordy Roseadc42d42011-06-16 07:13:34 +00001728 s2StrRef = s2StrRef.substr(0, s2Term);
1729
1730 // Use StringRef's comparison methods to compute the actual result.
1731 int result;
1732
1733 if (ignoreCase) {
1734 // Compare string 1 to string 2 the same way strcasecmp() does.
1735 result = s1StrRef.compare_lower(s2StrRef);
1736 } else {
1737 // Compare string 1 to string 2 the same way strcmp() does.
1738 result = s1StrRef.compare(s2StrRef);
1739 }
1740
1741 // Build the SVal of the comparison and bind the return value.
1742 SVal resultVal = svalBuilder.makeIntVal(result, CE->getType());
Ted Kremenek5eca4822012-01-06 22:09:28 +00001743 state = state->BindExpr(CE, LCtx, resultVal);
Jordy Roseadc42d42011-06-16 07:13:34 +00001744 }
1745 }
1746
1747 if (!canComputeResult) {
1748 // Conjure a symbolic value. It's the best we can do.
Ted Kremenek66c486f2012-08-22 06:26:15 +00001749 SVal resultVal = svalBuilder.conjureSymbolVal(0, CE, LCtx, C.blockCount());
Ted Kremenek5eca4822012-01-06 22:09:28 +00001750 state = state->BindExpr(CE, LCtx, resultVal);
Jordy Roseadc42d42011-06-16 07:13:34 +00001751 }
1752
1753 // Record this as a possible path.
Anna Zaks0bd6b112011-10-26 21:06:34 +00001754 C.addTransition(state);
Lenny Maiorani318dd922011-04-12 17:08:43 +00001755}
1756
Jordan Roseaf226212013-04-22 23:18:42 +00001757void CStringChecker::evalStrsep(CheckerContext &C, const CallExpr *CE) const {
1758 //char *strsep(char **stringp, const char *delim);
1759 if (CE->getNumArgs() < 2)
1760 return;
1761
1762 // Sanity: does the search string parameter match the return type?
1763 const Expr *SearchStrPtr = CE->getArg(0);
1764 QualType CharPtrTy = SearchStrPtr->getType()->getPointeeType();
1765 if (CharPtrTy.isNull() ||
1766 CE->getType().getUnqualifiedType() != CharPtrTy.getUnqualifiedType())
1767 return;
1768
1769 CurrentFunctionDescription = "strsep()";
1770 ProgramStateRef State = C.getState();
1771 const LocationContext *LCtx = C.getLocationContext();
1772
1773 // Check that the search string pointer is non-null (though it may point to
1774 // a null string).
1775 SVal SearchStrVal = State->getSVal(SearchStrPtr, LCtx);
1776 State = checkNonNull(C, State, SearchStrPtr, SearchStrVal);
1777 if (!State)
1778 return;
1779
1780 // Check that the delimiter string is non-null.
1781 const Expr *DelimStr = CE->getArg(1);
1782 SVal DelimStrVal = State->getSVal(DelimStr, LCtx);
1783 State = checkNonNull(C, State, DelimStr, DelimStrVal);
1784 if (!State)
1785 return;
1786
1787 SValBuilder &SVB = C.getSValBuilder();
1788 SVal Result;
1789 if (Optional<Loc> SearchStrLoc = SearchStrVal.getAs<Loc>()) {
1790 // Get the current value of the search string pointer, as a char*.
1791 Result = State->getSVal(*SearchStrLoc, CharPtrTy);
1792
1793 // Invalidate the search string, representing the change of one delimiter
1794 // character to NUL.
1795 State = InvalidateBuffer(C, State, SearchStrPtr, Result);
1796
1797 // Overwrite the search string pointer. The new value is either an address
1798 // further along in the same string, or NULL if there are no more tokens.
1799 State = State->bindLoc(*SearchStrLoc,
1800 SVB.conjureSymbolVal(getTag(), CE, LCtx, CharPtrTy,
1801 C.blockCount()));
1802 } else {
1803 assert(SearchStrVal.isUnknown());
1804 // Conjure a symbolic value. It's the best we can do.
1805 Result = SVB.conjureSymbolVal(0, CE, LCtx, C.blockCount());
1806 }
1807
1808 // Set the return value, and finish.
1809 State = State->BindExpr(CE, LCtx, Result);
1810 C.addTransition(State);
1811}
1812
1813
Jordy Rosed325ffb2010-07-08 23:57:29 +00001814//===----------------------------------------------------------------------===//
Jordy Rosea5261542010-08-14 21:02:52 +00001815// The driver method, and other Checker callbacks.
Jordy Rosed325ffb2010-07-08 23:57:29 +00001816//===----------------------------------------------------------------------===//
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001817
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001818bool CStringChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
Anna Zaks998e2752012-02-17 22:35:26 +00001819 const FunctionDecl *FDecl = C.getCalleeDecl(CE);
1820
1821 if (!FDecl)
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001822 return false;
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001823
Jordan Roseaf226212013-04-22 23:18:42 +00001824 // FIXME: Poorly-factored string switches are slow.
Anna Zaks998e2752012-02-17 22:35:26 +00001825 FnCheck evalFunction = 0;
1826 if (C.isCLibraryFunction(FDecl, "memcpy"))
1827 evalFunction = &CStringChecker::evalMemcpy;
1828 else if (C.isCLibraryFunction(FDecl, "mempcpy"))
1829 evalFunction = &CStringChecker::evalMempcpy;
1830 else if (C.isCLibraryFunction(FDecl, "memcmp"))
1831 evalFunction = &CStringChecker::evalMemcmp;
1832 else if (C.isCLibraryFunction(FDecl, "memmove"))
1833 evalFunction = &CStringChecker::evalMemmove;
1834 else if (C.isCLibraryFunction(FDecl, "strcpy"))
1835 evalFunction = &CStringChecker::evalStrcpy;
1836 else if (C.isCLibraryFunction(FDecl, "strncpy"))
1837 evalFunction = &CStringChecker::evalStrncpy;
1838 else if (C.isCLibraryFunction(FDecl, "stpcpy"))
1839 evalFunction = &CStringChecker::evalStpcpy;
1840 else if (C.isCLibraryFunction(FDecl, "strcat"))
1841 evalFunction = &CStringChecker::evalStrcat;
1842 else if (C.isCLibraryFunction(FDecl, "strncat"))
1843 evalFunction = &CStringChecker::evalStrncat;
1844 else if (C.isCLibraryFunction(FDecl, "strlen"))
1845 evalFunction = &CStringChecker::evalstrLength;
1846 else if (C.isCLibraryFunction(FDecl, "strnlen"))
1847 evalFunction = &CStringChecker::evalstrnLength;
1848 else if (C.isCLibraryFunction(FDecl, "strcmp"))
1849 evalFunction = &CStringChecker::evalStrcmp;
1850 else if (C.isCLibraryFunction(FDecl, "strncmp"))
1851 evalFunction = &CStringChecker::evalStrncmp;
1852 else if (C.isCLibraryFunction(FDecl, "strcasecmp"))
1853 evalFunction = &CStringChecker::evalStrcasecmp;
1854 else if (C.isCLibraryFunction(FDecl, "strncasecmp"))
1855 evalFunction = &CStringChecker::evalStrncasecmp;
Jordan Roseaf226212013-04-22 23:18:42 +00001856 else if (C.isCLibraryFunction(FDecl, "strsep"))
1857 evalFunction = &CStringChecker::evalStrsep;
Anna Zaks998e2752012-02-17 22:35:26 +00001858 else if (C.isCLibraryFunction(FDecl, "bcopy"))
1859 evalFunction = &CStringChecker::evalBcopy;
1860 else if (C.isCLibraryFunction(FDecl, "bcmp"))
1861 evalFunction = &CStringChecker::evalMemcmp;
1862
Jordy Rosed325ffb2010-07-08 23:57:29 +00001863 // If the callee isn't a string function, let another checker handle it.
Ted Kremenek9c149532010-12-01 21:57:22 +00001864 if (!evalFunction)
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001865 return false;
1866
Jordy Rose9e49d9f2011-06-20 02:06:40 +00001867 // Make sure each function sets its own description.
1868 // (But don't bother in a release build.)
1869 assert(!(CurrentFunctionDescription = NULL));
1870
Jordy Rosed325ffb2010-07-08 23:57:29 +00001871 // Check and evaluate the call.
Ted Kremenek9c149532010-12-01 21:57:22 +00001872 (this->*evalFunction)(C, CE);
Anna Zaks57300762012-02-07 00:56:14 +00001873
1874 // If the evaluate call resulted in no change, chain to the next eval call
1875 // handler.
1876 // Note, the custom CString evaluation calls assume that basic safety
1877 // properties are held. However, if the user chooses to turn off some of these
1878 // checks, we ignore the issues and leave the call evaluation to a generic
1879 // handler.
1880 if (!C.isDifferent())
1881 return false;
1882
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001883 return true;
1884}
Jordy Rosea5261542010-08-14 21:02:52 +00001885
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001886void CStringChecker::checkPreStmt(const DeclStmt *DS, CheckerContext &C) const {
Jordy Rosea5261542010-08-14 21:02:52 +00001887 // Record string length for char a[] = "abc";
Ted Kremenek8bef8232012-01-26 21:29:00 +00001888 ProgramStateRef state = C.getState();
Jordy Rosea5261542010-08-14 21:02:52 +00001889
1890 for (DeclStmt::const_decl_iterator I = DS->decl_begin(), E = DS->decl_end();
1891 I != E; ++I) {
1892 const VarDecl *D = dyn_cast<VarDecl>(*I);
1893 if (!D)
1894 continue;
1895
1896 // FIXME: Handle array fields of structs.
1897 if (!D->getType()->isArrayType())
1898 continue;
1899
1900 const Expr *Init = D->getInit();
1901 if (!Init)
1902 continue;
1903 if (!isa<StringLiteral>(Init))
1904 continue;
1905
Anna Zaks39ac1872011-10-26 21:06:44 +00001906 Loc VarLoc = state->getLValue(D, C.getLocationContext());
Jordy Rosea5261542010-08-14 21:02:52 +00001907 const MemRegion *MR = VarLoc.getAsRegion();
1908 if (!MR)
1909 continue;
1910
Ted Kremenek5eca4822012-01-06 22:09:28 +00001911 SVal StrVal = state->getSVal(Init, C.getLocationContext());
Jordy Rosea5261542010-08-14 21:02:52 +00001912 assert(StrVal.isValid() && "Initializer string is unknown or undefined");
David Blaikie5251abe2013-02-20 05:52:05 +00001913 DefinedOrUnknownSVal strLength =
1914 getCStringLength(C, state, Init, StrVal).castAs<DefinedOrUnknownSVal>();
Jordy Rosea5261542010-08-14 21:02:52 +00001915
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001916 state = state->set<CStringLength>(MR, strLength);
Jordy Rosea5261542010-08-14 21:02:52 +00001917 }
1918
Anna Zaks0bd6b112011-10-26 21:06:34 +00001919 C.addTransition(state);
Jordy Rosea5261542010-08-14 21:02:52 +00001920}
1921
Ted Kremenek8bef8232012-01-26 21:29:00 +00001922bool CStringChecker::wantsRegionChangeUpdate(ProgramStateRef state) const {
Jordan Rose166d5022012-11-02 01:54:06 +00001923 CStringLengthTy Entries = state->get<CStringLength>();
Jordy Rosea5261542010-08-14 21:02:52 +00001924 return !Entries.isEmpty();
1925}
1926
Ted Kremenek8bef8232012-01-26 21:29:00 +00001927ProgramStateRef
1928CStringChecker::checkRegionChanges(ProgramStateRef state,
Anna Zaksbf53dfa2012-12-20 00:38:25 +00001929 const InvalidatedSymbols *,
Jordy Rose537716a2011-08-27 22:51:26 +00001930 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00001931 ArrayRef<const MemRegion *> Regions,
Jordan Rose740d4902012-07-02 19:27:35 +00001932 const CallEvent *Call) const {
Jordan Rose166d5022012-11-02 01:54:06 +00001933 CStringLengthTy Entries = state->get<CStringLength>();
Jordy Rosea5261542010-08-14 21:02:52 +00001934 if (Entries.isEmpty())
1935 return state;
1936
1937 llvm::SmallPtrSet<const MemRegion *, 8> Invalidated;
1938 llvm::SmallPtrSet<const MemRegion *, 32> SuperRegions;
1939
1940 // First build sets for the changed regions and their super-regions.
Jordy Rose537716a2011-08-27 22:51:26 +00001941 for (ArrayRef<const MemRegion *>::iterator
1942 I = Regions.begin(), E = Regions.end(); I != E; ++I) {
1943 const MemRegion *MR = *I;
Jordy Rosea5261542010-08-14 21:02:52 +00001944 Invalidated.insert(MR);
1945
1946 SuperRegions.insert(MR);
1947 while (const SubRegion *SR = dyn_cast<SubRegion>(MR)) {
1948 MR = SR->getSuperRegion();
1949 SuperRegions.insert(MR);
1950 }
1951 }
1952
Jordan Rose166d5022012-11-02 01:54:06 +00001953 CStringLengthTy::Factory &F = state->get_context<CStringLength>();
Jordy Rosea5261542010-08-14 21:02:52 +00001954
1955 // Then loop over the entries in the current state.
Jordan Rose166d5022012-11-02 01:54:06 +00001956 for (CStringLengthTy::iterator I = Entries.begin(),
Jordy Rosea5261542010-08-14 21:02:52 +00001957 E = Entries.end(); I != E; ++I) {
1958 const MemRegion *MR = I.getKey();
1959
1960 // Is this entry for a super-region of a changed region?
1961 if (SuperRegions.count(MR)) {
Ted Kremenek3baf6722010-11-24 00:54:37 +00001962 Entries = F.remove(Entries, MR);
Jordy Rosea5261542010-08-14 21:02:52 +00001963 continue;
1964 }
1965
1966 // Is this entry for a sub-region of a changed region?
1967 const MemRegion *Super = MR;
1968 while (const SubRegion *SR = dyn_cast<SubRegion>(Super)) {
1969 Super = SR->getSuperRegion();
1970 if (Invalidated.count(Super)) {
Ted Kremenek3baf6722010-11-24 00:54:37 +00001971 Entries = F.remove(Entries, MR);
Jordy Rosea5261542010-08-14 21:02:52 +00001972 break;
1973 }
1974 }
1975 }
1976
1977 return state->set<CStringLength>(Entries);
1978}
1979
Ted Kremenek8bef8232012-01-26 21:29:00 +00001980void CStringChecker::checkLiveSymbols(ProgramStateRef state,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001981 SymbolReaper &SR) const {
Jordy Rosea5261542010-08-14 21:02:52 +00001982 // Mark all symbols in our string length map as valid.
Jordan Rose166d5022012-11-02 01:54:06 +00001983 CStringLengthTy Entries = state->get<CStringLength>();
Jordy Rosea5261542010-08-14 21:02:52 +00001984
Jordan Rose166d5022012-11-02 01:54:06 +00001985 for (CStringLengthTy::iterator I = Entries.begin(), E = Entries.end();
Jordy Rosea5261542010-08-14 21:02:52 +00001986 I != E; ++I) {
1987 SVal Len = I.getData();
Jordy Rosed5af0e12011-06-15 05:52:56 +00001988
Anna Zaks1d1d5152011-12-06 23:12:33 +00001989 for (SymExpr::symbol_iterator si = Len.symbol_begin(),
1990 se = Len.symbol_end(); si != se; ++si)
Jordy Rosed5af0e12011-06-15 05:52:56 +00001991 SR.markInUse(*si);
Jordy Rosea5261542010-08-14 21:02:52 +00001992 }
1993}
1994
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001995void CStringChecker::checkDeadSymbols(SymbolReaper &SR,
1996 CheckerContext &C) const {
Jordy Rosea5261542010-08-14 21:02:52 +00001997 if (!SR.hasDeadSymbols())
1998 return;
1999
Ted Kremenek8bef8232012-01-26 21:29:00 +00002000 ProgramStateRef state = C.getState();
Jordan Rose166d5022012-11-02 01:54:06 +00002001 CStringLengthTy Entries = state->get<CStringLength>();
Jordy Rosea5261542010-08-14 21:02:52 +00002002 if (Entries.isEmpty())
2003 return;
2004
Jordan Rose166d5022012-11-02 01:54:06 +00002005 CStringLengthTy::Factory &F = state->get_context<CStringLength>();
2006 for (CStringLengthTy::iterator I = Entries.begin(), E = Entries.end();
Jordy Rosea5261542010-08-14 21:02:52 +00002007 I != E; ++I) {
2008 SVal Len = I.getData();
2009 if (SymbolRef Sym = Len.getAsSymbol()) {
2010 if (SR.isDead(Sym))
Ted Kremenek3baf6722010-11-24 00:54:37 +00002011 Entries = F.remove(Entries, I.getKey());
Jordy Rosea5261542010-08-14 21:02:52 +00002012 }
2013 }
2014
2015 state = state->set<CStringLength>(Entries);
Anna Zaks0bd6b112011-10-26 21:06:34 +00002016 C.addTransition(state);
Jordy Rosea5261542010-08-14 21:02:52 +00002017}
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00002018
Anna Zaks57300762012-02-07 00:56:14 +00002019#define REGISTER_CHECKER(name) \
2020void ento::register##name(CheckerManager &mgr) {\
2021 static CStringChecker *TheChecker = 0; \
2022 if (TheChecker == 0) \
2023 TheChecker = mgr.registerChecker<CStringChecker>(); \
2024 TheChecker->Filter.Check##name = true; \
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00002025}
Anna Zaks57300762012-02-07 00:56:14 +00002026
2027REGISTER_CHECKER(CStringNullArg)
2028REGISTER_CHECKER(CStringOutOfBounds)
2029REGISTER_CHECKER(CStringBufferOverlap)
2030REGISTER_CHECKER(CStringNotNullTerm)
Anna Zaksf0dfc9c2012-02-17 22:35:31 +00002031
2032void ento::registerCStringCheckerBasic(CheckerManager &Mgr) {
2033 registerCStringNullArg(Mgr);
2034}