blob: 3c5cf615c8e7bd6c7dc704416a9ce08b8ec06a58 [file] [log] [blame]
Anna Zakscc925212011-10-11 16:49:54 +00001//= CStringChecker.cpp - Checks calls to C string functions --------*- C++ -*-//
Jordy Rose134a2362010-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 Kyrtzidis2d3905f2011-02-15 21:25:03 +000015#include "ClangSACheckers.h"
Anna Zakse56167e2012-02-17 22:35:31 +000016#include "InterCheckerAPI.h"
Jordan Rose4938f272013-02-09 10:09:43 +000017#include "clang/Basic/CharInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
Argyrios Kyrtzidis6a5674f2011-03-01 01:16:21 +000019#include "clang/StaticAnalyzer/Core/Checker.h"
Argyrios Kyrtzidis507ff532011-02-17 21:39:17 +000020#include "clang/StaticAnalyzer/Core/CheckerManager.h"
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +000021#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
Ted Kremenek001fd5b2011-08-15 22:09:50 +000022#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
Benjamin Kramer3307c5082012-02-04 12:31:12 +000023#include "llvm/ADT/STLExtras.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "llvm/ADT/SmallString.h"
Jordy Rose134a2362010-07-06 23:11:01 +000025#include "llvm/ADT/StringSwitch.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000026#include "llvm/Support/raw_ostream.h"
Jordy Rose134a2362010-07-06 23:11:01 +000027
28using namespace clang;
Ted Kremenek98857c92010-12-23 07:20:52 +000029using namespace ento;
Jordy Rose134a2362010-07-06 23:11:01 +000030
31namespace {
Argyrios Kyrtzidis6a5674f2011-03-01 01:16:21 +000032class CStringChecker : public Checker< eval::Call,
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +000033 check::PreStmt<DeclStmt>,
34 check::LiveSymbols,
35 check::DeadSymbols,
36 check::RegionChanges
37 > {
Anna Zakse0c7c272012-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 Rosedceb0cf2011-06-20 02:06:40 +000044 mutable const char *CurrentFunctionDescription;
45
Jordy Rose134a2362010-07-06 23:11:01 +000046public:
Anna Zakse0c7c272012-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;
Alexander Kornienko4aca9b12014-02-11 21:49:21 +000054
55 CheckName CheckNameCStringNullArg;
56 CheckName CheckNameCStringOutOfBounds;
57 CheckName CheckNameCStringBufferOverlap;
58 CheckName CheckNameCStringNotNullTerm;
Anna Zakse0c7c272012-02-07 00:56:14 +000059 };
60
61 CStringChecksFilter Filter;
62
Jordy Rose134a2362010-07-06 23:11:01 +000063 static void *getTag() { static int tag; return &tag; }
64
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +000065 bool evalCall(const CallExpr *CE, CheckerContext &C) const;
66 void checkPreStmt(const DeclStmt *DS, CheckerContext &C) const;
Ted Kremenek49b1e382012-01-26 21:29:00 +000067 void checkLiveSymbols(ProgramStateRef state, SymbolReaper &SR) const;
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +000068 void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const;
Ted Kremenek49b1e382012-01-26 21:29:00 +000069 bool wantsRegionChangeUpdate(ProgramStateRef state) const;
Jordy Rose2a2e21c2010-08-14 21:02:52 +000070
Ted Kremenek49b1e382012-01-26 21:29:00 +000071 ProgramStateRef
72 checkRegionChanges(ProgramStateRef state,
Anna Zaksdc154152012-12-20 00:38:25 +000073 const InvalidatedSymbols *,
Jordy Rose1fad6632011-08-27 22:51:26 +000074 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks3d348342012-02-14 21:55:24 +000075 ArrayRef<const MemRegion *> Regions,
Jordan Rose742920c2012-07-02 19:27:35 +000076 const CallEvent *Call) const;
Jordy Rose134a2362010-07-06 23:11:01 +000077
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +000078 typedef void (CStringChecker::*FnCheck)(CheckerContext &,
79 const CallExpr *) const;
Jordy Rose134a2362010-07-06 23:11:01 +000080
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +000081 void evalMemcpy(CheckerContext &C, const CallExpr *CE) const;
Lenny Maiorani79d74142011-03-31 21:36:53 +000082 void evalMempcpy(CheckerContext &C, const CallExpr *CE) const;
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +000083 void evalMemmove(CheckerContext &C, const CallExpr *CE) const;
84 void evalBcopy(CheckerContext &C, const CallExpr *CE) const;
Lenny Maiorani79d74142011-03-31 21:36:53 +000085 void evalCopyCommon(CheckerContext &C, const CallExpr *CE,
Ted Kremenek49b1e382012-01-26 21:29:00 +000086 ProgramStateRef state,
Ted Kremenek001fd5b2011-08-15 22:09:50 +000087 const Expr *Size,
88 const Expr *Source,
89 const Expr *Dest,
Lenny Maiorani79d74142011-03-31 21:36:53 +000090 bool Restricted = false,
91 bool IsMempcpy = false) const;
Jordy Rosed5d2e502010-07-08 23:57:29 +000092
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +000093 void evalMemcmp(CheckerContext &C, const CallExpr *CE) const;
Jordy Rose134a2362010-07-06 23:11:01 +000094
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +000095 void evalstrLength(CheckerContext &C, const CallExpr *CE) const;
96 void evalstrnLength(CheckerContext &C, const CallExpr *CE) const;
Ted Kremenek001fd5b2011-08-15 22:09:50 +000097 void evalstrLengthCommon(CheckerContext &C,
98 const CallExpr *CE,
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +000099 bool IsStrnlen = false) const;
Jordy Roseb052e8f2010-07-27 01:37:31 +0000100
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000101 void evalStrcpy(CheckerContext &C, const CallExpr *CE) const;
102 void evalStrncpy(CheckerContext &C, const CallExpr *CE) const;
103 void evalStpcpy(CheckerContext &C, const CallExpr *CE) const;
Ted Kremenek001fd5b2011-08-15 22:09:50 +0000104 void evalStrcpyCommon(CheckerContext &C,
105 const CallExpr *CE,
106 bool returnEnd,
107 bool isBounded,
108 bool isAppending) const;
Lenny Maiorani467dbd52011-04-09 15:12:58 +0000109
110 void evalStrcat(CheckerContext &C, const CallExpr *CE) const;
111 void evalStrncat(CheckerContext &C, const CallExpr *CE) const;
Jordy Rose722f5582010-08-16 07:51:42 +0000112
Lenny Maioranif3539ad2011-04-12 17:08:43 +0000113 void evalStrcmp(CheckerContext &C, const CallExpr *CE) const;
Lenny Maioranie553e402011-04-25 22:21:00 +0000114 void evalStrncmp(CheckerContext &C, const CallExpr *CE) const;
Lenny Maiorani4af23c82011-04-28 15:09:11 +0000115 void evalStrcasecmp(CheckerContext &C, const CallExpr *CE) const;
Lenny Maiorani0b510272011-05-02 19:05:49 +0000116 void evalStrncasecmp(CheckerContext &C, const CallExpr *CE) const;
Ted Kremenek001fd5b2011-08-15 22:09:50 +0000117 void evalStrcmpCommon(CheckerContext &C,
118 const CallExpr *CE,
119 bool isBounded = false,
120 bool ignoreCase = false) const;
Lenny Maioranif3539ad2011-04-12 17:08:43 +0000121
Jordan Rose6e3cf2b2013-04-22 23:18:42 +0000122 void evalStrsep(CheckerContext &C, const CallExpr *CE) const;
123
Jordy Rose134a2362010-07-06 23:11:01 +0000124 // Utility methods
Ted Kremenek49b1e382012-01-26 21:29:00 +0000125 std::pair<ProgramStateRef , ProgramStateRef >
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000126 static assumeZero(CheckerContext &C,
Ted Kremenek49b1e382012-01-26 21:29:00 +0000127 ProgramStateRef state, SVal V, QualType Ty);
Jordy Rosed5d2e502010-07-08 23:57:29 +0000128
Ted Kremenek49b1e382012-01-26 21:29:00 +0000129 static ProgramStateRef setCStringLength(ProgramStateRef state,
Ted Kremenek001fd5b2011-08-15 22:09:50 +0000130 const MemRegion *MR,
131 SVal strLength);
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000132 static SVal getCStringLengthForRegion(CheckerContext &C,
Ted Kremenek49b1e382012-01-26 21:29:00 +0000133 ProgramStateRef &state,
Ted Kremenek001fd5b2011-08-15 22:09:50 +0000134 const Expr *Ex,
135 const MemRegion *MR,
Jordy Rose634c12d2011-06-15 05:52:56 +0000136 bool hypothetical);
Ted Kremenek001fd5b2011-08-15 22:09:50 +0000137 SVal getCStringLength(CheckerContext &C,
Ted Kremenek49b1e382012-01-26 21:29:00 +0000138 ProgramStateRef &state,
Ted Kremenek001fd5b2011-08-15 22:09:50 +0000139 const Expr *Ex,
140 SVal Buf,
Jordy Rose634c12d2011-06-15 05:52:56 +0000141 bool hypothetical = false) const;
Jordy Roseb052e8f2010-07-27 01:37:31 +0000142
Lenny Maioranif3539ad2011-04-12 17:08:43 +0000143 const StringLiteral *getCStringLiteral(CheckerContext &C,
Ted Kremenek49b1e382012-01-26 21:29:00 +0000144 ProgramStateRef &state,
Lenny Maioranif3539ad2011-04-12 17:08:43 +0000145 const Expr *expr,
146 SVal val) const;
147
Ted Kremenek49b1e382012-01-26 21:29:00 +0000148 static ProgramStateRef InvalidateBuffer(CheckerContext &C,
Anton Yartsev968c60a2013-11-17 09:18:48 +0000149 ProgramStateRef state,
150 const Expr *Ex, SVal V,
151 bool IsSourceBuffer);
Jordy Rose722f5582010-08-16 07:51:42 +0000152
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000153 static bool SummarizeRegion(raw_ostream &os, ASTContext &Ctx,
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000154 const MemRegion *MR);
Jordy Roseb052e8f2010-07-27 01:37:31 +0000155
156 // Re-usable checks
Ted Kremenek49b1e382012-01-26 21:29:00 +0000157 ProgramStateRef checkNonNull(CheckerContext &C,
158 ProgramStateRef state,
Ted Kremenek001fd5b2011-08-15 22:09:50 +0000159 const Expr *S,
160 SVal l) const;
Ted Kremenek49b1e382012-01-26 21:29:00 +0000161 ProgramStateRef CheckLocation(CheckerContext &C,
162 ProgramStateRef state,
Ted Kremenek001fd5b2011-08-15 22:09:50 +0000163 const Expr *S,
164 SVal l,
165 const char *message = NULL) const;
Ted Kremenek49b1e382012-01-26 21:29:00 +0000166 ProgramStateRef CheckBufferAccess(CheckerContext &C,
167 ProgramStateRef state,
Ted Kremenek001fd5b2011-08-15 22:09:50 +0000168 const Expr *Size,
169 const Expr *FirstBuf,
170 const Expr *SecondBuf,
171 const char *firstMessage = NULL,
172 const char *secondMessage = NULL,
173 bool WarnAboutSize = false) const;
174
Ted Kremenek49b1e382012-01-26 21:29:00 +0000175 ProgramStateRef CheckBufferAccess(CheckerContext &C,
176 ProgramStateRef state,
Ted Kremenek001fd5b2011-08-15 22:09:50 +0000177 const Expr *Size,
178 const Expr *Buf,
179 const char *message = NULL,
180 bool WarnAboutSize = false) const {
Jordy Rosedceb0cf2011-06-20 02:06:40 +0000181 // This is a convenience override.
Jordy Rose328deee2011-06-20 03:49:16 +0000182 return CheckBufferAccess(C, state, Size, Buf, NULL, message, NULL,
183 WarnAboutSize);
Jordy Rosedceb0cf2011-06-20 02:06:40 +0000184 }
Ted Kremenek49b1e382012-01-26 21:29:00 +0000185 ProgramStateRef CheckOverlap(CheckerContext &C,
186 ProgramStateRef state,
Ted Kremenek001fd5b2011-08-15 22:09:50 +0000187 const Expr *Size,
188 const Expr *First,
189 const Expr *Second) const;
190 void emitOverlapBug(CheckerContext &C,
Ted Kremenek49b1e382012-01-26 21:29:00 +0000191 ProgramStateRef state,
Ted Kremenek001fd5b2011-08-15 22:09:50 +0000192 const Stmt *First,
193 const Stmt *Second) const;
194
Ted Kremenek49b1e382012-01-26 21:29:00 +0000195 ProgramStateRef checkAdditionOverflow(CheckerContext &C,
196 ProgramStateRef state,
Ted Kremenek001fd5b2011-08-15 22:09:50 +0000197 NonLoc left,
198 NonLoc right) const;
Jordy Rose134a2362010-07-06 23:11:01 +0000199};
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000200
Jordy Rose134a2362010-07-06 23:11:01 +0000201} //end anonymous namespace
202
Jordan Rose0c153cb2012-11-02 01:54:06 +0000203REGISTER_MAP_WITH_PROGRAMSTATE(CStringLength, const MemRegion *, SVal)
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000204
Jordy Rosed5d2e502010-07-08 23:57:29 +0000205//===----------------------------------------------------------------------===//
206// Individual checks and utility methods.
207//===----------------------------------------------------------------------===//
208
Ted Kremenek49b1e382012-01-26 21:29:00 +0000209std::pair<ProgramStateRef , ProgramStateRef >
210CStringChecker::assumeZero(CheckerContext &C, ProgramStateRef state, SVal V,
Jordy Rosed5d2e502010-07-08 23:57:29 +0000211 QualType Ty) {
David Blaikie05785d12013-02-20 22:23:23 +0000212 Optional<DefinedSVal> val = V.getAs<DefinedSVal>();
Ted Kremenek90af9092010-12-02 07:49:45 +0000213 if (!val)
Ted Kremenek49b1e382012-01-26 21:29:00 +0000214 return std::pair<ProgramStateRef , ProgramStateRef >(state, state);
Jordy Rose33c829a2010-07-07 07:48:06 +0000215
Ted Kremenek90af9092010-12-02 07:49:45 +0000216 SValBuilder &svalBuilder = C.getSValBuilder();
217 DefinedOrUnknownSVal zero = svalBuilder.makeZeroVal(Ty);
218 return state->assume(svalBuilder.evalEQ(state, *val, zero));
Jordy Rosed5d2e502010-07-08 23:57:29 +0000219}
Jordy Rose33c829a2010-07-07 07:48:06 +0000220
Ted Kremenek49b1e382012-01-26 21:29:00 +0000221ProgramStateRef CStringChecker::checkNonNull(CheckerContext &C,
222 ProgramStateRef state,
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000223 const Expr *S, SVal l) const {
Jordy Rosed5d2e502010-07-08 23:57:29 +0000224 // If a previous check has failed, propagate the failure.
225 if (!state)
226 return NULL;
227
Ted Kremenek49b1e382012-01-26 21:29:00 +0000228 ProgramStateRef stateNull, stateNonNull;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000229 std::tie(stateNull, stateNonNull) = assumeZero(C, state, l, S->getType());
Jordy Rosed5d2e502010-07-08 23:57:29 +0000230
231 if (stateNull && !stateNonNull) {
Anna Zakse0c7c272012-02-07 00:56:14 +0000232 if (!Filter.CheckCStringNullArg)
233 return NULL;
234
Ted Kremenek750b7ac2010-12-20 21:19:09 +0000235 ExplodedNode *N = C.generateSink(stateNull);
Jordy Rose33c829a2010-07-07 07:48:06 +0000236 if (!N)
237 return NULL;
238
Jordy Rosed5d2e502010-07-08 23:57:29 +0000239 if (!BT_Null)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000240 BT_Null.reset(new BuiltinBug(
241 Filter.CheckNameCStringNullArg, categories::UnixAPI,
242 "Null pointer argument in call to byte string function"));
Jordy Rose33c829a2010-07-07 07:48:06 +0000243
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000244 SmallString<80> buf;
Jordy Rosedceb0cf2011-06-20 02:06:40 +0000245 llvm::raw_svector_ostream os(buf);
246 assert(CurrentFunctionDescription);
247 os << "Null pointer argument in call to " << CurrentFunctionDescription;
248
Jordy Rose33c829a2010-07-07 07:48:06 +0000249 // Generate a report for this bug.
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000250 BuiltinBug *BT = static_cast<BuiltinBug*>(BT_Null.get());
Anna Zaks3a6bdf82011-08-17 23:00:25 +0000251 BugReport *report = new BugReport(*BT, os.str(), N);
Jordy Rose33c829a2010-07-07 07:48:06 +0000252
253 report->addRange(S->getSourceRange());
Jordan Rosea0f7d352012-08-28 00:50:51 +0000254 bugreporter::trackNullOrUndefValue(N, S, *report);
Jordan Rosee10d5a72012-11-02 01:53:40 +0000255 C.emitReport(report);
Jordy Rose33c829a2010-07-07 07:48:06 +0000256 return NULL;
257 }
258
259 // From here on, assume that the value is non-null.
Jordy Rosed5d2e502010-07-08 23:57:29 +0000260 assert(stateNonNull);
261 return stateNonNull;
Jordy Rose33c829a2010-07-07 07:48:06 +0000262}
263
Jordy Rose134a2362010-07-06 23:11:01 +0000264// FIXME: This was originally copied from ArrayBoundChecker.cpp. Refactor?
Ted Kremenek49b1e382012-01-26 21:29:00 +0000265ProgramStateRef CStringChecker::CheckLocation(CheckerContext &C,
266 ProgramStateRef state,
Jordy Rose722f5582010-08-16 07:51:42 +0000267 const Expr *S, SVal l,
Jordy Rosedceb0cf2011-06-20 02:06:40 +0000268 const char *warningMsg) const {
Jordy Rosed5d2e502010-07-08 23:57:29 +0000269 // If a previous check has failed, propagate the failure.
270 if (!state)
271 return NULL;
272
Jordy Rose134a2362010-07-06 23:11:01 +0000273 // Check for out of bound array element access.
274 const MemRegion *R = l.getAsRegion();
275 if (!R)
276 return state;
277
Jordy Rose134a2362010-07-06 23:11:01 +0000278 const ElementRegion *ER = dyn_cast<ElementRegion>(R);
279 if (!ER)
280 return state;
281
Zhongxing Xu8de0a3d2010-08-11 06:10:55 +0000282 assert(ER->getValueType() == C.getASTContext().CharTy &&
Jordy Rose134a2362010-07-06 23:11:01 +0000283 "CheckLocation should only be called with char* ElementRegions");
284
285 // Get the size of the array.
Ted Kremenek90af9092010-12-02 07:49:45 +0000286 const SubRegion *superReg = cast<SubRegion>(ER->getSuperRegion());
287 SValBuilder &svalBuilder = C.getSValBuilder();
Jordy Rose455bd582011-06-16 05:51:02 +0000288 SVal Extent =
289 svalBuilder.convertToArrayIndex(superReg->getExtent(svalBuilder));
David Blaikie2fdacbc2013-02-20 05:52:05 +0000290 DefinedOrUnknownSVal Size = Extent.castAs<DefinedOrUnknownSVal>();
Jordy Rose134a2362010-07-06 23:11:01 +0000291
292 // Get the index of the accessed element.
David Blaikie87396b92013-02-21 22:23:56 +0000293 DefinedOrUnknownSVal Idx = ER->getIndex().castAs<DefinedOrUnknownSVal>();
Jordy Rose134a2362010-07-06 23:11:01 +0000294
Ted Kremenek49b1e382012-01-26 21:29:00 +0000295 ProgramStateRef StInBound = state->assumeInBound(Idx, Size, true);
296 ProgramStateRef StOutBound = state->assumeInBound(Idx, Size, false);
Jordy Rose134a2362010-07-06 23:11:01 +0000297 if (StOutBound && !StInBound) {
Ted Kremenek750b7ac2010-12-20 21:19:09 +0000298 ExplodedNode *N = C.generateSink(StOutBound);
Jordy Rose134a2362010-07-06 23:11:01 +0000299 if (!N)
300 return NULL;
301
Jordy Rosedceb0cf2011-06-20 02:06:40 +0000302 if (!BT_Bounds) {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000303 BT_Bounds.reset(new BuiltinBug(
304 Filter.CheckNameCStringOutOfBounds, "Out-of-bound array access",
305 "Byte string function accesses out-of-bound array element"));
Jordy Rosedceb0cf2011-06-20 02:06:40 +0000306 }
307 BuiltinBug *BT = static_cast<BuiltinBug*>(BT_Bounds.get());
308
309 // Generate a report for this bug.
Anna Zaks3a6bdf82011-08-17 23:00:25 +0000310 BugReport *report;
Jordy Rosedceb0cf2011-06-20 02:06:40 +0000311 if (warningMsg) {
Anna Zaks3a6bdf82011-08-17 23:00:25 +0000312 report = new BugReport(*BT, warningMsg, N);
Jordy Rose722f5582010-08-16 07:51:42 +0000313 } else {
Jordy Rosedceb0cf2011-06-20 02:06:40 +0000314 assert(CurrentFunctionDescription);
315 assert(CurrentFunctionDescription[0] != '\0');
316
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000317 SmallString<80> buf;
Jordy Rosedceb0cf2011-06-20 02:06:40 +0000318 llvm::raw_svector_ostream os(buf);
Jordan Rose4938f272013-02-09 10:09:43 +0000319 os << toUppercase(CurrentFunctionDescription[0])
Jordy Rosedceb0cf2011-06-20 02:06:40 +0000320 << &CurrentFunctionDescription[1]
321 << " accesses out-of-bound array element";
Anna Zaks3a6bdf82011-08-17 23:00:25 +0000322 report = new BugReport(*BT, os.str(), N);
Jordy Rose722f5582010-08-16 07:51:42 +0000323 }
Jordy Rose134a2362010-07-06 23:11:01 +0000324
325 // FIXME: It would be nice to eventually make this diagnostic more clear,
326 // e.g., by referencing the original declaration or by saying *why* this
327 // reference is outside the range.
328
Jordy Rose134a2362010-07-06 23:11:01 +0000329 report->addRange(S->getSourceRange());
Jordan Rosee10d5a72012-11-02 01:53:40 +0000330 C.emitReport(report);
Jordy Rose134a2362010-07-06 23:11:01 +0000331 return NULL;
332 }
333
334 // Array bound check succeeded. From this point forward the array bound
335 // should always succeed.
336 return StInBound;
337}
338
Ted Kremenek49b1e382012-01-26 21:29:00 +0000339ProgramStateRef CStringChecker::CheckBufferAccess(CheckerContext &C,
340 ProgramStateRef state,
Jordy Rose134a2362010-07-06 23:11:01 +0000341 const Expr *Size,
342 const Expr *FirstBuf,
Jordy Rose722f5582010-08-16 07:51:42 +0000343 const Expr *SecondBuf,
Jordy Rosedceb0cf2011-06-20 02:06:40 +0000344 const char *firstMessage,
Jordy Rose328deee2011-06-20 03:49:16 +0000345 const char *secondMessage,
346 bool WarnAboutSize) const {
Jordy Rosed5d2e502010-07-08 23:57:29 +0000347 // If a previous check has failed, propagate the failure.
348 if (!state)
349 return NULL;
350
Ted Kremenek90af9092010-12-02 07:49:45 +0000351 SValBuilder &svalBuilder = C.getSValBuilder();
Jordy Rose455bd582011-06-16 05:51:02 +0000352 ASTContext &Ctx = svalBuilder.getContext();
Ted Kremenek632e3b72012-01-06 22:09:28 +0000353 const LocationContext *LCtx = C.getLocationContext();
Jordy Rose134a2362010-07-06 23:11:01 +0000354
Ted Kremenek90af9092010-12-02 07:49:45 +0000355 QualType sizeTy = Size->getType();
Jordy Rose134a2362010-07-06 23:11:01 +0000356 QualType PtrTy = Ctx.getPointerType(Ctx.CharTy);
357
Jordy Rose33c829a2010-07-07 07:48:06 +0000358 // Check that the first buffer is non-null.
Ted Kremenek632e3b72012-01-06 22:09:28 +0000359 SVal BufVal = state->getSVal(FirstBuf, LCtx);
Ted Kremenek90af9092010-12-02 07:49:45 +0000360 state = checkNonNull(C, state, FirstBuf, BufVal);
Jordy Rose33c829a2010-07-07 07:48:06 +0000361 if (!state)
362 return NULL;
363
Anna Zakse0c7c272012-02-07 00:56:14 +0000364 // If out-of-bounds checking is turned off, skip the rest.
365 if (!Filter.CheckCStringOutOfBounds)
366 return state;
367
Jordy Rosed5d2e502010-07-08 23:57:29 +0000368 // Get the access length and make sure it is known.
Jordy Rosedceb0cf2011-06-20 02:06:40 +0000369 // FIXME: This assumes the caller has already checked that the access length
370 // is positive. And that it's unsigned.
Ted Kremenek632e3b72012-01-06 22:09:28 +0000371 SVal LengthVal = state->getSVal(Size, LCtx);
David Blaikie05785d12013-02-20 22:23:23 +0000372 Optional<NonLoc> Length = LengthVal.getAs<NonLoc>();
Jordy Rosed5d2e502010-07-08 23:57:29 +0000373 if (!Length)
374 return state;
375
Jordy Rose134a2362010-07-06 23:11:01 +0000376 // Compute the offset of the last element to be accessed: size-1.
David Blaikie2fdacbc2013-02-20 05:52:05 +0000377 NonLoc One = svalBuilder.makeIntVal(1, sizeTy).castAs<NonLoc>();
378 NonLoc LastOffset = svalBuilder
379 .evalBinOpNN(state, BO_Sub, *Length, One, sizeTy).castAs<NonLoc>();
Jordy Rose134a2362010-07-06 23:11:01 +0000380
Chris Lattner57540c52011-04-15 05:22:18 +0000381 // Check that the first buffer is sufficiently long.
Ted Kremenek90af9092010-12-02 07:49:45 +0000382 SVal BufStart = svalBuilder.evalCast(BufVal, PtrTy, FirstBuf->getType());
David Blaikie05785d12013-02-20 22:23:23 +0000383 if (Optional<Loc> BufLoc = BufStart.getAs<Loc>()) {
Jordy Rose328deee2011-06-20 03:49:16 +0000384 const Expr *warningExpr = (WarnAboutSize ? Size : FirstBuf);
385
Ted Kremenek90af9092010-12-02 07:49:45 +0000386 SVal BufEnd = svalBuilder.evalBinOpLN(state, BO_Add, *BufLoc,
387 LastOffset, PtrTy);
Jordy Rose328deee2011-06-20 03:49:16 +0000388 state = CheckLocation(C, state, warningExpr, BufEnd, firstMessage);
Jordy Rose134a2362010-07-06 23:11:01 +0000389
Jordy Roseafdb0532010-08-05 23:11:30 +0000390 // If the buffer isn't large enough, abort.
391 if (!state)
392 return NULL;
393 }
Jordy Rose134a2362010-07-06 23:11:01 +0000394
395 // If there's a second buffer, check it as well.
396 if (SecondBuf) {
Ted Kremenek632e3b72012-01-06 22:09:28 +0000397 BufVal = state->getSVal(SecondBuf, LCtx);
Ted Kremenek90af9092010-12-02 07:49:45 +0000398 state = checkNonNull(C, state, SecondBuf, BufVal);
Jordy Rose33c829a2010-07-07 07:48:06 +0000399 if (!state)
400 return NULL;
401
Ted Kremenek90af9092010-12-02 07:49:45 +0000402 BufStart = svalBuilder.evalCast(BufVal, PtrTy, SecondBuf->getType());
David Blaikie05785d12013-02-20 22:23:23 +0000403 if (Optional<Loc> BufLoc = BufStart.getAs<Loc>()) {
Jordy Rose328deee2011-06-20 03:49:16 +0000404 const Expr *warningExpr = (WarnAboutSize ? Size : SecondBuf);
405
Ted Kremenek90af9092010-12-02 07:49:45 +0000406 SVal BufEnd = svalBuilder.evalBinOpLN(state, BO_Add, *BufLoc,
407 LastOffset, PtrTy);
Jordy Rose328deee2011-06-20 03:49:16 +0000408 state = CheckLocation(C, state, warningExpr, BufEnd, secondMessage);
Jordy Roseafdb0532010-08-05 23:11:30 +0000409 }
Jordy Rose134a2362010-07-06 23:11:01 +0000410 }
411
412 // Large enough or not, return this state!
413 return state;
414}
415
Ted Kremenek49b1e382012-01-26 21:29:00 +0000416ProgramStateRef CStringChecker::CheckOverlap(CheckerContext &C,
417 ProgramStateRef state,
Jordy Rosed5d2e502010-07-08 23:57:29 +0000418 const Expr *Size,
Jordy Rose134a2362010-07-06 23:11:01 +0000419 const Expr *First,
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000420 const Expr *Second) const {
Anna Zakse0c7c272012-02-07 00:56:14 +0000421 if (!Filter.CheckCStringBufferOverlap)
422 return state;
423
Jordy Rose134a2362010-07-06 23:11:01 +0000424 // Do a simple check for overlap: if the two arguments are from the same
425 // buffer, see if the end of the first is greater than the start of the second
426 // or vice versa.
427
Jordy Rosed5d2e502010-07-08 23:57:29 +0000428 // If a previous check has failed, propagate the failure.
429 if (!state)
430 return NULL;
431
Ted Kremenek49b1e382012-01-26 21:29:00 +0000432 ProgramStateRef stateTrue, stateFalse;
Jordy Rose134a2362010-07-06 23:11:01 +0000433
434 // Get the buffer values and make sure they're known locations.
Ted Kremenek632e3b72012-01-06 22:09:28 +0000435 const LocationContext *LCtx = C.getLocationContext();
436 SVal firstVal = state->getSVal(First, LCtx);
437 SVal secondVal = state->getSVal(Second, LCtx);
Jordy Rose134a2362010-07-06 23:11:01 +0000438
David Blaikie05785d12013-02-20 22:23:23 +0000439 Optional<Loc> firstLoc = firstVal.getAs<Loc>();
Ted Kremenek90af9092010-12-02 07:49:45 +0000440 if (!firstLoc)
Jordy Rose134a2362010-07-06 23:11:01 +0000441 return state;
442
David Blaikie05785d12013-02-20 22:23:23 +0000443 Optional<Loc> secondLoc = secondVal.getAs<Loc>();
Ted Kremenek90af9092010-12-02 07:49:45 +0000444 if (!secondLoc)
Jordy Rose134a2362010-07-06 23:11:01 +0000445 return state;
446
447 // Are the two values the same?
Ted Kremenek90af9092010-12-02 07:49:45 +0000448 SValBuilder &svalBuilder = C.getSValBuilder();
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000449 std::tie(stateTrue, stateFalse) =
Ted Kremenek90af9092010-12-02 07:49:45 +0000450 state->assume(svalBuilder.evalEQ(state, *firstLoc, *secondLoc));
Jordy Rose134a2362010-07-06 23:11:01 +0000451
452 if (stateTrue && !stateFalse) {
453 // If the values are known to be equal, that's automatically an overlap.
Ted Kremenek90af9092010-12-02 07:49:45 +0000454 emitOverlapBug(C, stateTrue, First, Second);
Jordy Rose134a2362010-07-06 23:11:01 +0000455 return NULL;
456 }
457
Ted Kremenekc5bea1e2010-12-01 22:16:56 +0000458 // assume the two expressions are not equal.
Jordy Rose134a2362010-07-06 23:11:01 +0000459 assert(stateFalse);
460 state = stateFalse;
461
462 // Which value comes first?
Jordy Rose0585a612011-06-16 05:56:50 +0000463 QualType cmpTy = svalBuilder.getConditionType();
Ted Kremenek90af9092010-12-02 07:49:45 +0000464 SVal reverse = svalBuilder.evalBinOpLL(state, BO_GT,
465 *firstLoc, *secondLoc, cmpTy);
David Blaikie05785d12013-02-20 22:23:23 +0000466 Optional<DefinedOrUnknownSVal> reverseTest =
David Blaikie2fdacbc2013-02-20 05:52:05 +0000467 reverse.getAs<DefinedOrUnknownSVal>();
Ted Kremenek90af9092010-12-02 07:49:45 +0000468 if (!reverseTest)
Jordy Rose134a2362010-07-06 23:11:01 +0000469 return state;
470
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000471 std::tie(stateTrue, stateFalse) = state->assume(*reverseTest);
Jordy Rose134a2362010-07-06 23:11:01 +0000472 if (stateTrue) {
473 if (stateFalse) {
474 // If we don't know which one comes first, we can't perform this test.
475 return state;
476 } else {
Ted Kremenek90af9092010-12-02 07:49:45 +0000477 // Switch the values so that firstVal is before secondVal.
David Blaikie2fdacbc2013-02-20 05:52:05 +0000478 std::swap(firstLoc, secondLoc);
Jordy Rose134a2362010-07-06 23:11:01 +0000479
480 // Switch the Exprs as well, so that they still correspond.
David Blaikie2fdacbc2013-02-20 05:52:05 +0000481 std::swap(First, Second);
Jordy Rose134a2362010-07-06 23:11:01 +0000482 }
483 }
484
485 // Get the length, and make sure it too is known.
Ted Kremenek632e3b72012-01-06 22:09:28 +0000486 SVal LengthVal = state->getSVal(Size, LCtx);
David Blaikie05785d12013-02-20 22:23:23 +0000487 Optional<NonLoc> Length = LengthVal.getAs<NonLoc>();
Jordy Rose134a2362010-07-06 23:11:01 +0000488 if (!Length)
489 return state;
490
491 // Convert the first buffer's start address to char*.
492 // Bail out if the cast fails.
Jordy Rose0585a612011-06-16 05:56:50 +0000493 ASTContext &Ctx = svalBuilder.getContext();
Jordy Rose134a2362010-07-06 23:11:01 +0000494 QualType CharPtrTy = Ctx.getPointerType(Ctx.CharTy);
Jordy Rose455bd582011-06-16 05:51:02 +0000495 SVal FirstStart = svalBuilder.evalCast(*firstLoc, CharPtrTy,
496 First->getType());
David Blaikie05785d12013-02-20 22:23:23 +0000497 Optional<Loc> FirstStartLoc = FirstStart.getAs<Loc>();
Jordy Rose134a2362010-07-06 23:11:01 +0000498 if (!FirstStartLoc)
499 return state;
500
501 // Compute the end of the first buffer. Bail out if THAT fails.
Ted Kremenek90af9092010-12-02 07:49:45 +0000502 SVal FirstEnd = svalBuilder.evalBinOpLN(state, BO_Add,
Jordy Rose134a2362010-07-06 23:11:01 +0000503 *FirstStartLoc, *Length, CharPtrTy);
David Blaikie05785d12013-02-20 22:23:23 +0000504 Optional<Loc> FirstEndLoc = FirstEnd.getAs<Loc>();
Jordy Rose134a2362010-07-06 23:11:01 +0000505 if (!FirstEndLoc)
506 return state;
507
508 // Is the end of the first buffer past the start of the second buffer?
Ted Kremenek90af9092010-12-02 07:49:45 +0000509 SVal Overlap = svalBuilder.evalBinOpLL(state, BO_GT,
510 *FirstEndLoc, *secondLoc, cmpTy);
David Blaikie05785d12013-02-20 22:23:23 +0000511 Optional<DefinedOrUnknownSVal> OverlapTest =
David Blaikie2fdacbc2013-02-20 05:52:05 +0000512 Overlap.getAs<DefinedOrUnknownSVal>();
Jordy Rose134a2362010-07-06 23:11:01 +0000513 if (!OverlapTest)
514 return state;
515
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000516 std::tie(stateTrue, stateFalse) = state->assume(*OverlapTest);
Jordy Rose134a2362010-07-06 23:11:01 +0000517
518 if (stateTrue && !stateFalse) {
519 // Overlap!
Ted Kremenek90af9092010-12-02 07:49:45 +0000520 emitOverlapBug(C, stateTrue, First, Second);
Jordy Rose134a2362010-07-06 23:11:01 +0000521 return NULL;
522 }
523
Ted Kremenekc5bea1e2010-12-01 22:16:56 +0000524 // assume the two expressions don't overlap.
Jordy Rose134a2362010-07-06 23:11:01 +0000525 assert(stateFalse);
526 return stateFalse;
527}
528
Ted Kremenek49b1e382012-01-26 21:29:00 +0000529void CStringChecker::emitOverlapBug(CheckerContext &C, ProgramStateRef state,
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000530 const Stmt *First, const Stmt *Second) const {
Ted Kremenek750b7ac2010-12-20 21:19:09 +0000531 ExplodedNode *N = C.generateSink(state);
Jordy Rose134a2362010-07-06 23:11:01 +0000532 if (!N)
533 return;
534
535 if (!BT_Overlap)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000536 BT_Overlap.reset(new BugType(Filter.CheckNameCStringBufferOverlap,
537 categories::UnixAPI, "Improper arguments"));
Jordy Rose134a2362010-07-06 23:11:01 +0000538
539 // Generate a report for this bug.
Anna Zaks3a6bdf82011-08-17 23:00:25 +0000540 BugReport *report =
541 new BugReport(*BT_Overlap,
Jordy Rose134a2362010-07-06 23:11:01 +0000542 "Arguments must not be overlapping buffers", N);
543 report->addRange(First->getSourceRange());
544 report->addRange(Second->getSourceRange());
545
Jordan Rosee10d5a72012-11-02 01:53:40 +0000546 C.emitReport(report);
Jordy Rose134a2362010-07-06 23:11:01 +0000547}
548
Ted Kremenek49b1e382012-01-26 21:29:00 +0000549ProgramStateRef CStringChecker::checkAdditionOverflow(CheckerContext &C,
550 ProgramStateRef state,
Jordy Rose634c12d2011-06-15 05:52:56 +0000551 NonLoc left,
552 NonLoc right) const {
Anna Zakse0c7c272012-02-07 00:56:14 +0000553 // If out-of-bounds checking is turned off, skip the rest.
554 if (!Filter.CheckCStringOutOfBounds)
555 return state;
556
Jordy Rose634c12d2011-06-15 05:52:56 +0000557 // If a previous check has failed, propagate the failure.
558 if (!state)
559 return NULL;
560
561 SValBuilder &svalBuilder = C.getSValBuilder();
562 BasicValueFactory &BVF = svalBuilder.getBasicValueFactory();
563
564 QualType sizeTy = svalBuilder.getContext().getSizeType();
565 const llvm::APSInt &maxValInt = BVF.getMaxValue(sizeTy);
566 NonLoc maxVal = svalBuilder.makeIntVal(maxValInt);
567
Anna Zaks7c96b7d2011-12-11 18:43:40 +0000568 SVal maxMinusRight;
David Blaikie2fdacbc2013-02-20 05:52:05 +0000569 if (right.getAs<nonloc::ConcreteInt>()) {
Anna Zaks7c96b7d2011-12-11 18:43:40 +0000570 maxMinusRight = svalBuilder.evalBinOpNN(state, BO_Sub, maxVal, right,
571 sizeTy);
572 } else {
Jordy Rose634c12d2011-06-15 05:52:56 +0000573 // Try switching the operands. (The order of these two assignments is
574 // important!)
575 maxMinusRight = svalBuilder.evalBinOpNN(state, BO_Sub, maxVal, left,
576 sizeTy);
577 left = right;
578 }
579
David Blaikie05785d12013-02-20 22:23:23 +0000580 if (Optional<NonLoc> maxMinusRightNL = maxMinusRight.getAs<NonLoc>()) {
Jordy Rose634c12d2011-06-15 05:52:56 +0000581 QualType cmpTy = svalBuilder.getConditionType();
582 // If left > max - right, we have an overflow.
583 SVal willOverflow = svalBuilder.evalBinOpNN(state, BO_GT, left,
584 *maxMinusRightNL, cmpTy);
585
Ted Kremenek49b1e382012-01-26 21:29:00 +0000586 ProgramStateRef stateOverflow, stateOkay;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000587 std::tie(stateOverflow, stateOkay) =
David Blaikie2fdacbc2013-02-20 05:52:05 +0000588 state->assume(willOverflow.castAs<DefinedOrUnknownSVal>());
Jordy Rose634c12d2011-06-15 05:52:56 +0000589
590 if (stateOverflow && !stateOkay) {
591 // We have an overflow. Emit a bug report.
592 ExplodedNode *N = C.generateSink(stateOverflow);
593 if (!N)
594 return NULL;
595
596 if (!BT_AdditionOverflow)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000597 BT_AdditionOverflow.reset(
598 new BuiltinBug(Filter.CheckNameCStringOutOfBounds, "API",
599 "Sum of expressions causes overflow"));
Jordy Rose634c12d2011-06-15 05:52:56 +0000600
Jordy Rose634c12d2011-06-15 05:52:56 +0000601 // This isn't a great error message, but this should never occur in real
602 // code anyway -- you'd have to create a buffer longer than a size_t can
603 // represent, which is sort of a contradiction.
Jordy Rose789adbb2011-06-20 03:51:53 +0000604 const char *warning =
605 "This expression will create a string whose length is too big to "
606 "be represented as a size_t";
Jordy Rose634c12d2011-06-15 05:52:56 +0000607
608 // Generate a report for this bug.
Jordy Rose789adbb2011-06-20 03:51:53 +0000609 BugReport *report = new BugReport(*BT_AdditionOverflow, warning, N);
Jordan Rosee10d5a72012-11-02 01:53:40 +0000610 C.emitReport(report);
Jordy Rose634c12d2011-06-15 05:52:56 +0000611
612 return NULL;
613 }
614
615 // From now on, assume an overflow didn't occur.
616 assert(stateOkay);
617 state = stateOkay;
618 }
619
620 return state;
621}
622
Ted Kremenek49b1e382012-01-26 21:29:00 +0000623ProgramStateRef CStringChecker::setCStringLength(ProgramStateRef state,
Jordy Rose722f5582010-08-16 07:51:42 +0000624 const MemRegion *MR,
Ted Kremenek90af9092010-12-02 07:49:45 +0000625 SVal strLength) {
626 assert(!strLength.isUndef() && "Attempt to set an undefined string length");
Jordy Rose722f5582010-08-16 07:51:42 +0000627
628 MR = MR->StripCasts();
629
630 switch (MR->getKind()) {
631 case MemRegion::StringRegionKind:
632 // FIXME: This can happen if we strcpy() into a string region. This is
633 // undefined [C99 6.4.5p6], but we should still warn about it.
634 return state;
635
636 case MemRegion::SymbolicRegionKind:
637 case MemRegion::AllocaRegionKind:
638 case MemRegion::VarRegionKind:
639 case MemRegion::FieldRegionKind:
640 case MemRegion::ObjCIvarRegionKind:
Jordy Rose0e9fb282011-06-15 05:14:03 +0000641 // These are the types we can currently track string lengths for.
642 break;
Jordy Rose722f5582010-08-16 07:51:42 +0000643
644 case MemRegion::ElementRegionKind:
645 // FIXME: Handle element regions by upper-bounding the parent region's
646 // string length.
647 return state;
648
649 default:
650 // Other regions (mostly non-data) can't have a reliable C string length.
651 // For now, just ignore the change.
652 // FIXME: These are rare but not impossible. We should output some kind of
653 // warning for things like strcpy((char[]){'a', 0}, "b");
654 return state;
655 }
Jordy Rose0e9fb282011-06-15 05:14:03 +0000656
657 if (strLength.isUnknown())
658 return state->remove<CStringLength>(MR);
659
660 return state->set<CStringLength>(MR, strLength);
Jordy Rose722f5582010-08-16 07:51:42 +0000661}
662
Ted Kremenek90af9092010-12-02 07:49:45 +0000663SVal CStringChecker::getCStringLengthForRegion(CheckerContext &C,
Ted Kremenek49b1e382012-01-26 21:29:00 +0000664 ProgramStateRef &state,
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000665 const Expr *Ex,
Jordy Rose634c12d2011-06-15 05:52:56 +0000666 const MemRegion *MR,
667 bool hypothetical) {
668 if (!hypothetical) {
669 // If there's a recorded length, go ahead and return it.
670 const SVal *Recorded = state->get<CStringLength>(MR);
671 if (Recorded)
672 return *Recorded;
673 }
Jordan Rose60619a62013-08-19 16:27:34 +0000674
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000675 // Otherwise, get a new symbol and update the state.
Ted Kremenek90af9092010-12-02 07:49:45 +0000676 SValBuilder &svalBuilder = C.getSValBuilder();
677 QualType sizeTy = svalBuilder.getContext().getSizeType();
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000678 SVal strLength = svalBuilder.getMetadataSymbolVal(CStringChecker::getTag(),
Ted Kremenekd94854a2012-08-22 06:26:15 +0000679 MR, Ex, sizeTy,
680 C.blockCount());
Jordy Rose634c12d2011-06-15 05:52:56 +0000681
Jordan Rose60619a62013-08-19 16:27:34 +0000682 if (!hypothetical) {
683 if (Optional<NonLoc> strLn = strLength.getAs<NonLoc>()) {
684 // In case of unbounded calls strlen etc bound the range to SIZE_MAX/4
685 BasicValueFactory &BVF = svalBuilder.getBasicValueFactory();
686 const llvm::APSInt &maxValInt = BVF.getMaxValue(sizeTy);
687 llvm::APSInt fourInt = APSIntType(maxValInt).getValue(4);
688 const llvm::APSInt *maxLengthInt = BVF.evalAPSInt(BO_Div, maxValInt,
689 fourInt);
690 NonLoc maxLength = svalBuilder.makeIntVal(*maxLengthInt);
691 SVal evalLength = svalBuilder.evalBinOpNN(state, BO_LE, *strLn,
692 maxLength, sizeTy);
693 state = state->assume(evalLength.castAs<DefinedOrUnknownSVal>(), true);
694 }
Jordy Rose634c12d2011-06-15 05:52:56 +0000695 state = state->set<CStringLength>(MR, strLength);
Jordan Rose60619a62013-08-19 16:27:34 +0000696 }
Jordy Rose634c12d2011-06-15 05:52:56 +0000697
Ted Kremenek90af9092010-12-02 07:49:45 +0000698 return strLength;
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000699}
700
Ted Kremenek49b1e382012-01-26 21:29:00 +0000701SVal CStringChecker::getCStringLength(CheckerContext &C, ProgramStateRef &state,
Jordy Rose634c12d2011-06-15 05:52:56 +0000702 const Expr *Ex, SVal Buf,
703 bool hypothetical) const {
Jordy Roseb052e8f2010-07-27 01:37:31 +0000704 const MemRegion *MR = Buf.getAsRegion();
705 if (!MR) {
706 // If we can't get a region, see if it's something we /know/ isn't a
707 // C string. In the context of locations, the only time we can issue such
708 // a warning is for labels.
David Blaikie05785d12013-02-20 22:23:23 +0000709 if (Optional<loc::GotoLabel> Label = Buf.getAs<loc::GotoLabel>()) {
Anna Zakse0c7c272012-02-07 00:56:14 +0000710 if (!Filter.CheckCStringNotNullTerm)
711 return UndefinedVal();
712
Anna Zaksda4c8d62011-10-26 21:06:34 +0000713 if (ExplodedNode *N = C.addTransition(state)) {
Jordy Roseb052e8f2010-07-27 01:37:31 +0000714 if (!BT_NotCString)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000715 BT_NotCString.reset(new BuiltinBug(
716 Filter.CheckNameCStringNotNullTerm, categories::UnixAPI,
717 "Argument is not a null-terminated string."));
Jordy Roseb052e8f2010-07-27 01:37:31 +0000718
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000719 SmallString<120> buf;
Jordy Roseb052e8f2010-07-27 01:37:31 +0000720 llvm::raw_svector_ostream os(buf);
Jordy Rosedceb0cf2011-06-20 02:06:40 +0000721 assert(CurrentFunctionDescription);
722 os << "Argument to " << CurrentFunctionDescription
723 << " is the address of the label '" << Label->getLabel()->getName()
Jordy Roseb052e8f2010-07-27 01:37:31 +0000724 << "', which is not a null-terminated string";
725
726 // Generate a report for this bug.
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000727 BugReport *report = new BugReport(*BT_NotCString, os.str(), N);
Jordy Roseb052e8f2010-07-27 01:37:31 +0000728
729 report->addRange(Ex->getSourceRange());
Jordan Rosee10d5a72012-11-02 01:53:40 +0000730 C.emitReport(report);
Jordy Roseb052e8f2010-07-27 01:37:31 +0000731 }
Jordy Roseb052e8f2010-07-27 01:37:31 +0000732 return UndefinedVal();
Anna Zakse0c7c272012-02-07 00:56:14 +0000733
Jordy Roseb052e8f2010-07-27 01:37:31 +0000734 }
735
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000736 // If it's not a region and not a label, give up.
737 return UnknownVal();
Jordy Roseb052e8f2010-07-27 01:37:31 +0000738 }
739
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000740 // If we have a region, strip casts from it and see if we can figure out
741 // its length. For anything we can't figure out, just return UnknownVal.
742 MR = MR->StripCasts();
743
744 switch (MR->getKind()) {
745 case MemRegion::StringRegionKind: {
746 // Modifying the contents of string regions is undefined [C99 6.4.5p6],
747 // so we can assume that the byte length is the correct C string length.
Ted Kremenek90af9092010-12-02 07:49:45 +0000748 SValBuilder &svalBuilder = C.getSValBuilder();
749 QualType sizeTy = svalBuilder.getContext().getSizeType();
750 const StringLiteral *strLit = cast<StringRegion>(MR)->getStringLiteral();
751 return svalBuilder.makeIntVal(strLit->getByteLength(), sizeTy);
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000752 }
753 case MemRegion::SymbolicRegionKind:
754 case MemRegion::AllocaRegionKind:
755 case MemRegion::VarRegionKind:
756 case MemRegion::FieldRegionKind:
757 case MemRegion::ObjCIvarRegionKind:
Jordy Rose634c12d2011-06-15 05:52:56 +0000758 return getCStringLengthForRegion(C, state, Ex, MR, hypothetical);
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000759 case MemRegion::CompoundLiteralRegionKind:
760 // FIXME: Can we track this? Is it necessary?
761 return UnknownVal();
762 case MemRegion::ElementRegionKind:
763 // FIXME: How can we handle this? It's not good enough to subtract the
764 // offset from the base string length; consider "123\x00567" and &a[5].
765 return UnknownVal();
766 default:
767 // Other regions (mostly non-data) can't have a reliable C string length.
768 // In this case, an error is emitted and UndefinedVal is returned.
769 // The caller should always be prepared to handle this case.
Anna Zakse0c7c272012-02-07 00:56:14 +0000770 if (!Filter.CheckCStringNotNullTerm)
771 return UndefinedVal();
772
Anna Zaksda4c8d62011-10-26 21:06:34 +0000773 if (ExplodedNode *N = C.addTransition(state)) {
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000774 if (!BT_NotCString)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000775 BT_NotCString.reset(new BuiltinBug(
776 Filter.CheckNameCStringNotNullTerm, categories::UnixAPI,
777 "Argument is not a null-terminated string."));
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000778
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000779 SmallString<120> buf;
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000780 llvm::raw_svector_ostream os(buf);
781
Jordy Rosedceb0cf2011-06-20 02:06:40 +0000782 assert(CurrentFunctionDescription);
783 os << "Argument to " << CurrentFunctionDescription << " is ";
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000784
785 if (SummarizeRegion(os, C.getASTContext(), MR))
786 os << ", which is not a null-terminated string";
787 else
788 os << "not a null-terminated string";
789
790 // Generate a report for this bug.
Anna Zaks3a6bdf82011-08-17 23:00:25 +0000791 BugReport *report = new BugReport(*BT_NotCString,
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000792 os.str(), N);
793
794 report->addRange(Ex->getSourceRange());
Jordan Rosee10d5a72012-11-02 01:53:40 +0000795 C.emitReport(report);
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000796 }
797
798 return UndefinedVal();
799 }
Jordy Roseb052e8f2010-07-27 01:37:31 +0000800}
801
Lenny Maioranif3539ad2011-04-12 17:08:43 +0000802const StringLiteral *CStringChecker::getCStringLiteral(CheckerContext &C,
Ted Kremenek49b1e382012-01-26 21:29:00 +0000803 ProgramStateRef &state, const Expr *expr, SVal val) const {
Lenny Maioranif3539ad2011-04-12 17:08:43 +0000804
805 // Get the memory region pointed to by the val.
806 const MemRegion *bufRegion = val.getAsRegion();
807 if (!bufRegion)
808 return NULL;
809
810 // Strip casts off the memory region.
811 bufRegion = bufRegion->StripCasts();
812
813 // Cast the memory region to a string region.
814 const StringRegion *strRegion= dyn_cast<StringRegion>(bufRegion);
815 if (!strRegion)
816 return NULL;
817
818 // Return the actual string in the string region.
819 return strRegion->getStringLiteral();
820}
821
Ted Kremenek49b1e382012-01-26 21:29:00 +0000822ProgramStateRef CStringChecker::InvalidateBuffer(CheckerContext &C,
Anton Yartsev968c60a2013-11-17 09:18:48 +0000823 ProgramStateRef state,
824 const Expr *E, SVal V,
825 bool IsSourceBuffer) {
David Blaikie05785d12013-02-20 22:23:23 +0000826 Optional<Loc> L = V.getAs<Loc>();
Jordy Rose722f5582010-08-16 07:51:42 +0000827 if (!L)
828 return state;
829
830 // FIXME: This is a simplified version of what's in CFRefCount.cpp -- it makes
831 // some assumptions about the value that CFRefCount can't. Even so, it should
832 // probably be refactored.
David Blaikie05785d12013-02-20 22:23:23 +0000833 if (Optional<loc::MemRegionVal> MR = L->getAs<loc::MemRegionVal>()) {
Jordy Rose722f5582010-08-16 07:51:42 +0000834 const MemRegion *R = MR->getRegion()->StripCasts();
835
836 // Are we dealing with an ElementRegion? If so, we should be invalidating
837 // the super-region.
838 if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
839 R = ER->getSuperRegion();
840 // FIXME: What about layers of ElementRegions?
841 }
842
843 // Invalidate this region.
Ted Kremenekd519cae2012-02-17 23:13:45 +0000844 const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
Anton Yartsev968c60a2013-11-17 09:18:48 +0000845
846 bool CausesPointerEscape = false;
847 RegionAndSymbolInvalidationTraits ITraits;
848 // Invalidate and escape only indirect regions accessible through the source
849 // buffer.
850 if (IsSourceBuffer) {
851 ITraits.setTrait(R,
852 RegionAndSymbolInvalidationTraits::TK_PreserveContents);
853 ITraits.setTrait(R, RegionAndSymbolInvalidationTraits::TK_SuppressEscape);
854 CausesPointerEscape = true;
855 }
856
857 return state->invalidateRegions(R, E, C.blockCount(), LCtx,
858 CausesPointerEscape, 0, 0, &ITraits);
Jordy Rose722f5582010-08-16 07:51:42 +0000859 }
860
861 // If we have a non-region value by chance, just remove the binding.
862 // FIXME: is this necessary or correct? This handles the non-Region
863 // cases. Is it ever valid to store to these?
Ted Kremenek62698882012-08-22 06:37:46 +0000864 return state->killBinding(*L);
Jordy Rose722f5582010-08-16 07:51:42 +0000865}
866
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000867bool CStringChecker::SummarizeRegion(raw_ostream &os, ASTContext &Ctx,
Jordy Roseb052e8f2010-07-27 01:37:31 +0000868 const MemRegion *MR) {
Ted Kremenek8df44b262011-08-12 20:02:48 +0000869 const TypedValueRegion *TVR = dyn_cast<TypedValueRegion>(MR);
Jordy Roseb052e8f2010-07-27 01:37:31 +0000870
Jordy Roseadd45b72011-08-12 21:41:07 +0000871 switch (MR->getKind()) {
Jordy Roseb052e8f2010-07-27 01:37:31 +0000872 case MemRegion::FunctionTextRegionKind: {
Anna Zaks42782342012-09-17 19:13:56 +0000873 const NamedDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
Jordy Roseb052e8f2010-07-27 01:37:31 +0000874 if (FD)
Benjamin Kramerb89514a2011-10-14 18:45:37 +0000875 os << "the address of the function '" << *FD << '\'';
Jordy Roseb052e8f2010-07-27 01:37:31 +0000876 else
877 os << "the address of a function";
878 return true;
879 }
880 case MemRegion::BlockTextRegionKind:
881 os << "block text";
882 return true;
883 case MemRegion::BlockDataRegionKind:
884 os << "a block";
885 return true;
886 case MemRegion::CXXThisRegionKind:
Zhongxing Xu03207162010-11-26 08:52:48 +0000887 case MemRegion::CXXTempObjectRegionKind:
Ted Kremenek8df44b262011-08-12 20:02:48 +0000888 os << "a C++ temp object of type " << TVR->getValueType().getAsString();
Jordy Roseb052e8f2010-07-27 01:37:31 +0000889 return true;
890 case MemRegion::VarRegionKind:
Ted Kremenek8df44b262011-08-12 20:02:48 +0000891 os << "a variable of type" << TVR->getValueType().getAsString();
Jordy Roseb052e8f2010-07-27 01:37:31 +0000892 return true;
893 case MemRegion::FieldRegionKind:
Ted Kremenek8df44b262011-08-12 20:02:48 +0000894 os << "a field of type " << TVR->getValueType().getAsString();
Jordy Roseb052e8f2010-07-27 01:37:31 +0000895 return true;
896 case MemRegion::ObjCIvarRegionKind:
Ted Kremenek8df44b262011-08-12 20:02:48 +0000897 os << "an instance variable of type " << TVR->getValueType().getAsString();
Jordy Roseb052e8f2010-07-27 01:37:31 +0000898 return true;
899 default:
900 return false;
901 }
902}
903
Jordy Rosed5d2e502010-07-08 23:57:29 +0000904//===----------------------------------------------------------------------===//
Ted Kremenekdc891422010-12-01 21:57:22 +0000905// evaluation of individual function calls.
Jordy Rosed5d2e502010-07-08 23:57:29 +0000906//===----------------------------------------------------------------------===//
907
Lenny Maiorani79d74142011-03-31 21:36:53 +0000908void CStringChecker::evalCopyCommon(CheckerContext &C,
909 const CallExpr *CE,
Ted Kremenek49b1e382012-01-26 21:29:00 +0000910 ProgramStateRef state,
Jordy Rosed5d2e502010-07-08 23:57:29 +0000911 const Expr *Size, const Expr *Dest,
Lenny Maiorani79d74142011-03-31 21:36:53 +0000912 const Expr *Source, bool Restricted,
913 bool IsMempcpy) const {
Jordy Rosedceb0cf2011-06-20 02:06:40 +0000914 CurrentFunctionDescription = "memory copy function";
915
Jordy Rosed5d2e502010-07-08 23:57:29 +0000916 // See if the size argument is zero.
Ted Kremenek632e3b72012-01-06 22:09:28 +0000917 const LocationContext *LCtx = C.getLocationContext();
918 SVal sizeVal = state->getSVal(Size, LCtx);
Ted Kremenek90af9092010-12-02 07:49:45 +0000919 QualType sizeTy = Size->getType();
Jordy Rosed5d2e502010-07-08 23:57:29 +0000920
Ted Kremenek49b1e382012-01-26 21:29:00 +0000921 ProgramStateRef stateZeroSize, stateNonZeroSize;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000922 std::tie(stateZeroSize, stateNonZeroSize) =
Jordy Rose455bd582011-06-16 05:51:02 +0000923 assumeZero(C, state, sizeVal, sizeTy);
Jordy Rosed5d2e502010-07-08 23:57:29 +0000924
Lenny Maiorani79d74142011-03-31 21:36:53 +0000925 // Get the value of the Dest.
Ted Kremenek632e3b72012-01-06 22:09:28 +0000926 SVal destVal = state->getSVal(Dest, LCtx);
Lenny Maiorani79d74142011-03-31 21:36:53 +0000927
928 // If the size is zero, there won't be any actual memory access, so
929 // just bind the return value to the destination buffer and return.
Anna Zaksb3b56bb2012-05-03 18:21:28 +0000930 if (stateZeroSize && !stateNonZeroSize) {
Ted Kremenek632e3b72012-01-06 22:09:28 +0000931 stateZeroSize = stateZeroSize->BindExpr(CE, LCtx, destVal);
Anna Zaksda4c8d62011-10-26 21:06:34 +0000932 C.addTransition(stateZeroSize);
Anna Zaksb3b56bb2012-05-03 18:21:28 +0000933 return;
Lenny Maiorani79d74142011-03-31 21:36:53 +0000934 }
Jordy Rosed5d2e502010-07-08 23:57:29 +0000935
936 // If the size can be nonzero, we have to check the other arguments.
Ted Kremenek90af9092010-12-02 07:49:45 +0000937 if (stateNonZeroSize) {
Jordy Rose63b84be2011-06-04 00:04:22 +0000938 state = stateNonZeroSize;
Lenny Maiorani79d74142011-03-31 21:36:53 +0000939
940 // Ensure the destination is not null. If it is NULL there will be a
941 // NULL pointer dereference.
942 state = checkNonNull(C, state, Dest, destVal);
943 if (!state)
944 return;
945
946 // Get the value of the Src.
Ted Kremenek632e3b72012-01-06 22:09:28 +0000947 SVal srcVal = state->getSVal(Source, LCtx);
Lenny Maiorani79d74142011-03-31 21:36:53 +0000948
949 // Ensure the source is not null. If it is NULL there will be a
950 // NULL pointer dereference.
951 state = checkNonNull(C, state, Source, srcVal);
952 if (!state)
953 return;
954
Jordy Rosefb5e8c22011-06-04 01:50:25 +0000955 // Ensure the accesses are valid and that the buffers do not overlap.
Jordy Rosedceb0cf2011-06-20 02:06:40 +0000956 const char * const writeWarning =
957 "Memory copy function overflows destination buffer";
Jordy Rose722f5582010-08-16 07:51:42 +0000958 state = CheckBufferAccess(C, state, Size, Dest, Source,
Jordy Rosedceb0cf2011-06-20 02:06:40 +0000959 writeWarning, /* sourceWarning = */ NULL);
Jordy Rosed5d2e502010-07-08 23:57:29 +0000960 if (Restricted)
961 state = CheckOverlap(C, state, Size, Dest, Source);
Jordy Rose722f5582010-08-16 07:51:42 +0000962
Jordy Rosefb5e8c22011-06-04 01:50:25 +0000963 if (!state)
964 return;
Lenny Maiorani79d74142011-03-31 21:36:53 +0000965
Jordy Rosefb5e8c22011-06-04 01:50:25 +0000966 // If this is mempcpy, get the byte after the last byte copied and
967 // bind the expr.
968 if (IsMempcpy) {
David Blaikie2fdacbc2013-02-20 05:52:05 +0000969 loc::MemRegionVal destRegVal = destVal.castAs<loc::MemRegionVal>();
Jordy Rosefb5e8c22011-06-04 01:50:25 +0000970
971 // Get the length to copy.
David Blaikie05785d12013-02-20 22:23:23 +0000972 if (Optional<NonLoc> lenValNonLoc = sizeVal.getAs<NonLoc>()) {
Jordy Rosefb5e8c22011-06-04 01:50:25 +0000973 // Get the byte after the last byte copied.
974 SVal lastElement = C.getSValBuilder().evalBinOpLN(state, BO_Add,
David Blaikie2fdacbc2013-02-20 05:52:05 +0000975 destRegVal,
Jordy Rosefb5e8c22011-06-04 01:50:25 +0000976 *lenValNonLoc,
977 Dest->getType());
978
979 // The byte after the last byte copied is the return value.
Ted Kremenek632e3b72012-01-06 22:09:28 +0000980 state = state->BindExpr(CE, LCtx, lastElement);
Jordy Rose097c5392011-06-04 01:47:27 +0000981 } else {
Jordy Rosefb5e8c22011-06-04 01:50:25 +0000982 // If we don't know how much we copied, we can at least
983 // conjure a return value for later.
Ted Kremenekd94854a2012-08-22 06:26:15 +0000984 SVal result = C.getSValBuilder().conjureSymbolVal(0, CE, LCtx,
985 C.blockCount());
Ted Kremenek632e3b72012-01-06 22:09:28 +0000986 state = state->BindExpr(CE, LCtx, result);
Lenny Maiorani79d74142011-03-31 21:36:53 +0000987 }
988
Jordy Rosefb5e8c22011-06-04 01:50:25 +0000989 } else {
990 // All other copies return the destination buffer.
991 // (Well, bcopy() has a void return type, but this won't hurt.)
Ted Kremenek632e3b72012-01-06 22:09:28 +0000992 state = state->BindExpr(CE, LCtx, destVal);
Jordy Rose722f5582010-08-16 07:51:42 +0000993 }
Jordy Rosefb5e8c22011-06-04 01:50:25 +0000994
Anton Yartsev968c60a2013-11-17 09:18:48 +0000995 // Invalidate the destination (regular invalidation without pointer-escaping
996 // the address of the top-level region).
Jordy Rosefb5e8c22011-06-04 01:50:25 +0000997 // FIXME: Even if we can't perfectly model the copy, we should see if we
998 // can use LazyCompoundVals to copy the source values into the destination.
999 // This would probably remove any existing bindings past the end of the
1000 // copied region, but that's still an improvement over blank invalidation.
Anton Yartsev968c60a2013-11-17 09:18:48 +00001001 state = InvalidateBuffer(C, state, Dest, C.getSVal(Dest),
1002 /*IsSourceBuffer*/false);
1003
1004 // Invalidate the source (const-invalidation without const-pointer-escaping
1005 // the address of the top-level region).
1006 state = InvalidateBuffer(C, state, Source, C.getSVal(Source),
1007 /*IsSourceBuffer*/true);
1008
Anna Zaksda4c8d62011-10-26 21:06:34 +00001009 C.addTransition(state);
Jordy Rosed5d2e502010-07-08 23:57:29 +00001010 }
1011}
1012
1013
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00001014void CStringChecker::evalMemcpy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaksb508d292012-04-10 23:41:11 +00001015 if (CE->getNumArgs() < 3)
1016 return;
1017
Jordy Rose134a2362010-07-06 23:11:01 +00001018 // void *memcpy(void *restrict dst, const void *restrict src, size_t n);
Jordy Rose134a2362010-07-06 23:11:01 +00001019 // The return value is the address of the destination buffer.
Jordy Rosed5d2e502010-07-08 23:57:29 +00001020 const Expr *Dest = CE->getArg(0);
Ted Kremenek49b1e382012-01-26 21:29:00 +00001021 ProgramStateRef state = C.getState();
Jordy Rose097c5392011-06-04 01:47:27 +00001022
Lenny Maiorani79d74142011-03-31 21:36:53 +00001023 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1), true);
1024}
1025
1026void CStringChecker::evalMempcpy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaksb508d292012-04-10 23:41:11 +00001027 if (CE->getNumArgs() < 3)
1028 return;
1029
Lenny Maiorani79d74142011-03-31 21:36:53 +00001030 // void *mempcpy(void *restrict dst, const void *restrict src, size_t n);
1031 // The return value is a pointer to the byte following the last written byte.
1032 const Expr *Dest = CE->getArg(0);
Ted Kremenek49b1e382012-01-26 21:29:00 +00001033 ProgramStateRef state = C.getState();
Lenny Maiorani79d74142011-03-31 21:36:53 +00001034
1035 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1), true, true);
Jordy Rose134a2362010-07-06 23:11:01 +00001036}
1037
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00001038void CStringChecker::evalMemmove(CheckerContext &C, const CallExpr *CE) const {
Anna Zaksb508d292012-04-10 23:41:11 +00001039 if (CE->getNumArgs() < 3)
1040 return;
1041
Jordy Rosed5d2e502010-07-08 23:57:29 +00001042 // void *memmove(void *dst, const void *src, size_t n);
1043 // The return value is the address of the destination buffer.
1044 const Expr *Dest = CE->getArg(0);
Ted Kremenek49b1e382012-01-26 21:29:00 +00001045 ProgramStateRef state = C.getState();
Jordy Rose097c5392011-06-04 01:47:27 +00001046
Lenny Maiorani79d74142011-03-31 21:36:53 +00001047 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1));
Jordy Rosed5d2e502010-07-08 23:57:29 +00001048}
1049
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00001050void CStringChecker::evalBcopy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaksb508d292012-04-10 23:41:11 +00001051 if (CE->getNumArgs() < 3)
1052 return;
1053
Jordy Rosed5d2e502010-07-08 23:57:29 +00001054 // void bcopy(const void *src, void *dst, size_t n);
Lenny Maiorani79d74142011-03-31 21:36:53 +00001055 evalCopyCommon(C, CE, C.getState(),
1056 CE->getArg(2), CE->getArg(1), CE->getArg(0));
Jordy Rosed5d2e502010-07-08 23:57:29 +00001057}
1058
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00001059void CStringChecker::evalMemcmp(CheckerContext &C, const CallExpr *CE) const {
Anna Zaksb508d292012-04-10 23:41:11 +00001060 if (CE->getNumArgs() < 3)
1061 return;
1062
Jordy Rose65136fb2010-07-07 08:15:01 +00001063 // int memcmp(const void *s1, const void *s2, size_t n);
Jordy Rosedceb0cf2011-06-20 02:06:40 +00001064 CurrentFunctionDescription = "memory comparison function";
1065
Jordy Rose65136fb2010-07-07 08:15:01 +00001066 const Expr *Left = CE->getArg(0);
1067 const Expr *Right = CE->getArg(1);
1068 const Expr *Size = CE->getArg(2);
1069
Ted Kremenek49b1e382012-01-26 21:29:00 +00001070 ProgramStateRef state = C.getState();
Ted Kremenek90af9092010-12-02 07:49:45 +00001071 SValBuilder &svalBuilder = C.getSValBuilder();
Jordy Rose65136fb2010-07-07 08:15:01 +00001072
Jordy Rosed5d2e502010-07-08 23:57:29 +00001073 // See if the size argument is zero.
Ted Kremenek632e3b72012-01-06 22:09:28 +00001074 const LocationContext *LCtx = C.getLocationContext();
1075 SVal sizeVal = state->getSVal(Size, LCtx);
Ted Kremenek90af9092010-12-02 07:49:45 +00001076 QualType sizeTy = Size->getType();
Jordy Rose65136fb2010-07-07 08:15:01 +00001077
Ted Kremenek49b1e382012-01-26 21:29:00 +00001078 ProgramStateRef stateZeroSize, stateNonZeroSize;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001079 std::tie(stateZeroSize, stateNonZeroSize) =
Ted Kremenek90af9092010-12-02 07:49:45 +00001080 assumeZero(C, state, sizeVal, sizeTy);
Jordy Rose65136fb2010-07-07 08:15:01 +00001081
Jordy Rosed5d2e502010-07-08 23:57:29 +00001082 // If the size can be zero, the result will be 0 in that case, and we don't
1083 // have to check either of the buffers.
Ted Kremenek90af9092010-12-02 07:49:45 +00001084 if (stateZeroSize) {
1085 state = stateZeroSize;
Ted Kremenek632e3b72012-01-06 22:09:28 +00001086 state = state->BindExpr(CE, LCtx,
1087 svalBuilder.makeZeroVal(CE->getType()));
Anna Zaksda4c8d62011-10-26 21:06:34 +00001088 C.addTransition(state);
Jordy Rose65136fb2010-07-07 08:15:01 +00001089 }
1090
Jordy Rosed5d2e502010-07-08 23:57:29 +00001091 // If the size can be nonzero, we have to check the other arguments.
Ted Kremenek90af9092010-12-02 07:49:45 +00001092 if (stateNonZeroSize) {
1093 state = stateNonZeroSize;
Jordy Rosed5d2e502010-07-08 23:57:29 +00001094 // If we know the two buffers are the same, we know the result is 0.
1095 // First, get the two buffers' addresses. Another checker will have already
1096 // made sure they're not undefined.
Ted Kremenek632e3b72012-01-06 22:09:28 +00001097 DefinedOrUnknownSVal LV =
David Blaikie2fdacbc2013-02-20 05:52:05 +00001098 state->getSVal(Left, LCtx).castAs<DefinedOrUnknownSVal>();
Ted Kremenek632e3b72012-01-06 22:09:28 +00001099 DefinedOrUnknownSVal RV =
David Blaikie2fdacbc2013-02-20 05:52:05 +00001100 state->getSVal(Right, LCtx).castAs<DefinedOrUnknownSVal>();
Jordy Rose65136fb2010-07-07 08:15:01 +00001101
Jordy Rosed5d2e502010-07-08 23:57:29 +00001102 // See if they are the same.
Ted Kremenek90af9092010-12-02 07:49:45 +00001103 DefinedOrUnknownSVal SameBuf = svalBuilder.evalEQ(state, LV, RV);
Ted Kremenek49b1e382012-01-26 21:29:00 +00001104 ProgramStateRef StSameBuf, StNotSameBuf;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001105 std::tie(StSameBuf, StNotSameBuf) = state->assume(SameBuf);
Jordy Rosed5d2e502010-07-08 23:57:29 +00001106
Jordy Rose455bd582011-06-16 05:51:02 +00001107 // If the two arguments might be the same buffer, we know the result is 0,
Jordy Rosed5d2e502010-07-08 23:57:29 +00001108 // and we only need to check one size.
1109 if (StSameBuf) {
1110 state = StSameBuf;
1111 state = CheckBufferAccess(C, state, Size, Left);
1112 if (state) {
Ted Kremenek632e3b72012-01-06 22:09:28 +00001113 state = StSameBuf->BindExpr(CE, LCtx,
1114 svalBuilder.makeZeroVal(CE->getType()));
Anna Zaksda4c8d62011-10-26 21:06:34 +00001115 C.addTransition(state);
Jordy Rosed5d2e502010-07-08 23:57:29 +00001116 }
1117 }
1118
1119 // If the two arguments might be different buffers, we have to check the
1120 // size of both of them.
1121 if (StNotSameBuf) {
1122 state = StNotSameBuf;
1123 state = CheckBufferAccess(C, state, Size, Left, Right);
1124 if (state) {
1125 // The return value is the comparison result, which we don't know.
Ted Kremenekd94854a2012-08-22 06:26:15 +00001126 SVal CmpV = svalBuilder.conjureSymbolVal(0, CE, LCtx, C.blockCount());
Ted Kremenek632e3b72012-01-06 22:09:28 +00001127 state = state->BindExpr(CE, LCtx, CmpV);
Anna Zaksda4c8d62011-10-26 21:06:34 +00001128 C.addTransition(state);
Jordy Rosed5d2e502010-07-08 23:57:29 +00001129 }
1130 }
1131 }
Jordy Rose65136fb2010-07-07 08:15:01 +00001132}
1133
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00001134void CStringChecker::evalstrLength(CheckerContext &C,
1135 const CallExpr *CE) const {
Anna Zaksb508d292012-04-10 23:41:11 +00001136 if (CE->getNumArgs() < 1)
1137 return;
1138
Jordy Roseb052e8f2010-07-27 01:37:31 +00001139 // size_t strlen(const char *s);
Ted Kremenek280a01f2011-02-22 04:55:05 +00001140 evalstrLengthCommon(C, CE, /* IsStrnlen = */ false);
1141}
1142
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00001143void CStringChecker::evalstrnLength(CheckerContext &C,
1144 const CallExpr *CE) const {
Anna Zaksb508d292012-04-10 23:41:11 +00001145 if (CE->getNumArgs() < 2)
1146 return;
1147
Ted Kremenek280a01f2011-02-22 04:55:05 +00001148 // size_t strnlen(const char *s, size_t maxlen);
1149 evalstrLengthCommon(C, CE, /* IsStrnlen = */ true);
1150}
1151
1152void CStringChecker::evalstrLengthCommon(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00001153 bool IsStrnlen) const {
Jordy Rosedceb0cf2011-06-20 02:06:40 +00001154 CurrentFunctionDescription = "string length function";
Ted Kremenek49b1e382012-01-26 21:29:00 +00001155 ProgramStateRef state = C.getState();
Ted Kremenek632e3b72012-01-06 22:09:28 +00001156 const LocationContext *LCtx = C.getLocationContext();
Jordy Rosed3592892011-06-14 01:15:31 +00001157
1158 if (IsStrnlen) {
1159 const Expr *maxlenExpr = CE->getArg(1);
Ted Kremenek632e3b72012-01-06 22:09:28 +00001160 SVal maxlenVal = state->getSVal(maxlenExpr, LCtx);
Jordy Rosed3592892011-06-14 01:15:31 +00001161
Ted Kremenek49b1e382012-01-26 21:29:00 +00001162 ProgramStateRef stateZeroSize, stateNonZeroSize;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001163 std::tie(stateZeroSize, stateNonZeroSize) =
Jordy Rosed3592892011-06-14 01:15:31 +00001164 assumeZero(C, state, maxlenVal, maxlenExpr->getType());
1165
1166 // If the size can be zero, the result will be 0 in that case, and we don't
1167 // have to check the string itself.
1168 if (stateZeroSize) {
1169 SVal zero = C.getSValBuilder().makeZeroVal(CE->getType());
Ted Kremenek632e3b72012-01-06 22:09:28 +00001170 stateZeroSize = stateZeroSize->BindExpr(CE, LCtx, zero);
Anna Zaksda4c8d62011-10-26 21:06:34 +00001171 C.addTransition(stateZeroSize);
Jordy Rosed3592892011-06-14 01:15:31 +00001172 }
1173
1174 // If the size is GUARANTEED to be zero, we're done!
1175 if (!stateNonZeroSize)
1176 return;
1177
1178 // Otherwise, record the assumption that the size is nonzero.
1179 state = stateNonZeroSize;
1180 }
1181
1182 // Check that the string argument is non-null.
Jordy Roseb052e8f2010-07-27 01:37:31 +00001183 const Expr *Arg = CE->getArg(0);
Ted Kremenek632e3b72012-01-06 22:09:28 +00001184 SVal ArgVal = state->getSVal(Arg, LCtx);
Jordy Roseb052e8f2010-07-27 01:37:31 +00001185
Ted Kremenek90af9092010-12-02 07:49:45 +00001186 state = checkNonNull(C, state, Arg, ArgVal);
Jordy Roseb052e8f2010-07-27 01:37:31 +00001187
Jordy Rose45d8c122011-06-14 01:26:48 +00001188 if (!state)
1189 return;
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001190
Jordy Rose45d8c122011-06-14 01:26:48 +00001191 SVal strLength = getCStringLength(C, state, Arg, ArgVal);
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001192
Jordy Rose45d8c122011-06-14 01:26:48 +00001193 // If the argument isn't a valid C string, there's no valid state to
1194 // transition to.
1195 if (strLength.isUndef())
1196 return;
Jordy Rosed3592892011-06-14 01:15:31 +00001197
Jordy Rose45d8c122011-06-14 01:26:48 +00001198 DefinedOrUnknownSVal result = UnknownVal();
Jordy Rosed3592892011-06-14 01:15:31 +00001199
Jordy Rose45d8c122011-06-14 01:26:48 +00001200 // If the check is for strnlen() then bind the return value to no more than
1201 // the maxlen value.
1202 if (IsStrnlen) {
Jordy Rose0585a612011-06-16 05:56:50 +00001203 QualType cmpTy = C.getSValBuilder().getConditionType();
Jordy Rosed3592892011-06-14 01:15:31 +00001204
Jordy Rose45d8c122011-06-14 01:26:48 +00001205 // It's a little unfortunate to be getting this again,
1206 // but it's not that expensive...
1207 const Expr *maxlenExpr = CE->getArg(1);
Ted Kremenek632e3b72012-01-06 22:09:28 +00001208 SVal maxlenVal = state->getSVal(maxlenExpr, LCtx);
Ted Kremenek280a01f2011-02-22 04:55:05 +00001209
David Blaikie05785d12013-02-20 22:23:23 +00001210 Optional<NonLoc> strLengthNL = strLength.getAs<NonLoc>();
1211 Optional<NonLoc> maxlenValNL = maxlenVal.getAs<NonLoc>();
Ted Kremenek280a01f2011-02-22 04:55:05 +00001212
Jordy Rose45d8c122011-06-14 01:26:48 +00001213 if (strLengthNL && maxlenValNL) {
Ted Kremenek49b1e382012-01-26 21:29:00 +00001214 ProgramStateRef stateStringTooLong, stateStringNotTooLong;
Jordy Rosed3592892011-06-14 01:15:31 +00001215
Jordy Rose45d8c122011-06-14 01:26:48 +00001216 // Check if the strLength is greater than the maxlen.
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001217 std::tie(stateStringTooLong, stateStringNotTooLong) = state->assume(
1218 C.getSValBuilder()
1219 .evalBinOpNN(state, BO_GT, *strLengthNL, *maxlenValNL, cmpTy)
1220 .castAs<DefinedOrUnknownSVal>());
Jordy Rosed3592892011-06-14 01:15:31 +00001221
Jordy Rose45d8c122011-06-14 01:26:48 +00001222 if (stateStringTooLong && !stateStringNotTooLong) {
1223 // If the string is longer than maxlen, return maxlen.
1224 result = *maxlenValNL;
1225 } else if (stateStringNotTooLong && !stateStringTooLong) {
1226 // If the string is shorter than maxlen, return its length.
1227 result = *strLengthNL;
Ted Kremenek280a01f2011-02-22 04:55:05 +00001228 }
1229 }
1230
Jordy Rose45d8c122011-06-14 01:26:48 +00001231 if (result.isUnknown()) {
1232 // If we don't have enough information for a comparison, there's
1233 // no guarantee the full string length will actually be returned.
1234 // All we know is the return value is the min of the string length
1235 // and the limit. This is better than nothing.
Ted Kremenekd94854a2012-08-22 06:26:15 +00001236 result = C.getSValBuilder().conjureSymbolVal(0, CE, LCtx, C.blockCount());
David Blaikie2fdacbc2013-02-20 05:52:05 +00001237 NonLoc resultNL = result.castAs<NonLoc>();
Jordy Rose45d8c122011-06-14 01:26:48 +00001238
1239 if (strLengthNL) {
David Blaikie2fdacbc2013-02-20 05:52:05 +00001240 state = state->assume(C.getSValBuilder().evalBinOpNN(
1241 state, BO_LE, resultNL, *strLengthNL, cmpTy)
1242 .castAs<DefinedOrUnknownSVal>(), true);
Jordy Rose45d8c122011-06-14 01:26:48 +00001243 }
1244
1245 if (maxlenValNL) {
David Blaikie2fdacbc2013-02-20 05:52:05 +00001246 state = state->assume(C.getSValBuilder().evalBinOpNN(
1247 state, BO_LE, resultNL, *maxlenValNL, cmpTy)
1248 .castAs<DefinedOrUnknownSVal>(), true);
Jordy Rose45d8c122011-06-14 01:26:48 +00001249 }
1250 }
1251
1252 } else {
1253 // This is a plain strlen(), not strnlen().
David Blaikie2fdacbc2013-02-20 05:52:05 +00001254 result = strLength.castAs<DefinedOrUnknownSVal>();
Jordy Rose45d8c122011-06-14 01:26:48 +00001255
1256 // If we don't know the length of the string, conjure a return
1257 // value, so it can be used in constraints, at least.
1258 if (result.isUnknown()) {
Ted Kremenekd94854a2012-08-22 06:26:15 +00001259 result = C.getSValBuilder().conjureSymbolVal(0, CE, LCtx, C.blockCount());
Jordy Rose45d8c122011-06-14 01:26:48 +00001260 }
Jordy Roseb052e8f2010-07-27 01:37:31 +00001261 }
Jordy Rose45d8c122011-06-14 01:26:48 +00001262
1263 // Bind the return value.
1264 assert(!result.isUnknown() && "Should have conjured a value by now");
Ted Kremenek632e3b72012-01-06 22:09:28 +00001265 state = state->BindExpr(CE, LCtx, result);
Anna Zaksda4c8d62011-10-26 21:06:34 +00001266 C.addTransition(state);
Jordy Roseb052e8f2010-07-27 01:37:31 +00001267}
1268
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00001269void CStringChecker::evalStrcpy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaksb508d292012-04-10 23:41:11 +00001270 if (CE->getNumArgs() < 2)
1271 return;
1272
Jordy Rose722f5582010-08-16 07:51:42 +00001273 // char *strcpy(char *restrict dst, const char *restrict src);
Lenny Maiorani467dbd52011-04-09 15:12:58 +00001274 evalStrcpyCommon(C, CE,
1275 /* returnEnd = */ false,
1276 /* isBounded = */ false,
1277 /* isAppending = */ false);
Ted Kremenekfb1a79a2011-02-22 04:58:34 +00001278}
1279
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00001280void CStringChecker::evalStrncpy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaksb508d292012-04-10 23:41:11 +00001281 if (CE->getNumArgs() < 3)
1282 return;
1283
Jordy Rose4451cd42011-06-04 00:05:23 +00001284 // char *strncpy(char *restrict dst, const char *restrict src, size_t n);
Lenny Maiorani467dbd52011-04-09 15:12:58 +00001285 evalStrcpyCommon(C, CE,
1286 /* returnEnd = */ false,
1287 /* isBounded = */ true,
1288 /* isAppending = */ false);
Jordy Rose722f5582010-08-16 07:51:42 +00001289}
1290
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00001291void CStringChecker::evalStpcpy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaksb508d292012-04-10 23:41:11 +00001292 if (CE->getNumArgs() < 2)
1293 return;
1294
Jordy Rose722f5582010-08-16 07:51:42 +00001295 // char *stpcpy(char *restrict dst, const char *restrict src);
Lenny Maiorani467dbd52011-04-09 15:12:58 +00001296 evalStrcpyCommon(C, CE,
1297 /* returnEnd = */ true,
1298 /* isBounded = */ false,
1299 /* isAppending = */ false);
1300}
1301
1302void CStringChecker::evalStrcat(CheckerContext &C, const CallExpr *CE) const {
Anna Zaksb508d292012-04-10 23:41:11 +00001303 if (CE->getNumArgs() < 2)
1304 return;
1305
Lenny Maiorani467dbd52011-04-09 15:12:58 +00001306 //char *strcat(char *restrict s1, const char *restrict s2);
1307 evalStrcpyCommon(C, CE,
1308 /* returnEnd = */ false,
1309 /* isBounded = */ false,
1310 /* isAppending = */ true);
1311}
1312
1313void CStringChecker::evalStrncat(CheckerContext &C, const CallExpr *CE) const {
Anna Zaksb508d292012-04-10 23:41:11 +00001314 if (CE->getNumArgs() < 3)
1315 return;
1316
Lenny Maiorani467dbd52011-04-09 15:12:58 +00001317 //char *strncat(char *restrict s1, const char *restrict s2, size_t n);
1318 evalStrcpyCommon(C, CE,
1319 /* returnEnd = */ false,
1320 /* isBounded = */ true,
1321 /* isAppending = */ true);
Jordy Rose722f5582010-08-16 07:51:42 +00001322}
1323
Ted Kremenekdc891422010-12-01 21:57:22 +00001324void CStringChecker::evalStrcpyCommon(CheckerContext &C, const CallExpr *CE,
Lenny Maiorani467dbd52011-04-09 15:12:58 +00001325 bool returnEnd, bool isBounded,
1326 bool isAppending) const {
Jordy Rosedceb0cf2011-06-20 02:06:40 +00001327 CurrentFunctionDescription = "string copy function";
Ted Kremenek49b1e382012-01-26 21:29:00 +00001328 ProgramStateRef state = C.getState();
Ted Kremenek632e3b72012-01-06 22:09:28 +00001329 const LocationContext *LCtx = C.getLocationContext();
Jordy Rose722f5582010-08-16 07:51:42 +00001330
Lenny Maiorani467dbd52011-04-09 15:12:58 +00001331 // Check that the destination is non-null.
Jordy Rose722f5582010-08-16 07:51:42 +00001332 const Expr *Dst = CE->getArg(0);
Ted Kremenek632e3b72012-01-06 22:09:28 +00001333 SVal DstVal = state->getSVal(Dst, LCtx);
Jordy Rose722f5582010-08-16 07:51:42 +00001334
Ted Kremenek90af9092010-12-02 07:49:45 +00001335 state = checkNonNull(C, state, Dst, DstVal);
Jordy Rose722f5582010-08-16 07:51:42 +00001336 if (!state)
1337 return;
1338
1339 // Check that the source is non-null.
Ted Kremenek90af9092010-12-02 07:49:45 +00001340 const Expr *srcExpr = CE->getArg(1);
Ted Kremenek632e3b72012-01-06 22:09:28 +00001341 SVal srcVal = state->getSVal(srcExpr, LCtx);
Ted Kremenek90af9092010-12-02 07:49:45 +00001342 state = checkNonNull(C, state, srcExpr, srcVal);
Jordy Rose722f5582010-08-16 07:51:42 +00001343 if (!state)
1344 return;
1345
1346 // Get the string length of the source.
Ted Kremenek90af9092010-12-02 07:49:45 +00001347 SVal strLength = getCStringLength(C, state, srcExpr, srcVal);
Jordy Rose722f5582010-08-16 07:51:42 +00001348
1349 // If the source isn't a valid C string, give up.
Ted Kremenek90af9092010-12-02 07:49:45 +00001350 if (strLength.isUndef())
Jordy Rose722f5582010-08-16 07:51:42 +00001351 return;
1352
Jordy Rose634c12d2011-06-15 05:52:56 +00001353 SValBuilder &svalBuilder = C.getSValBuilder();
1354 QualType cmpTy = svalBuilder.getConditionType();
Jordy Roseb41f7c52011-06-20 21:55:40 +00001355 QualType sizeTy = svalBuilder.getContext().getSizeType();
Jordy Rose634c12d2011-06-15 05:52:56 +00001356
Jordy Roseb41f7c52011-06-20 21:55:40 +00001357 // These two values allow checking two kinds of errors:
1358 // - actual overflows caused by a source that doesn't fit in the destination
1359 // - potential overflows caused by a bound that could exceed the destination
Jordy Rose634c12d2011-06-15 05:52:56 +00001360 SVal amountCopied = UnknownVal();
Jordy Roseb41f7c52011-06-20 21:55:40 +00001361 SVal maxLastElementIndex = UnknownVal();
1362 const char *boundWarning = NULL;
Jordy Rose634c12d2011-06-15 05:52:56 +00001363
Lenny Maiorani467dbd52011-04-09 15:12:58 +00001364 // If the function is strncpy, strncat, etc... it is bounded.
1365 if (isBounded) {
1366 // Get the max number of characters to copy.
Ted Kremenekfb1a79a2011-02-22 04:58:34 +00001367 const Expr *lenExpr = CE->getArg(2);
Ted Kremenek632e3b72012-01-06 22:09:28 +00001368 SVal lenVal = state->getSVal(lenExpr, LCtx);
Ted Kremenekfb1a79a2011-02-22 04:58:34 +00001369
Jordy Rose634c12d2011-06-15 05:52:56 +00001370 // Protect against misdeclared strncpy().
Jordy Roseb41f7c52011-06-20 21:55:40 +00001371 lenVal = svalBuilder.evalCast(lenVal, sizeTy, lenExpr->getType());
Jordy Rose634c12d2011-06-15 05:52:56 +00001372
David Blaikie05785d12013-02-20 22:23:23 +00001373 Optional<NonLoc> strLengthNL = strLength.getAs<NonLoc>();
1374 Optional<NonLoc> lenValNL = lenVal.getAs<NonLoc>();
Ted Kremenekfb1a79a2011-02-22 04:58:34 +00001375
Jordy Rose634c12d2011-06-15 05:52:56 +00001376 // If we know both values, we might be able to figure out how much
1377 // we're copying.
1378 if (strLengthNL && lenValNL) {
Ted Kremenek49b1e382012-01-26 21:29:00 +00001379 ProgramStateRef stateSourceTooLong, stateSourceNotTooLong;
Ted Kremenekfb1a79a2011-02-22 04:58:34 +00001380
Jordy Rose634c12d2011-06-15 05:52:56 +00001381 // Check if the max number to copy is less than the length of the src.
Jordy Roseb41f7c52011-06-20 21:55:40 +00001382 // If the bound is equal to the source length, strncpy won't null-
1383 // terminate the result!
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001384 std::tie(stateSourceTooLong, stateSourceNotTooLong) = state->assume(
David Blaikie2fdacbc2013-02-20 05:52:05 +00001385 svalBuilder.evalBinOpNN(state, BO_GE, *strLengthNL, *lenValNL, cmpTy)
1386 .castAs<DefinedOrUnknownSVal>());
Jordy Rose634c12d2011-06-15 05:52:56 +00001387
1388 if (stateSourceTooLong && !stateSourceNotTooLong) {
1389 // Max number to copy is less than the length of the src, so the actual
1390 // strLength copied is the max number arg.
1391 state = stateSourceTooLong;
1392 amountCopied = lenVal;
1393
1394 } else if (!stateSourceTooLong && stateSourceNotTooLong) {
1395 // The source buffer entirely fits in the bound.
1396 state = stateSourceNotTooLong;
1397 amountCopied = strLength;
1398 }
1399 }
1400
Jordy Rose328deee2011-06-20 03:49:16 +00001401 // We still want to know if the bound is known to be too large.
Jordy Roseb41f7c52011-06-20 21:55:40 +00001402 if (lenValNL) {
1403 if (isAppending) {
1404 // For strncat, the check is strlen(dst) + lenVal < sizeof(dst)
1405
1406 // Get the string length of the destination. If the destination is
1407 // memory that can't have a string length, we shouldn't be copying
1408 // into it anyway.
1409 SVal dstStrLength = getCStringLength(C, state, Dst, DstVal);
1410 if (dstStrLength.isUndef())
1411 return;
1412
David Blaikie05785d12013-02-20 22:23:23 +00001413 if (Optional<NonLoc> dstStrLengthNL = dstStrLength.getAs<NonLoc>()) {
Jordy Roseb41f7c52011-06-20 21:55:40 +00001414 maxLastElementIndex = svalBuilder.evalBinOpNN(state, BO_Add,
1415 *lenValNL,
1416 *dstStrLengthNL,
1417 sizeTy);
1418 boundWarning = "Size argument is greater than the free space in the "
1419 "destination buffer";
1420 }
1421
1422 } else {
1423 // For strncpy, this is just checking that lenVal <= sizeof(dst)
1424 // (Yes, strncpy and strncat differ in how they treat termination.
1425 // strncat ALWAYS terminates, but strncpy doesn't.)
Jordy Rose459d5f62012-05-14 17:58:35 +00001426
1427 // We need a special case for when the copy size is zero, in which
1428 // case strncpy will do no work at all. Our bounds check uses n-1
1429 // as the last element accessed, so n == 0 is problematic.
1430 ProgramStateRef StateZeroSize, StateNonZeroSize;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001431 std::tie(StateZeroSize, StateNonZeroSize) =
Jordy Rose459d5f62012-05-14 17:58:35 +00001432 assumeZero(C, state, *lenValNL, sizeTy);
1433
1434 // If the size is known to be zero, we're done.
1435 if (StateZeroSize && !StateNonZeroSize) {
1436 StateZeroSize = StateZeroSize->BindExpr(CE, LCtx, DstVal);
1437 C.addTransition(StateZeroSize);
1438 return;
1439 }
1440
1441 // Otherwise, go ahead and figure out the last element we'll touch.
1442 // We don't record the non-zero assumption here because we can't
1443 // be sure. We won't warn on a possible zero.
David Blaikie2fdacbc2013-02-20 05:52:05 +00001444 NonLoc one = svalBuilder.makeIntVal(1, sizeTy).castAs<NonLoc>();
Jordy Roseb41f7c52011-06-20 21:55:40 +00001445 maxLastElementIndex = svalBuilder.evalBinOpNN(state, BO_Sub, *lenValNL,
1446 one, sizeTy);
1447 boundWarning = "Size argument is greater than the length of the "
1448 "destination buffer";
1449 }
1450 }
Jordy Rose328deee2011-06-20 03:49:16 +00001451
Jordy Rose634c12d2011-06-15 05:52:56 +00001452 // If we couldn't pin down the copy length, at least bound it.
Jordy Roseb41f7c52011-06-20 21:55:40 +00001453 // FIXME: We should actually run this code path for append as well, but
1454 // right now it creates problems with constraints (since we can end up
1455 // trying to pass constraints from symbol to symbol).
1456 if (amountCopied.isUnknown() && !isAppending) {
Jordy Rose634c12d2011-06-15 05:52:56 +00001457 // Try to get a "hypothetical" string length symbol, which we can later
1458 // set as a real value if that turns out to be the case.
1459 amountCopied = getCStringLength(C, state, lenExpr, srcVal, true);
1460 assert(!amountCopied.isUndef());
1461
David Blaikie05785d12013-02-20 22:23:23 +00001462 if (Optional<NonLoc> amountCopiedNL = amountCopied.getAs<NonLoc>()) {
Jordy Rose634c12d2011-06-15 05:52:56 +00001463 if (lenValNL) {
1464 // amountCopied <= lenVal
1465 SVal copiedLessThanBound = svalBuilder.evalBinOpNN(state, BO_LE,
1466 *amountCopiedNL,
1467 *lenValNL,
1468 cmpTy);
David Blaikie2fdacbc2013-02-20 05:52:05 +00001469 state = state->assume(
1470 copiedLessThanBound.castAs<DefinedOrUnknownSVal>(), true);
Jordy Rose634c12d2011-06-15 05:52:56 +00001471 if (!state)
1472 return;
1473 }
1474
1475 if (strLengthNL) {
1476 // amountCopied <= strlen(source)
1477 SVal copiedLessThanSrc = svalBuilder.evalBinOpNN(state, BO_LE,
1478 *amountCopiedNL,
1479 *strLengthNL,
1480 cmpTy);
David Blaikie2fdacbc2013-02-20 05:52:05 +00001481 state = state->assume(
1482 copiedLessThanSrc.castAs<DefinedOrUnknownSVal>(), true);
Jordy Rose634c12d2011-06-15 05:52:56 +00001483 if (!state)
1484 return;
1485 }
1486 }
1487 }
1488
1489 } else {
1490 // The function isn't bounded. The amount copied should match the length
1491 // of the source buffer.
1492 amountCopied = strLength;
Ted Kremenekfb1a79a2011-02-22 04:58:34 +00001493 }
1494
Jordy Rose634c12d2011-06-15 05:52:56 +00001495 assert(state);
1496
1497 // This represents the number of characters copied into the destination
1498 // buffer. (It may not actually be the strlen if the destination buffer
1499 // is not terminated.)
1500 SVal finalStrLength = UnknownVal();
1501
Lenny Maiorani467dbd52011-04-09 15:12:58 +00001502 // If this is an appending function (strcat, strncat...) then set the
1503 // string length to strlen(src) + strlen(dst) since the buffer will
1504 // ultimately contain both.
1505 if (isAppending) {
Jordy Rose455bd582011-06-16 05:51:02 +00001506 // Get the string length of the destination. If the destination is memory
1507 // that can't have a string length, we shouldn't be copying into it anyway.
Lenny Maiorani467dbd52011-04-09 15:12:58 +00001508 SVal dstStrLength = getCStringLength(C, state, Dst, DstVal);
1509 if (dstStrLength.isUndef())
1510 return;
1511
David Blaikie05785d12013-02-20 22:23:23 +00001512 Optional<NonLoc> srcStrLengthNL = amountCopied.getAs<NonLoc>();
1513 Optional<NonLoc> dstStrLengthNL = dstStrLength.getAs<NonLoc>();
Lenny Maiorani467dbd52011-04-09 15:12:58 +00001514
Jordy Rose634c12d2011-06-15 05:52:56 +00001515 // If we know both string lengths, we might know the final string length.
1516 if (srcStrLengthNL && dstStrLengthNL) {
1517 // Make sure the two lengths together don't overflow a size_t.
1518 state = checkAdditionOverflow(C, state, *srcStrLengthNL, *dstStrLengthNL);
1519 if (!state)
1520 return;
Lenny Maiorani467dbd52011-04-09 15:12:58 +00001521
Jordy Rose634c12d2011-06-15 05:52:56 +00001522 finalStrLength = svalBuilder.evalBinOpNN(state, BO_Add, *srcStrLengthNL,
1523 *dstStrLengthNL, sizeTy);
1524 }
Lenny Maiorani467dbd52011-04-09 15:12:58 +00001525
Jordy Rose634c12d2011-06-15 05:52:56 +00001526 // If we couldn't get a single value for the final string length,
1527 // we can at least bound it by the individual lengths.
1528 if (finalStrLength.isUnknown()) {
1529 // Try to get a "hypothetical" string length symbol, which we can later
1530 // set as a real value if that turns out to be the case.
1531 finalStrLength = getCStringLength(C, state, CE, DstVal, true);
1532 assert(!finalStrLength.isUndef());
1533
David Blaikie05785d12013-02-20 22:23:23 +00001534 if (Optional<NonLoc> finalStrLengthNL = finalStrLength.getAs<NonLoc>()) {
Jordy Rose634c12d2011-06-15 05:52:56 +00001535 if (srcStrLengthNL) {
1536 // finalStrLength >= srcStrLength
1537 SVal sourceInResult = svalBuilder.evalBinOpNN(state, BO_GE,
1538 *finalStrLengthNL,
1539 *srcStrLengthNL,
1540 cmpTy);
David Blaikie2fdacbc2013-02-20 05:52:05 +00001541 state = state->assume(sourceInResult.castAs<DefinedOrUnknownSVal>(),
Jordy Rose634c12d2011-06-15 05:52:56 +00001542 true);
1543 if (!state)
1544 return;
1545 }
1546
1547 if (dstStrLengthNL) {
1548 // finalStrLength >= dstStrLength
1549 SVal destInResult = svalBuilder.evalBinOpNN(state, BO_GE,
1550 *finalStrLengthNL,
1551 *dstStrLengthNL,
1552 cmpTy);
David Blaikie2fdacbc2013-02-20 05:52:05 +00001553 state =
1554 state->assume(destInResult.castAs<DefinedOrUnknownSVal>(), true);
Jordy Rose634c12d2011-06-15 05:52:56 +00001555 if (!state)
1556 return;
1557 }
1558 }
1559 }
1560
1561 } else {
1562 // Otherwise, this is a copy-over function (strcpy, strncpy, ...), and
1563 // the final string length will match the input string length.
1564 finalStrLength = amountCopied;
Lenny Maiorani467dbd52011-04-09 15:12:58 +00001565 }
1566
Jordy Rose634c12d2011-06-15 05:52:56 +00001567 // The final result of the function will either be a pointer past the last
1568 // copied element, or a pointer to the start of the destination buffer.
Ted Kremenek90af9092010-12-02 07:49:45 +00001569 SVal Result = (returnEnd ? UnknownVal() : DstVal);
Jordy Rose722f5582010-08-16 07:51:42 +00001570
Jordy Rose634c12d2011-06-15 05:52:56 +00001571 assert(state);
1572
Jordy Rose722f5582010-08-16 07:51:42 +00001573 // If the destination is a MemRegion, try to check for a buffer overflow and
1574 // record the new string length.
David Blaikie05785d12013-02-20 22:23:23 +00001575 if (Optional<loc::MemRegionVal> dstRegVal =
David Blaikie2fdacbc2013-02-20 05:52:05 +00001576 DstVal.getAs<loc::MemRegionVal>()) {
Jordy Roseb41f7c52011-06-20 21:55:40 +00001577 QualType ptrTy = Dst->getType();
1578
1579 // If we have an exact value on a bounded copy, use that to check for
1580 // overflows, rather than our estimate about how much is actually copied.
1581 if (boundWarning) {
David Blaikie05785d12013-02-20 22:23:23 +00001582 if (Optional<NonLoc> maxLastNL = maxLastElementIndex.getAs<NonLoc>()) {
Jordy Roseb41f7c52011-06-20 21:55:40 +00001583 SVal maxLastElement = svalBuilder.evalBinOpLN(state, BO_Add, *dstRegVal,
1584 *maxLastNL, ptrTy);
1585 state = CheckLocation(C, state, CE->getArg(2), maxLastElement,
1586 boundWarning);
1587 if (!state)
1588 return;
1589 }
1590 }
1591
1592 // Then, if the final length is known...
David Blaikie05785d12013-02-20 22:23:23 +00001593 if (Optional<NonLoc> knownStrLength = finalStrLength.getAs<NonLoc>()) {
Jordy Rose634c12d2011-06-15 05:52:56 +00001594 SVal lastElement = svalBuilder.evalBinOpLN(state, BO_Add, *dstRegVal,
Jordy Roseb41f7c52011-06-20 21:55:40 +00001595 *knownStrLength, ptrTy);
Jordy Rose722f5582010-08-16 07:51:42 +00001596
Jordy Roseb41f7c52011-06-20 21:55:40 +00001597 // ...and we haven't checked the bound, we'll check the actual copy.
1598 if (!boundWarning) {
1599 const char * const warningMsg =
1600 "String copy function overflows destination buffer";
1601 state = CheckLocation(C, state, Dst, lastElement, warningMsg);
1602 if (!state)
1603 return;
1604 }
Jordy Rose722f5582010-08-16 07:51:42 +00001605
1606 // If this is a stpcpy-style copy, the last element is the return value.
Ted Kremenek90af9092010-12-02 07:49:45 +00001607 if (returnEnd)
1608 Result = lastElement;
Jordy Rose722f5582010-08-16 07:51:42 +00001609 }
1610
Anton Yartsev968c60a2013-11-17 09:18:48 +00001611 // Invalidate the destination (regular invalidation without pointer-escaping
1612 // the address of the top-level region). This must happen before we set the
1613 // C string length because invalidation will clear the length.
Jordy Rose722f5582010-08-16 07:51:42 +00001614 // FIXME: Even if we can't perfectly model the copy, we should see if we
1615 // can use LazyCompoundVals to copy the source values into the destination.
1616 // This would probably remove any existing bindings past the end of the
1617 // string, but that's still an improvement over blank invalidation.
Anton Yartsev968c60a2013-11-17 09:18:48 +00001618 state = InvalidateBuffer(C, state, Dst, *dstRegVal,
1619 /*IsSourceBuffer*/false);
1620
1621 // Invalidate the source (const-invalidation without const-pointer-escaping
1622 // the address of the top-level region).
1623 state = InvalidateBuffer(C, state, srcExpr, srcVal, /*IsSourceBuffer*/true);
Jordy Rose722f5582010-08-16 07:51:42 +00001624
Jordy Rose328deee2011-06-20 03:49:16 +00001625 // Set the C string length of the destination, if we know it.
Jordy Roseb41f7c52011-06-20 21:55:40 +00001626 if (isBounded && !isAppending) {
1627 // strncpy is annoying in that it doesn't guarantee to null-terminate
1628 // the result string. If the original string didn't fit entirely inside
1629 // the bound (including the null-terminator), we don't know how long the
1630 // result is.
1631 if (amountCopied != strLength)
1632 finalStrLength = UnknownVal();
1633 }
1634 state = setCStringLength(state, dstRegVal->getRegion(), finalStrLength);
Jordy Rose722f5582010-08-16 07:51:42 +00001635 }
1636
Jordy Rose634c12d2011-06-15 05:52:56 +00001637 assert(state);
1638
Jordy Rose722f5582010-08-16 07:51:42 +00001639 // If this is a stpcpy-style copy, but we were unable to check for a buffer
1640 // overflow, we still need a result. Conjure a return value.
Ted Kremenek90af9092010-12-02 07:49:45 +00001641 if (returnEnd && Result.isUnknown()) {
Ted Kremenekd94854a2012-08-22 06:26:15 +00001642 Result = svalBuilder.conjureSymbolVal(0, CE, LCtx, C.blockCount());
Jordy Rose722f5582010-08-16 07:51:42 +00001643 }
1644
1645 // Set the return value.
Ted Kremenek632e3b72012-01-06 22:09:28 +00001646 state = state->BindExpr(CE, LCtx, Result);
Anna Zaksda4c8d62011-10-26 21:06:34 +00001647 C.addTransition(state);
Jordy Rose722f5582010-08-16 07:51:42 +00001648}
1649
Lenny Maioranif3539ad2011-04-12 17:08:43 +00001650void CStringChecker::evalStrcmp(CheckerContext &C, const CallExpr *CE) const {
Anna Zaksb508d292012-04-10 23:41:11 +00001651 if (CE->getNumArgs() < 2)
1652 return;
1653
Jordy Rosec0263702011-06-16 07:13:34 +00001654 //int strcmp(const char *s1, const char *s2);
Lenny Maiorani4af23c82011-04-28 15:09:11 +00001655 evalStrcmpCommon(C, CE, /* isBounded = */ false, /* ignoreCase = */ false);
Lenny Maioranie553e402011-04-25 22:21:00 +00001656}
Lenny Maioranif3539ad2011-04-12 17:08:43 +00001657
Lenny Maioranie553e402011-04-25 22:21:00 +00001658void CStringChecker::evalStrncmp(CheckerContext &C, const CallExpr *CE) const {
Anna Zaksb508d292012-04-10 23:41:11 +00001659 if (CE->getNumArgs() < 3)
1660 return;
1661
Jordy Rosec0263702011-06-16 07:13:34 +00001662 //int strncmp(const char *s1, const char *s2, size_t n);
Lenny Maiorani4af23c82011-04-28 15:09:11 +00001663 evalStrcmpCommon(C, CE, /* isBounded = */ true, /* ignoreCase = */ false);
1664}
1665
1666void CStringChecker::evalStrcasecmp(CheckerContext &C,
1667 const CallExpr *CE) const {
Anna Zaksb508d292012-04-10 23:41:11 +00001668 if (CE->getNumArgs() < 2)
1669 return;
1670
Jordy Rosec0263702011-06-16 07:13:34 +00001671 //int strcasecmp(const char *s1, const char *s2);
Lenny Maiorani4af23c82011-04-28 15:09:11 +00001672 evalStrcmpCommon(C, CE, /* isBounded = */ false, /* ignoreCase = */ true);
Lenny Maioranie553e402011-04-25 22:21:00 +00001673}
1674
Lenny Maiorani0b510272011-05-02 19:05:49 +00001675void CStringChecker::evalStrncasecmp(CheckerContext &C,
1676 const CallExpr *CE) const {
Anna Zaksb508d292012-04-10 23:41:11 +00001677 if (CE->getNumArgs() < 3)
1678 return;
1679
Jordy Rosec0263702011-06-16 07:13:34 +00001680 //int strncasecmp(const char *s1, const char *s2, size_t n);
Lenny Maiorani0b510272011-05-02 19:05:49 +00001681 evalStrcmpCommon(C, CE, /* isBounded = */ true, /* ignoreCase = */ true);
1682}
1683
Lenny Maioranie553e402011-04-25 22:21:00 +00001684void CStringChecker::evalStrcmpCommon(CheckerContext &C, const CallExpr *CE,
Lenny Maiorani4af23c82011-04-28 15:09:11 +00001685 bool isBounded, bool ignoreCase) const {
Jordy Rosedceb0cf2011-06-20 02:06:40 +00001686 CurrentFunctionDescription = "string comparison function";
Ted Kremenek49b1e382012-01-26 21:29:00 +00001687 ProgramStateRef state = C.getState();
Ted Kremenek632e3b72012-01-06 22:09:28 +00001688 const LocationContext *LCtx = C.getLocationContext();
Lenny Maioranif3539ad2011-04-12 17:08:43 +00001689
1690 // Check that the first string is non-null
1691 const Expr *s1 = CE->getArg(0);
Ted Kremenek632e3b72012-01-06 22:09:28 +00001692 SVal s1Val = state->getSVal(s1, LCtx);
Lenny Maioranif3539ad2011-04-12 17:08:43 +00001693 state = checkNonNull(C, state, s1, s1Val);
1694 if (!state)
1695 return;
1696
1697 // Check that the second string is non-null.
1698 const Expr *s2 = CE->getArg(1);
Ted Kremenek632e3b72012-01-06 22:09:28 +00001699 SVal s2Val = state->getSVal(s2, LCtx);
Lenny Maioranif3539ad2011-04-12 17:08:43 +00001700 state = checkNonNull(C, state, s2, s2Val);
1701 if (!state)
1702 return;
1703
1704 // Get the string length of the first string or give up.
1705 SVal s1Length = getCStringLength(C, state, s1, s1Val);
1706 if (s1Length.isUndef())
1707 return;
1708
1709 // Get the string length of the second string or give up.
1710 SVal s2Length = getCStringLength(C, state, s2, s2Val);
1711 if (s2Length.isUndef())
1712 return;
1713
Jordy Rosec0263702011-06-16 07:13:34 +00001714 // If we know the two buffers are the same, we know the result is 0.
1715 // First, get the two buffers' addresses. Another checker will have already
1716 // made sure they're not undefined.
David Blaikie2fdacbc2013-02-20 05:52:05 +00001717 DefinedOrUnknownSVal LV = s1Val.castAs<DefinedOrUnknownSVal>();
1718 DefinedOrUnknownSVal RV = s2Val.castAs<DefinedOrUnknownSVal>();
Lenny Maioranif3539ad2011-04-12 17:08:43 +00001719
Jordy Rosec0263702011-06-16 07:13:34 +00001720 // See if they are the same.
Lenny Maioranif3539ad2011-04-12 17:08:43 +00001721 SValBuilder &svalBuilder = C.getSValBuilder();
Jordy Rosec0263702011-06-16 07:13:34 +00001722 DefinedOrUnknownSVal SameBuf = svalBuilder.evalEQ(state, LV, RV);
Ted Kremenek49b1e382012-01-26 21:29:00 +00001723 ProgramStateRef StSameBuf, StNotSameBuf;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001724 std::tie(StSameBuf, StNotSameBuf) = state->assume(SameBuf);
Lenny Maioranif3539ad2011-04-12 17:08:43 +00001725
Jordy Rosec0263702011-06-16 07:13:34 +00001726 // If the two arguments might be the same buffer, we know the result is 0,
1727 // and we only need to check one size.
1728 if (StSameBuf) {
Ted Kremenek632e3b72012-01-06 22:09:28 +00001729 StSameBuf = StSameBuf->BindExpr(CE, LCtx,
1730 svalBuilder.makeZeroVal(CE->getType()));
Anna Zaksda4c8d62011-10-26 21:06:34 +00001731 C.addTransition(StSameBuf);
Jordy Rosec0263702011-06-16 07:13:34 +00001732
1733 // If the two arguments are GUARANTEED to be the same, we're done!
1734 if (!StNotSameBuf)
1735 return;
1736 }
1737
1738 assert(StNotSameBuf);
1739 state = StNotSameBuf;
1740
1741 // At this point we can go about comparing the two buffers.
1742 // For now, we only do this if they're both known string literals.
1743
1744 // Attempt to extract string literals from both expressions.
1745 const StringLiteral *s1StrLiteral = getCStringLiteral(C, state, s1, s1Val);
1746 const StringLiteral *s2StrLiteral = getCStringLiteral(C, state, s2, s2Val);
1747 bool canComputeResult = false;
1748
1749 if (s1StrLiteral && s2StrLiteral) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001750 StringRef s1StrRef = s1StrLiteral->getString();
1751 StringRef s2StrRef = s2StrLiteral->getString();
Jordy Rosec0263702011-06-16 07:13:34 +00001752
1753 if (isBounded) {
1754 // Get the max number of characters to compare.
1755 const Expr *lenExpr = CE->getArg(2);
Ted Kremenek632e3b72012-01-06 22:09:28 +00001756 SVal lenVal = state->getSVal(lenExpr, LCtx);
Jordy Rosec0263702011-06-16 07:13:34 +00001757
1758 // If the length is known, we can get the right substrings.
1759 if (const llvm::APSInt *len = svalBuilder.getKnownValue(state, lenVal)) {
1760 // Create substrings of each to compare the prefix.
1761 s1StrRef = s1StrRef.substr(0, (size_t)len->getZExtValue());
1762 s2StrRef = s2StrRef.substr(0, (size_t)len->getZExtValue());
1763 canComputeResult = true;
1764 }
1765 } else {
1766 // This is a normal, unbounded strcmp.
1767 canComputeResult = true;
1768 }
1769
1770 if (canComputeResult) {
1771 // Real strcmp stops at null characters.
1772 size_t s1Term = s1StrRef.find('\0');
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001773 if (s1Term != StringRef::npos)
Jordy Rosec0263702011-06-16 07:13:34 +00001774 s1StrRef = s1StrRef.substr(0, s1Term);
1775
1776 size_t s2Term = s2StrRef.find('\0');
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001777 if (s2Term != StringRef::npos)
Jordy Rosec0263702011-06-16 07:13:34 +00001778 s2StrRef = s2StrRef.substr(0, s2Term);
1779
1780 // Use StringRef's comparison methods to compute the actual result.
1781 int result;
1782
1783 if (ignoreCase) {
1784 // Compare string 1 to string 2 the same way strcasecmp() does.
1785 result = s1StrRef.compare_lower(s2StrRef);
1786 } else {
1787 // Compare string 1 to string 2 the same way strcmp() does.
1788 result = s1StrRef.compare(s2StrRef);
1789 }
1790
1791 // Build the SVal of the comparison and bind the return value.
1792 SVal resultVal = svalBuilder.makeIntVal(result, CE->getType());
Ted Kremenek632e3b72012-01-06 22:09:28 +00001793 state = state->BindExpr(CE, LCtx, resultVal);
Jordy Rosec0263702011-06-16 07:13:34 +00001794 }
1795 }
1796
1797 if (!canComputeResult) {
1798 // Conjure a symbolic value. It's the best we can do.
Ted Kremenekd94854a2012-08-22 06:26:15 +00001799 SVal resultVal = svalBuilder.conjureSymbolVal(0, CE, LCtx, C.blockCount());
Ted Kremenek632e3b72012-01-06 22:09:28 +00001800 state = state->BindExpr(CE, LCtx, resultVal);
Jordy Rosec0263702011-06-16 07:13:34 +00001801 }
1802
1803 // Record this as a possible path.
Anna Zaksda4c8d62011-10-26 21:06:34 +00001804 C.addTransition(state);
Lenny Maioranif3539ad2011-04-12 17:08:43 +00001805}
1806
Jordan Rose6e3cf2b2013-04-22 23:18:42 +00001807void CStringChecker::evalStrsep(CheckerContext &C, const CallExpr *CE) const {
1808 //char *strsep(char **stringp, const char *delim);
1809 if (CE->getNumArgs() < 2)
1810 return;
1811
1812 // Sanity: does the search string parameter match the return type?
1813 const Expr *SearchStrPtr = CE->getArg(0);
1814 QualType CharPtrTy = SearchStrPtr->getType()->getPointeeType();
1815 if (CharPtrTy.isNull() ||
1816 CE->getType().getUnqualifiedType() != CharPtrTy.getUnqualifiedType())
1817 return;
1818
1819 CurrentFunctionDescription = "strsep()";
1820 ProgramStateRef State = C.getState();
1821 const LocationContext *LCtx = C.getLocationContext();
1822
1823 // Check that the search string pointer is non-null (though it may point to
1824 // a null string).
1825 SVal SearchStrVal = State->getSVal(SearchStrPtr, LCtx);
1826 State = checkNonNull(C, State, SearchStrPtr, SearchStrVal);
1827 if (!State)
1828 return;
1829
1830 // Check that the delimiter string is non-null.
1831 const Expr *DelimStr = CE->getArg(1);
1832 SVal DelimStrVal = State->getSVal(DelimStr, LCtx);
1833 State = checkNonNull(C, State, DelimStr, DelimStrVal);
1834 if (!State)
1835 return;
1836
1837 SValBuilder &SVB = C.getSValBuilder();
1838 SVal Result;
1839 if (Optional<Loc> SearchStrLoc = SearchStrVal.getAs<Loc>()) {
1840 // Get the current value of the search string pointer, as a char*.
1841 Result = State->getSVal(*SearchStrLoc, CharPtrTy);
1842
1843 // Invalidate the search string, representing the change of one delimiter
1844 // character to NUL.
Anton Yartsev968c60a2013-11-17 09:18:48 +00001845 State = InvalidateBuffer(C, State, SearchStrPtr, Result,
1846 /*IsSourceBuffer*/false);
Jordan Rose6e3cf2b2013-04-22 23:18:42 +00001847
1848 // Overwrite the search string pointer. The new value is either an address
1849 // further along in the same string, or NULL if there are no more tokens.
1850 State = State->bindLoc(*SearchStrLoc,
1851 SVB.conjureSymbolVal(getTag(), CE, LCtx, CharPtrTy,
1852 C.blockCount()));
1853 } else {
1854 assert(SearchStrVal.isUnknown());
1855 // Conjure a symbolic value. It's the best we can do.
1856 Result = SVB.conjureSymbolVal(0, CE, LCtx, C.blockCount());
1857 }
1858
1859 // Set the return value, and finish.
1860 State = State->BindExpr(CE, LCtx, Result);
1861 C.addTransition(State);
1862}
1863
1864
Jordy Rosed5d2e502010-07-08 23:57:29 +00001865//===----------------------------------------------------------------------===//
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001866// The driver method, and other Checker callbacks.
Jordy Rosed5d2e502010-07-08 23:57:29 +00001867//===----------------------------------------------------------------------===//
Jordy Rose134a2362010-07-06 23:11:01 +00001868
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00001869bool CStringChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
Anna Zaks6348a812012-02-17 22:35:26 +00001870 const FunctionDecl *FDecl = C.getCalleeDecl(CE);
1871
1872 if (!FDecl)
Jordy Rose134a2362010-07-06 23:11:01 +00001873 return false;
Jordy Rose134a2362010-07-06 23:11:01 +00001874
Jordan Rose6e3cf2b2013-04-22 23:18:42 +00001875 // FIXME: Poorly-factored string switches are slow.
Anna Zaks6348a812012-02-17 22:35:26 +00001876 FnCheck evalFunction = 0;
1877 if (C.isCLibraryFunction(FDecl, "memcpy"))
1878 evalFunction = &CStringChecker::evalMemcpy;
1879 else if (C.isCLibraryFunction(FDecl, "mempcpy"))
1880 evalFunction = &CStringChecker::evalMempcpy;
1881 else if (C.isCLibraryFunction(FDecl, "memcmp"))
1882 evalFunction = &CStringChecker::evalMemcmp;
1883 else if (C.isCLibraryFunction(FDecl, "memmove"))
1884 evalFunction = &CStringChecker::evalMemmove;
1885 else if (C.isCLibraryFunction(FDecl, "strcpy"))
1886 evalFunction = &CStringChecker::evalStrcpy;
1887 else if (C.isCLibraryFunction(FDecl, "strncpy"))
1888 evalFunction = &CStringChecker::evalStrncpy;
1889 else if (C.isCLibraryFunction(FDecl, "stpcpy"))
1890 evalFunction = &CStringChecker::evalStpcpy;
1891 else if (C.isCLibraryFunction(FDecl, "strcat"))
1892 evalFunction = &CStringChecker::evalStrcat;
1893 else if (C.isCLibraryFunction(FDecl, "strncat"))
1894 evalFunction = &CStringChecker::evalStrncat;
1895 else if (C.isCLibraryFunction(FDecl, "strlen"))
1896 evalFunction = &CStringChecker::evalstrLength;
1897 else if (C.isCLibraryFunction(FDecl, "strnlen"))
1898 evalFunction = &CStringChecker::evalstrnLength;
1899 else if (C.isCLibraryFunction(FDecl, "strcmp"))
1900 evalFunction = &CStringChecker::evalStrcmp;
1901 else if (C.isCLibraryFunction(FDecl, "strncmp"))
1902 evalFunction = &CStringChecker::evalStrncmp;
1903 else if (C.isCLibraryFunction(FDecl, "strcasecmp"))
1904 evalFunction = &CStringChecker::evalStrcasecmp;
1905 else if (C.isCLibraryFunction(FDecl, "strncasecmp"))
1906 evalFunction = &CStringChecker::evalStrncasecmp;
Jordan Rose6e3cf2b2013-04-22 23:18:42 +00001907 else if (C.isCLibraryFunction(FDecl, "strsep"))
1908 evalFunction = &CStringChecker::evalStrsep;
Anna Zaks6348a812012-02-17 22:35:26 +00001909 else if (C.isCLibraryFunction(FDecl, "bcopy"))
1910 evalFunction = &CStringChecker::evalBcopy;
1911 else if (C.isCLibraryFunction(FDecl, "bcmp"))
1912 evalFunction = &CStringChecker::evalMemcmp;
1913
Jordy Rosed5d2e502010-07-08 23:57:29 +00001914 // If the callee isn't a string function, let another checker handle it.
Ted Kremenekdc891422010-12-01 21:57:22 +00001915 if (!evalFunction)
Jordy Rose134a2362010-07-06 23:11:01 +00001916 return false;
1917
Jordy Rosedceb0cf2011-06-20 02:06:40 +00001918 // Make sure each function sets its own description.
1919 // (But don't bother in a release build.)
1920 assert(!(CurrentFunctionDescription = NULL));
1921
Jordy Rosed5d2e502010-07-08 23:57:29 +00001922 // Check and evaluate the call.
Ted Kremenekdc891422010-12-01 21:57:22 +00001923 (this->*evalFunction)(C, CE);
Anna Zakse0c7c272012-02-07 00:56:14 +00001924
1925 // If the evaluate call resulted in no change, chain to the next eval call
1926 // handler.
1927 // Note, the custom CString evaluation calls assume that basic safety
1928 // properties are held. However, if the user chooses to turn off some of these
1929 // checks, we ignore the issues and leave the call evaluation to a generic
1930 // handler.
1931 if (!C.isDifferent())
1932 return false;
1933
Jordy Rose134a2362010-07-06 23:11:01 +00001934 return true;
1935}
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001936
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00001937void CStringChecker::checkPreStmt(const DeclStmt *DS, CheckerContext &C) const {
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001938 // Record string length for char a[] = "abc";
Ted Kremenek49b1e382012-01-26 21:29:00 +00001939 ProgramStateRef state = C.getState();
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001940
1941 for (DeclStmt::const_decl_iterator I = DS->decl_begin(), E = DS->decl_end();
1942 I != E; ++I) {
1943 const VarDecl *D = dyn_cast<VarDecl>(*I);
1944 if (!D)
1945 continue;
1946
1947 // FIXME: Handle array fields of structs.
1948 if (!D->getType()->isArrayType())
1949 continue;
1950
1951 const Expr *Init = D->getInit();
1952 if (!Init)
1953 continue;
1954 if (!isa<StringLiteral>(Init))
1955 continue;
1956
Anna Zaksc9abbe22011-10-26 21:06:44 +00001957 Loc VarLoc = state->getLValue(D, C.getLocationContext());
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001958 const MemRegion *MR = VarLoc.getAsRegion();
1959 if (!MR)
1960 continue;
1961
Ted Kremenek632e3b72012-01-06 22:09:28 +00001962 SVal StrVal = state->getSVal(Init, C.getLocationContext());
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001963 assert(StrVal.isValid() && "Initializer string is unknown or undefined");
David Blaikie2fdacbc2013-02-20 05:52:05 +00001964 DefinedOrUnknownSVal strLength =
1965 getCStringLength(C, state, Init, StrVal).castAs<DefinedOrUnknownSVal>();
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001966
Ted Kremenek90af9092010-12-02 07:49:45 +00001967 state = state->set<CStringLength>(MR, strLength);
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001968 }
1969
Anna Zaksda4c8d62011-10-26 21:06:34 +00001970 C.addTransition(state);
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001971}
1972
Ted Kremenek49b1e382012-01-26 21:29:00 +00001973bool CStringChecker::wantsRegionChangeUpdate(ProgramStateRef state) const {
Jordan Rose0c153cb2012-11-02 01:54:06 +00001974 CStringLengthTy Entries = state->get<CStringLength>();
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001975 return !Entries.isEmpty();
1976}
1977
Ted Kremenek49b1e382012-01-26 21:29:00 +00001978ProgramStateRef
1979CStringChecker::checkRegionChanges(ProgramStateRef state,
Anna Zaksdc154152012-12-20 00:38:25 +00001980 const InvalidatedSymbols *,
Jordy Rose1fad6632011-08-27 22:51:26 +00001981 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks3d348342012-02-14 21:55:24 +00001982 ArrayRef<const MemRegion *> Regions,
Jordan Rose742920c2012-07-02 19:27:35 +00001983 const CallEvent *Call) const {
Jordan Rose0c153cb2012-11-02 01:54:06 +00001984 CStringLengthTy Entries = state->get<CStringLength>();
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001985 if (Entries.isEmpty())
1986 return state;
1987
1988 llvm::SmallPtrSet<const MemRegion *, 8> Invalidated;
1989 llvm::SmallPtrSet<const MemRegion *, 32> SuperRegions;
1990
1991 // First build sets for the changed regions and their super-regions.
Jordy Rose1fad6632011-08-27 22:51:26 +00001992 for (ArrayRef<const MemRegion *>::iterator
1993 I = Regions.begin(), E = Regions.end(); I != E; ++I) {
1994 const MemRegion *MR = *I;
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001995 Invalidated.insert(MR);
1996
1997 SuperRegions.insert(MR);
1998 while (const SubRegion *SR = dyn_cast<SubRegion>(MR)) {
1999 MR = SR->getSuperRegion();
2000 SuperRegions.insert(MR);
2001 }
2002 }
2003
Jordan Rose0c153cb2012-11-02 01:54:06 +00002004 CStringLengthTy::Factory &F = state->get_context<CStringLength>();
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002005
2006 // Then loop over the entries in the current state.
Jordan Rose0c153cb2012-11-02 01:54:06 +00002007 for (CStringLengthTy::iterator I = Entries.begin(),
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002008 E = Entries.end(); I != E; ++I) {
2009 const MemRegion *MR = I.getKey();
2010
2011 // Is this entry for a super-region of a changed region?
2012 if (SuperRegions.count(MR)) {
Ted Kremenekb3b56c62010-11-24 00:54:37 +00002013 Entries = F.remove(Entries, MR);
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002014 continue;
2015 }
2016
2017 // Is this entry for a sub-region of a changed region?
2018 const MemRegion *Super = MR;
2019 while (const SubRegion *SR = dyn_cast<SubRegion>(Super)) {
2020 Super = SR->getSuperRegion();
2021 if (Invalidated.count(Super)) {
Ted Kremenekb3b56c62010-11-24 00:54:37 +00002022 Entries = F.remove(Entries, MR);
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002023 break;
2024 }
2025 }
2026 }
2027
2028 return state->set<CStringLength>(Entries);
2029}
2030
Ted Kremenek49b1e382012-01-26 21:29:00 +00002031void CStringChecker::checkLiveSymbols(ProgramStateRef state,
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00002032 SymbolReaper &SR) const {
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002033 // Mark all symbols in our string length map as valid.
Jordan Rose0c153cb2012-11-02 01:54:06 +00002034 CStringLengthTy Entries = state->get<CStringLength>();
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002035
Jordan Rose0c153cb2012-11-02 01:54:06 +00002036 for (CStringLengthTy::iterator I = Entries.begin(), E = Entries.end();
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002037 I != E; ++I) {
2038 SVal Len = I.getData();
Jordy Rose634c12d2011-06-15 05:52:56 +00002039
Anna Zaksee1a4352011-12-06 23:12:33 +00002040 for (SymExpr::symbol_iterator si = Len.symbol_begin(),
2041 se = Len.symbol_end(); si != se; ++si)
Jordy Rose634c12d2011-06-15 05:52:56 +00002042 SR.markInUse(*si);
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002043 }
2044}
2045
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00002046void CStringChecker::checkDeadSymbols(SymbolReaper &SR,
2047 CheckerContext &C) const {
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002048 if (!SR.hasDeadSymbols())
2049 return;
2050
Ted Kremenek49b1e382012-01-26 21:29:00 +00002051 ProgramStateRef state = C.getState();
Jordan Rose0c153cb2012-11-02 01:54:06 +00002052 CStringLengthTy Entries = state->get<CStringLength>();
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002053 if (Entries.isEmpty())
2054 return;
2055
Jordan Rose0c153cb2012-11-02 01:54:06 +00002056 CStringLengthTy::Factory &F = state->get_context<CStringLength>();
2057 for (CStringLengthTy::iterator I = Entries.begin(), E = Entries.end();
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002058 I != E; ++I) {
2059 SVal Len = I.getData();
2060 if (SymbolRef Sym = Len.getAsSymbol()) {
2061 if (SR.isDead(Sym))
Ted Kremenekb3b56c62010-11-24 00:54:37 +00002062 Entries = F.remove(Entries, I.getKey());
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002063 }
2064 }
2065
2066 state = state->set<CStringLength>(Entries);
Anna Zaksda4c8d62011-10-26 21:06:34 +00002067 C.addTransition(state);
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002068}
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00002069
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002070#define REGISTER_CHECKER(name) \
2071 void ento::register##name(CheckerManager &mgr) { \
2072 CStringChecker *checker = mgr.registerChecker<CStringChecker>(); \
2073 checker->Filter.Check##name = true; \
2074 checker->Filter.CheckName##name = mgr.getCurrentCheckName(); \
2075 }
Anna Zakse0c7c272012-02-07 00:56:14 +00002076
2077REGISTER_CHECKER(CStringNullArg)
2078REGISTER_CHECKER(CStringOutOfBounds)
2079REGISTER_CHECKER(CStringBufferOverlap)
2080REGISTER_CHECKER(CStringNotNullTerm)
Anna Zakse56167e2012-02-17 22:35:31 +00002081
2082void ento::registerCStringCheckerBasic(CheckerManager &Mgr) {
2083 registerCStringNullArg(Mgr);
2084}