blob: 5130dd610aee0b3c49918011de8411251668475b [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 > {
Ahmed Charlesb8984322014-03-07 20:03:18 +000038 mutable std::unique_ptr<BugType> BT_Null, BT_Bounds, BT_Overlap,
39 BT_NotCString, BT_AdditionOverflow;
Anna Zakse0c7c272012-02-07 00:56:14 +000040
Jordy Rosedceb0cf2011-06-20 02:06:40 +000041 mutable const char *CurrentFunctionDescription;
42
Jordy Rose134a2362010-07-06 23:11:01 +000043public:
Anna Zakse0c7c272012-02-07 00:56:14 +000044 /// The filter is used to filter out the diagnostics which are not enabled by
45 /// the user.
46 struct CStringChecksFilter {
47 DefaultBool CheckCStringNullArg;
48 DefaultBool CheckCStringOutOfBounds;
49 DefaultBool CheckCStringBufferOverlap;
50 DefaultBool CheckCStringNotNullTerm;
Alexander Kornienko4aca9b12014-02-11 21:49:21 +000051
52 CheckName CheckNameCStringNullArg;
53 CheckName CheckNameCStringOutOfBounds;
54 CheckName CheckNameCStringBufferOverlap;
55 CheckName CheckNameCStringNotNullTerm;
Anna Zakse0c7c272012-02-07 00:56:14 +000056 };
57
58 CStringChecksFilter Filter;
59
Jordy Rose134a2362010-07-06 23:11:01 +000060 static void *getTag() { static int tag; return &tag; }
61
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +000062 bool evalCall(const CallExpr *CE, CheckerContext &C) const;
63 void checkPreStmt(const DeclStmt *DS, CheckerContext &C) const;
Ted Kremenek49b1e382012-01-26 21:29:00 +000064 void checkLiveSymbols(ProgramStateRef state, SymbolReaper &SR) const;
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +000065 void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const;
Ted Kremenek49b1e382012-01-26 21:29:00 +000066 bool wantsRegionChangeUpdate(ProgramStateRef state) const;
Jordy Rose2a2e21c2010-08-14 21:02:52 +000067
Ted Kremenek3a0678e2015-09-08 03:50:52 +000068 ProgramStateRef
Ted Kremenek49b1e382012-01-26 21:29:00 +000069 checkRegionChanges(ProgramStateRef state,
Anna Zaksdc154152012-12-20 00:38:25 +000070 const InvalidatedSymbols *,
Jordy Rose1fad6632011-08-27 22:51:26 +000071 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks3d348342012-02-14 21:55:24 +000072 ArrayRef<const MemRegion *> Regions,
Jordan Rose742920c2012-07-02 19:27:35 +000073 const CallEvent *Call) const;
Jordy Rose134a2362010-07-06 23:11:01 +000074
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +000075 typedef void (CStringChecker::*FnCheck)(CheckerContext &,
76 const CallExpr *) const;
Jordy Rose134a2362010-07-06 23:11:01 +000077
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +000078 void evalMemcpy(CheckerContext &C, const CallExpr *CE) const;
Lenny Maiorani79d74142011-03-31 21:36:53 +000079 void evalMempcpy(CheckerContext &C, const CallExpr *CE) const;
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +000080 void evalMemmove(CheckerContext &C, const CallExpr *CE) const;
81 void evalBcopy(CheckerContext &C, const CallExpr *CE) const;
Lenny Maiorani79d74142011-03-31 21:36:53 +000082 void evalCopyCommon(CheckerContext &C, const CallExpr *CE,
Ted Kremenek49b1e382012-01-26 21:29:00 +000083 ProgramStateRef state,
Ted Kremenek001fd5b2011-08-15 22:09:50 +000084 const Expr *Size,
85 const Expr *Source,
86 const Expr *Dest,
Lenny Maiorani79d74142011-03-31 21:36:53 +000087 bool Restricted = false,
88 bool IsMempcpy = false) const;
Jordy Rosed5d2e502010-07-08 23:57:29 +000089
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +000090 void evalMemcmp(CheckerContext &C, const CallExpr *CE) const;
Jordy Rose134a2362010-07-06 23:11:01 +000091
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +000092 void evalstrLength(CheckerContext &C, const CallExpr *CE) const;
93 void evalstrnLength(CheckerContext &C, const CallExpr *CE) const;
Ted Kremenek001fd5b2011-08-15 22:09:50 +000094 void evalstrLengthCommon(CheckerContext &C,
Ted Kremenek3a0678e2015-09-08 03:50:52 +000095 const CallExpr *CE,
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +000096 bool IsStrnlen = false) const;
Jordy Roseb052e8f2010-07-27 01:37:31 +000097
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +000098 void evalStrcpy(CheckerContext &C, const CallExpr *CE) const;
99 void evalStrncpy(CheckerContext &C, const CallExpr *CE) const;
100 void evalStpcpy(CheckerContext &C, const CallExpr *CE) const;
Ted Kremenek001fd5b2011-08-15 22:09:50 +0000101 void evalStrcpyCommon(CheckerContext &C,
102 const CallExpr *CE,
103 bool returnEnd,
104 bool isBounded,
105 bool isAppending) const;
Lenny Maiorani467dbd52011-04-09 15:12:58 +0000106
107 void evalStrcat(CheckerContext &C, const CallExpr *CE) const;
108 void evalStrncat(CheckerContext &C, const CallExpr *CE) const;
Jordy Rose722f5582010-08-16 07:51:42 +0000109
Lenny Maioranif3539ad2011-04-12 17:08:43 +0000110 void evalStrcmp(CheckerContext &C, const CallExpr *CE) const;
Lenny Maioranie553e402011-04-25 22:21:00 +0000111 void evalStrncmp(CheckerContext &C, const CallExpr *CE) const;
Lenny Maiorani4af23c82011-04-28 15:09:11 +0000112 void evalStrcasecmp(CheckerContext &C, const CallExpr *CE) const;
Lenny Maiorani0b510272011-05-02 19:05:49 +0000113 void evalStrncasecmp(CheckerContext &C, const CallExpr *CE) const;
Ted Kremenek001fd5b2011-08-15 22:09:50 +0000114 void evalStrcmpCommon(CheckerContext &C,
115 const CallExpr *CE,
116 bool isBounded = false,
117 bool ignoreCase = false) const;
Lenny Maioranif3539ad2011-04-12 17:08:43 +0000118
Jordan Rose6e3cf2b2013-04-22 23:18:42 +0000119 void evalStrsep(CheckerContext &C, const CallExpr *CE) const;
120
Devin Coughlin9165df12016-02-07 16:55:44 +0000121 void evalStdCopy(CheckerContext &C, const CallExpr *CE) const;
122 void evalStdCopyBackward(CheckerContext &C, const CallExpr *CE) const;
123 void evalStdCopyCommon(CheckerContext &C, const CallExpr *CE) const;
124
Jordy Rose134a2362010-07-06 23:11:01 +0000125 // Utility methods
Ted Kremenek49b1e382012-01-26 21:29:00 +0000126 std::pair<ProgramStateRef , ProgramStateRef >
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000127 static assumeZero(CheckerContext &C,
Ted Kremenek49b1e382012-01-26 21:29:00 +0000128 ProgramStateRef state, SVal V, QualType Ty);
Jordy Rosed5d2e502010-07-08 23:57:29 +0000129
Ted Kremenek49b1e382012-01-26 21:29:00 +0000130 static ProgramStateRef setCStringLength(ProgramStateRef state,
Ted Kremenek001fd5b2011-08-15 22:09:50 +0000131 const MemRegion *MR,
132 SVal strLength);
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000133 static SVal getCStringLengthForRegion(CheckerContext &C,
Ted Kremenek49b1e382012-01-26 21:29:00 +0000134 ProgramStateRef &state,
Ted Kremenek001fd5b2011-08-15 22:09:50 +0000135 const Expr *Ex,
136 const MemRegion *MR,
Jordy Rose634c12d2011-06-15 05:52:56 +0000137 bool hypothetical);
Ted Kremenek001fd5b2011-08-15 22:09:50 +0000138 SVal getCStringLength(CheckerContext &C,
Ted Kremenek49b1e382012-01-26 21:29:00 +0000139 ProgramStateRef &state,
Ted Kremenek001fd5b2011-08-15 22:09:50 +0000140 const Expr *Ex,
141 SVal Buf,
Jordy Rose634c12d2011-06-15 05:52:56 +0000142 bool hypothetical = false) const;
Jordy Roseb052e8f2010-07-27 01:37:31 +0000143
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000144 const StringLiteral *getCStringLiteral(CheckerContext &C,
Ted Kremenek49b1e382012-01-26 21:29:00 +0000145 ProgramStateRef &state,
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000146 const Expr *expr,
Lenny Maioranif3539ad2011-04-12 17:08:43 +0000147 SVal val) const;
148
Ted Kremenek49b1e382012-01-26 21:29:00 +0000149 static ProgramStateRef InvalidateBuffer(CheckerContext &C,
Anton Yartsev968c60a2013-11-17 09:18:48 +0000150 ProgramStateRef state,
151 const Expr *Ex, SVal V,
Devin Coughlin0da2e932015-09-24 16:52:56 +0000152 bool IsSourceBuffer,
153 const Expr *Size);
Jordy Rose722f5582010-08-16 07:51:42 +0000154
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000155 static bool SummarizeRegion(raw_ostream &os, ASTContext &Ctx,
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000156 const MemRegion *MR);
Jordy Roseb052e8f2010-07-27 01:37:31 +0000157
158 // Re-usable checks
Ted Kremenek49b1e382012-01-26 21:29:00 +0000159 ProgramStateRef checkNonNull(CheckerContext &C,
160 ProgramStateRef state,
Ted Kremenek001fd5b2011-08-15 22:09:50 +0000161 const Expr *S,
162 SVal l) const;
Ted Kremenek49b1e382012-01-26 21:29:00 +0000163 ProgramStateRef CheckLocation(CheckerContext &C,
164 ProgramStateRef state,
Ted Kremenek001fd5b2011-08-15 22:09:50 +0000165 const Expr *S,
166 SVal l,
Craig Topper0dbb7832014-05-27 02:45:47 +0000167 const char *message = nullptr) const;
Ted Kremenek49b1e382012-01-26 21:29:00 +0000168 ProgramStateRef CheckBufferAccess(CheckerContext &C,
169 ProgramStateRef state,
Ted Kremenek001fd5b2011-08-15 22:09:50 +0000170 const Expr *Size,
171 const Expr *FirstBuf,
172 const Expr *SecondBuf,
Craig Topper0dbb7832014-05-27 02:45:47 +0000173 const char *firstMessage = nullptr,
174 const char *secondMessage = nullptr,
Ted Kremenek001fd5b2011-08-15 22:09:50 +0000175 bool WarnAboutSize = false) const;
176
Ted Kremenek49b1e382012-01-26 21:29:00 +0000177 ProgramStateRef CheckBufferAccess(CheckerContext &C,
178 ProgramStateRef state,
Ted Kremenek001fd5b2011-08-15 22:09:50 +0000179 const Expr *Size,
180 const Expr *Buf,
Craig Topper0dbb7832014-05-27 02:45:47 +0000181 const char *message = nullptr,
Ted Kremenek001fd5b2011-08-15 22:09:50 +0000182 bool WarnAboutSize = false) const {
Jordy Rosedceb0cf2011-06-20 02:06:40 +0000183 // This is a convenience override.
Craig Topper0dbb7832014-05-27 02:45:47 +0000184 return CheckBufferAccess(C, state, Size, Buf, nullptr, message, nullptr,
Jordy Rose328deee2011-06-20 03:49:16 +0000185 WarnAboutSize);
Jordy Rosedceb0cf2011-06-20 02:06:40 +0000186 }
Ted Kremenek49b1e382012-01-26 21:29:00 +0000187 ProgramStateRef CheckOverlap(CheckerContext &C,
188 ProgramStateRef state,
Ted Kremenek001fd5b2011-08-15 22:09:50 +0000189 const Expr *Size,
190 const Expr *First,
191 const Expr *Second) const;
192 void emitOverlapBug(CheckerContext &C,
Ted Kremenek49b1e382012-01-26 21:29:00 +0000193 ProgramStateRef state,
Ted Kremenek001fd5b2011-08-15 22:09:50 +0000194 const Stmt *First,
195 const Stmt *Second) const;
196
Ted Kremenek49b1e382012-01-26 21:29:00 +0000197 ProgramStateRef checkAdditionOverflow(CheckerContext &C,
198 ProgramStateRef state,
Ted Kremenek001fd5b2011-08-15 22:09:50 +0000199 NonLoc left,
200 NonLoc right) const;
Devin Coughlin0da2e932015-09-24 16:52:56 +0000201
202 // Return true if the destination buffer of the copy function may be in bound.
203 // Expects SVal of Size to be positive and unsigned.
204 // Expects SVal of FirstBuf to be a FieldRegion.
205 static bool IsFirstBufInBound(CheckerContext &C,
206 ProgramStateRef state,
207 const Expr *FirstBuf,
208 const Expr *Size);
Jordy Rose134a2362010-07-06 23:11:01 +0000209};
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000210
Jordy Rose134a2362010-07-06 23:11:01 +0000211} //end anonymous namespace
212
Jordan Rose0c153cb2012-11-02 01:54:06 +0000213REGISTER_MAP_WITH_PROGRAMSTATE(CStringLength, const MemRegion *, SVal)
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000214
Jordy Rosed5d2e502010-07-08 23:57:29 +0000215//===----------------------------------------------------------------------===//
216// Individual checks and utility methods.
217//===----------------------------------------------------------------------===//
218
Ted Kremenek49b1e382012-01-26 21:29:00 +0000219std::pair<ProgramStateRef , ProgramStateRef >
220CStringChecker::assumeZero(CheckerContext &C, ProgramStateRef state, SVal V,
Jordy Rosed5d2e502010-07-08 23:57:29 +0000221 QualType Ty) {
David Blaikie05785d12013-02-20 22:23:23 +0000222 Optional<DefinedSVal> val = V.getAs<DefinedSVal>();
Ted Kremenek90af9092010-12-02 07:49:45 +0000223 if (!val)
Ted Kremenek49b1e382012-01-26 21:29:00 +0000224 return std::pair<ProgramStateRef , ProgramStateRef >(state, state);
Jordy Rose33c829a2010-07-07 07:48:06 +0000225
Ted Kremenek90af9092010-12-02 07:49:45 +0000226 SValBuilder &svalBuilder = C.getSValBuilder();
227 DefinedOrUnknownSVal zero = svalBuilder.makeZeroVal(Ty);
228 return state->assume(svalBuilder.evalEQ(state, *val, zero));
Jordy Rosed5d2e502010-07-08 23:57:29 +0000229}
Jordy Rose33c829a2010-07-07 07:48:06 +0000230
Ted Kremenek49b1e382012-01-26 21:29:00 +0000231ProgramStateRef CStringChecker::checkNonNull(CheckerContext &C,
232 ProgramStateRef state,
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000233 const Expr *S, SVal l) const {
Jordy Rosed5d2e502010-07-08 23:57:29 +0000234 // If a previous check has failed, propagate the failure.
235 if (!state)
Craig Topper0dbb7832014-05-27 02:45:47 +0000236 return nullptr;
Jordy Rosed5d2e502010-07-08 23:57:29 +0000237
Ted Kremenek49b1e382012-01-26 21:29:00 +0000238 ProgramStateRef stateNull, stateNonNull;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000239 std::tie(stateNull, stateNonNull) = assumeZero(C, state, l, S->getType());
Jordy Rosed5d2e502010-07-08 23:57:29 +0000240
241 if (stateNull && !stateNonNull) {
Anna Zakse0c7c272012-02-07 00:56:14 +0000242 if (!Filter.CheckCStringNullArg)
Craig Topper0dbb7832014-05-27 02:45:47 +0000243 return nullptr;
Anna Zakse0c7c272012-02-07 00:56:14 +0000244
Devin Coughline39bd402015-09-16 22:03:05 +0000245 ExplodedNode *N = C.generateErrorNode(stateNull);
Jordy Rose33c829a2010-07-07 07:48:06 +0000246 if (!N)
Craig Topper0dbb7832014-05-27 02:45:47 +0000247 return nullptr;
Jordy Rose33c829a2010-07-07 07:48:06 +0000248
Jordy Rosed5d2e502010-07-08 23:57:29 +0000249 if (!BT_Null)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000250 BT_Null.reset(new BuiltinBug(
251 Filter.CheckNameCStringNullArg, categories::UnixAPI,
252 "Null pointer argument in call to byte string function"));
Jordy Rose33c829a2010-07-07 07:48:06 +0000253
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000254 SmallString<80> buf;
Jordy Rosedceb0cf2011-06-20 02:06:40 +0000255 llvm::raw_svector_ostream os(buf);
256 assert(CurrentFunctionDescription);
257 os << "Null pointer argument in call to " << CurrentFunctionDescription;
258
Jordy Rose33c829a2010-07-07 07:48:06 +0000259 // Generate a report for this bug.
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000260 BuiltinBug *BT = static_cast<BuiltinBug*>(BT_Null.get());
Aaron Ballman8d3a7a52015-06-23 13:15:32 +0000261 auto report = llvm::make_unique<BugReport>(*BT, os.str(), N);
Jordy Rose33c829a2010-07-07 07:48:06 +0000262
263 report->addRange(S->getSourceRange());
Jordan Rosea0f7d352012-08-28 00:50:51 +0000264 bugreporter::trackNullOrUndefValue(N, S, *report);
Aaron Ballman8d3a7a52015-06-23 13:15:32 +0000265 C.emitReport(std::move(report));
Craig Topper0dbb7832014-05-27 02:45:47 +0000266 return nullptr;
Jordy Rose33c829a2010-07-07 07:48:06 +0000267 }
268
269 // From here on, assume that the value is non-null.
Jordy Rosed5d2e502010-07-08 23:57:29 +0000270 assert(stateNonNull);
271 return stateNonNull;
Jordy Rose33c829a2010-07-07 07:48:06 +0000272}
273
Jordy Rose134a2362010-07-06 23:11:01 +0000274// FIXME: This was originally copied from ArrayBoundChecker.cpp. Refactor?
Ted Kremenek49b1e382012-01-26 21:29:00 +0000275ProgramStateRef CStringChecker::CheckLocation(CheckerContext &C,
276 ProgramStateRef state,
Jordy Rose722f5582010-08-16 07:51:42 +0000277 const Expr *S, SVal l,
Jordy Rosedceb0cf2011-06-20 02:06:40 +0000278 const char *warningMsg) const {
Jordy Rosed5d2e502010-07-08 23:57:29 +0000279 // If a previous check has failed, propagate the failure.
280 if (!state)
Craig Topper0dbb7832014-05-27 02:45:47 +0000281 return nullptr;
Jordy Rosed5d2e502010-07-08 23:57:29 +0000282
Jordy Rose134a2362010-07-06 23:11:01 +0000283 // Check for out of bound array element access.
284 const MemRegion *R = l.getAsRegion();
285 if (!R)
286 return state;
287
Jordy Rose134a2362010-07-06 23:11:01 +0000288 const ElementRegion *ER = dyn_cast<ElementRegion>(R);
289 if (!ER)
290 return state;
291
Zhongxing Xu8de0a3d2010-08-11 06:10:55 +0000292 assert(ER->getValueType() == C.getASTContext().CharTy &&
Jordy Rose134a2362010-07-06 23:11:01 +0000293 "CheckLocation should only be called with char* ElementRegions");
294
295 // Get the size of the array.
Ted Kremenek90af9092010-12-02 07:49:45 +0000296 const SubRegion *superReg = cast<SubRegion>(ER->getSuperRegion());
297 SValBuilder &svalBuilder = C.getSValBuilder();
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000298 SVal Extent =
Jordy Rose455bd582011-06-16 05:51:02 +0000299 svalBuilder.convertToArrayIndex(superReg->getExtent(svalBuilder));
David Blaikie2fdacbc2013-02-20 05:52:05 +0000300 DefinedOrUnknownSVal Size = Extent.castAs<DefinedOrUnknownSVal>();
Jordy Rose134a2362010-07-06 23:11:01 +0000301
302 // Get the index of the accessed element.
David Blaikie87396b92013-02-21 22:23:56 +0000303 DefinedOrUnknownSVal Idx = ER->getIndex().castAs<DefinedOrUnknownSVal>();
Jordy Rose134a2362010-07-06 23:11:01 +0000304
Ted Kremenek49b1e382012-01-26 21:29:00 +0000305 ProgramStateRef StInBound = state->assumeInBound(Idx, Size, true);
306 ProgramStateRef StOutBound = state->assumeInBound(Idx, Size, false);
Jordy Rose134a2362010-07-06 23:11:01 +0000307 if (StOutBound && !StInBound) {
Devin Coughline39bd402015-09-16 22:03:05 +0000308 ExplodedNode *N = C.generateErrorNode(StOutBound);
Jordy Rose134a2362010-07-06 23:11:01 +0000309 if (!N)
Craig Topper0dbb7832014-05-27 02:45:47 +0000310 return nullptr;
Jordy Rose134a2362010-07-06 23:11:01 +0000311
Jordy Rosedceb0cf2011-06-20 02:06:40 +0000312 if (!BT_Bounds) {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000313 BT_Bounds.reset(new BuiltinBug(
314 Filter.CheckNameCStringOutOfBounds, "Out-of-bound array access",
315 "Byte string function accesses out-of-bound array element"));
Jordy Rosedceb0cf2011-06-20 02:06:40 +0000316 }
317 BuiltinBug *BT = static_cast<BuiltinBug*>(BT_Bounds.get());
318
319 // Generate a report for this bug.
Aaron Ballman8d3a7a52015-06-23 13:15:32 +0000320 std::unique_ptr<BugReport> report;
Jordy Rosedceb0cf2011-06-20 02:06:40 +0000321 if (warningMsg) {
Aaron Ballman8d3a7a52015-06-23 13:15:32 +0000322 report = llvm::make_unique<BugReport>(*BT, warningMsg, N);
Jordy Rose722f5582010-08-16 07:51:42 +0000323 } else {
Jordy Rosedceb0cf2011-06-20 02:06:40 +0000324 assert(CurrentFunctionDescription);
325 assert(CurrentFunctionDescription[0] != '\0');
326
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000327 SmallString<80> buf;
Jordy Rosedceb0cf2011-06-20 02:06:40 +0000328 llvm::raw_svector_ostream os(buf);
Jordan Rose4938f272013-02-09 10:09:43 +0000329 os << toUppercase(CurrentFunctionDescription[0])
Jordy Rosedceb0cf2011-06-20 02:06:40 +0000330 << &CurrentFunctionDescription[1]
331 << " accesses out-of-bound array element";
Aaron Ballman8d3a7a52015-06-23 13:15:32 +0000332 report = llvm::make_unique<BugReport>(*BT, os.str(), N);
Jordy Rose722f5582010-08-16 07:51:42 +0000333 }
Jordy Rose134a2362010-07-06 23:11:01 +0000334
335 // FIXME: It would be nice to eventually make this diagnostic more clear,
336 // e.g., by referencing the original declaration or by saying *why* this
337 // reference is outside the range.
338
Jordy Rose134a2362010-07-06 23:11:01 +0000339 report->addRange(S->getSourceRange());
Aaron Ballman8d3a7a52015-06-23 13:15:32 +0000340 C.emitReport(std::move(report));
Craig Topper0dbb7832014-05-27 02:45:47 +0000341 return nullptr;
Jordy Rose134a2362010-07-06 23:11:01 +0000342 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000343
Jordy Rose134a2362010-07-06 23:11:01 +0000344 // Array bound check succeeded. From this point forward the array bound
345 // should always succeed.
346 return StInBound;
347}
348
Ted Kremenek49b1e382012-01-26 21:29:00 +0000349ProgramStateRef CStringChecker::CheckBufferAccess(CheckerContext &C,
350 ProgramStateRef state,
Jordy Rose134a2362010-07-06 23:11:01 +0000351 const Expr *Size,
352 const Expr *FirstBuf,
Jordy Rose722f5582010-08-16 07:51:42 +0000353 const Expr *SecondBuf,
Jordy Rosedceb0cf2011-06-20 02:06:40 +0000354 const char *firstMessage,
Jordy Rose328deee2011-06-20 03:49:16 +0000355 const char *secondMessage,
356 bool WarnAboutSize) const {
Jordy Rosed5d2e502010-07-08 23:57:29 +0000357 // If a previous check has failed, propagate the failure.
358 if (!state)
Craig Topper0dbb7832014-05-27 02:45:47 +0000359 return nullptr;
Jordy Rosed5d2e502010-07-08 23:57:29 +0000360
Ted Kremenek90af9092010-12-02 07:49:45 +0000361 SValBuilder &svalBuilder = C.getSValBuilder();
Jordy Rose455bd582011-06-16 05:51:02 +0000362 ASTContext &Ctx = svalBuilder.getContext();
Ted Kremenek632e3b72012-01-06 22:09:28 +0000363 const LocationContext *LCtx = C.getLocationContext();
Jordy Rose134a2362010-07-06 23:11:01 +0000364
Ted Kremenek90af9092010-12-02 07:49:45 +0000365 QualType sizeTy = Size->getType();
Jordy Rose134a2362010-07-06 23:11:01 +0000366 QualType PtrTy = Ctx.getPointerType(Ctx.CharTy);
367
Jordy Rose33c829a2010-07-07 07:48:06 +0000368 // Check that the first buffer is non-null.
Ted Kremenek632e3b72012-01-06 22:09:28 +0000369 SVal BufVal = state->getSVal(FirstBuf, LCtx);
Ted Kremenek90af9092010-12-02 07:49:45 +0000370 state = checkNonNull(C, state, FirstBuf, BufVal);
Jordy Rose33c829a2010-07-07 07:48:06 +0000371 if (!state)
Craig Topper0dbb7832014-05-27 02:45:47 +0000372 return nullptr;
Jordy Rose33c829a2010-07-07 07:48:06 +0000373
Anna Zakse0c7c272012-02-07 00:56:14 +0000374 // If out-of-bounds checking is turned off, skip the rest.
375 if (!Filter.CheckCStringOutOfBounds)
376 return state;
377
Jordy Rosed5d2e502010-07-08 23:57:29 +0000378 // Get the access length and make sure it is known.
Jordy Rosedceb0cf2011-06-20 02:06:40 +0000379 // FIXME: This assumes the caller has already checked that the access length
380 // is positive. And that it's unsigned.
Ted Kremenek632e3b72012-01-06 22:09:28 +0000381 SVal LengthVal = state->getSVal(Size, LCtx);
David Blaikie05785d12013-02-20 22:23:23 +0000382 Optional<NonLoc> Length = LengthVal.getAs<NonLoc>();
Jordy Rosed5d2e502010-07-08 23:57:29 +0000383 if (!Length)
384 return state;
385
Jordy Rose134a2362010-07-06 23:11:01 +0000386 // Compute the offset of the last element to be accessed: size-1.
David Blaikie2fdacbc2013-02-20 05:52:05 +0000387 NonLoc One = svalBuilder.makeIntVal(1, sizeTy).castAs<NonLoc>();
388 NonLoc LastOffset = svalBuilder
389 .evalBinOpNN(state, BO_Sub, *Length, One, sizeTy).castAs<NonLoc>();
Jordy Rose134a2362010-07-06 23:11:01 +0000390
Chris Lattner57540c52011-04-15 05:22:18 +0000391 // Check that the first buffer is sufficiently long.
Ted Kremenek90af9092010-12-02 07:49:45 +0000392 SVal BufStart = svalBuilder.evalCast(BufVal, PtrTy, FirstBuf->getType());
David Blaikie05785d12013-02-20 22:23:23 +0000393 if (Optional<Loc> BufLoc = BufStart.getAs<Loc>()) {
Jordy Rose328deee2011-06-20 03:49:16 +0000394 const Expr *warningExpr = (WarnAboutSize ? Size : FirstBuf);
395
Ted Kremenek90af9092010-12-02 07:49:45 +0000396 SVal BufEnd = svalBuilder.evalBinOpLN(state, BO_Add, *BufLoc,
397 LastOffset, PtrTy);
Jordy Rose328deee2011-06-20 03:49:16 +0000398 state = CheckLocation(C, state, warningExpr, BufEnd, firstMessage);
Jordy Rose134a2362010-07-06 23:11:01 +0000399
Jordy Roseafdb0532010-08-05 23:11:30 +0000400 // If the buffer isn't large enough, abort.
401 if (!state)
Craig Topper0dbb7832014-05-27 02:45:47 +0000402 return nullptr;
Jordy Roseafdb0532010-08-05 23:11:30 +0000403 }
Jordy Rose134a2362010-07-06 23:11:01 +0000404
405 // If there's a second buffer, check it as well.
406 if (SecondBuf) {
Ted Kremenek632e3b72012-01-06 22:09:28 +0000407 BufVal = state->getSVal(SecondBuf, LCtx);
Ted Kremenek90af9092010-12-02 07:49:45 +0000408 state = checkNonNull(C, state, SecondBuf, BufVal);
Jordy Rose33c829a2010-07-07 07:48:06 +0000409 if (!state)
Craig Topper0dbb7832014-05-27 02:45:47 +0000410 return nullptr;
Jordy Rose33c829a2010-07-07 07:48:06 +0000411
Ted Kremenek90af9092010-12-02 07:49:45 +0000412 BufStart = svalBuilder.evalCast(BufVal, PtrTy, SecondBuf->getType());
David Blaikie05785d12013-02-20 22:23:23 +0000413 if (Optional<Loc> BufLoc = BufStart.getAs<Loc>()) {
Jordy Rose328deee2011-06-20 03:49:16 +0000414 const Expr *warningExpr = (WarnAboutSize ? Size : SecondBuf);
415
Ted Kremenek90af9092010-12-02 07:49:45 +0000416 SVal BufEnd = svalBuilder.evalBinOpLN(state, BO_Add, *BufLoc,
417 LastOffset, PtrTy);
Jordy Rose328deee2011-06-20 03:49:16 +0000418 state = CheckLocation(C, state, warningExpr, BufEnd, secondMessage);
Jordy Roseafdb0532010-08-05 23:11:30 +0000419 }
Jordy Rose134a2362010-07-06 23:11:01 +0000420 }
421
422 // Large enough or not, return this state!
423 return state;
424}
425
Ted Kremenek49b1e382012-01-26 21:29:00 +0000426ProgramStateRef CStringChecker::CheckOverlap(CheckerContext &C,
427 ProgramStateRef state,
Jordy Rosed5d2e502010-07-08 23:57:29 +0000428 const Expr *Size,
Jordy Rose134a2362010-07-06 23:11:01 +0000429 const Expr *First,
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000430 const Expr *Second) const {
Anna Zakse0c7c272012-02-07 00:56:14 +0000431 if (!Filter.CheckCStringBufferOverlap)
432 return state;
433
Jordy Rose134a2362010-07-06 23:11:01 +0000434 // Do a simple check for overlap: if the two arguments are from the same
435 // buffer, see if the end of the first is greater than the start of the second
436 // or vice versa.
437
Jordy Rosed5d2e502010-07-08 23:57:29 +0000438 // If a previous check has failed, propagate the failure.
439 if (!state)
Craig Topper0dbb7832014-05-27 02:45:47 +0000440 return nullptr;
Jordy Rosed5d2e502010-07-08 23:57:29 +0000441
Ted Kremenek49b1e382012-01-26 21:29:00 +0000442 ProgramStateRef stateTrue, stateFalse;
Jordy Rose134a2362010-07-06 23:11:01 +0000443
444 // Get the buffer values and make sure they're known locations.
Ted Kremenek632e3b72012-01-06 22:09:28 +0000445 const LocationContext *LCtx = C.getLocationContext();
446 SVal firstVal = state->getSVal(First, LCtx);
447 SVal secondVal = state->getSVal(Second, LCtx);
Jordy Rose134a2362010-07-06 23:11:01 +0000448
David Blaikie05785d12013-02-20 22:23:23 +0000449 Optional<Loc> firstLoc = firstVal.getAs<Loc>();
Ted Kremenek90af9092010-12-02 07:49:45 +0000450 if (!firstLoc)
Jordy Rose134a2362010-07-06 23:11:01 +0000451 return state;
452
David Blaikie05785d12013-02-20 22:23:23 +0000453 Optional<Loc> secondLoc = secondVal.getAs<Loc>();
Ted Kremenek90af9092010-12-02 07:49:45 +0000454 if (!secondLoc)
Jordy Rose134a2362010-07-06 23:11:01 +0000455 return state;
456
457 // Are the two values the same?
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000458 SValBuilder &svalBuilder = C.getSValBuilder();
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000459 std::tie(stateTrue, stateFalse) =
Ted Kremenek90af9092010-12-02 07:49:45 +0000460 state->assume(svalBuilder.evalEQ(state, *firstLoc, *secondLoc));
Jordy Rose134a2362010-07-06 23:11:01 +0000461
462 if (stateTrue && !stateFalse) {
463 // If the values are known to be equal, that's automatically an overlap.
Ted Kremenek90af9092010-12-02 07:49:45 +0000464 emitOverlapBug(C, stateTrue, First, Second);
Craig Topper0dbb7832014-05-27 02:45:47 +0000465 return nullptr;
Jordy Rose134a2362010-07-06 23:11:01 +0000466 }
467
Ted Kremenekc5bea1e2010-12-01 22:16:56 +0000468 // assume the two expressions are not equal.
Jordy Rose134a2362010-07-06 23:11:01 +0000469 assert(stateFalse);
470 state = stateFalse;
471
472 // Which value comes first?
Jordy Rose0585a612011-06-16 05:56:50 +0000473 QualType cmpTy = svalBuilder.getConditionType();
Ted Kremenek90af9092010-12-02 07:49:45 +0000474 SVal reverse = svalBuilder.evalBinOpLL(state, BO_GT,
475 *firstLoc, *secondLoc, cmpTy);
David Blaikie05785d12013-02-20 22:23:23 +0000476 Optional<DefinedOrUnknownSVal> reverseTest =
David Blaikie2fdacbc2013-02-20 05:52:05 +0000477 reverse.getAs<DefinedOrUnknownSVal>();
Ted Kremenek90af9092010-12-02 07:49:45 +0000478 if (!reverseTest)
Jordy Rose134a2362010-07-06 23:11:01 +0000479 return state;
480
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000481 std::tie(stateTrue, stateFalse) = state->assume(*reverseTest);
Jordy Rose134a2362010-07-06 23:11:01 +0000482 if (stateTrue) {
483 if (stateFalse) {
484 // If we don't know which one comes first, we can't perform this test.
485 return state;
486 } else {
Ted Kremenek90af9092010-12-02 07:49:45 +0000487 // Switch the values so that firstVal is before secondVal.
David Blaikie2fdacbc2013-02-20 05:52:05 +0000488 std::swap(firstLoc, secondLoc);
Jordy Rose134a2362010-07-06 23:11:01 +0000489
490 // Switch the Exprs as well, so that they still correspond.
David Blaikie2fdacbc2013-02-20 05:52:05 +0000491 std::swap(First, Second);
Jordy Rose134a2362010-07-06 23:11:01 +0000492 }
493 }
494
495 // Get the length, and make sure it too is known.
Ted Kremenek632e3b72012-01-06 22:09:28 +0000496 SVal LengthVal = state->getSVal(Size, LCtx);
David Blaikie05785d12013-02-20 22:23:23 +0000497 Optional<NonLoc> Length = LengthVal.getAs<NonLoc>();
Jordy Rose134a2362010-07-06 23:11:01 +0000498 if (!Length)
499 return state;
500
501 // Convert the first buffer's start address to char*.
502 // Bail out if the cast fails.
Jordy Rose0585a612011-06-16 05:56:50 +0000503 ASTContext &Ctx = svalBuilder.getContext();
Jordy Rose134a2362010-07-06 23:11:01 +0000504 QualType CharPtrTy = Ctx.getPointerType(Ctx.CharTy);
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000505 SVal FirstStart = svalBuilder.evalCast(*firstLoc, CharPtrTy,
Jordy Rose455bd582011-06-16 05:51:02 +0000506 First->getType());
David Blaikie05785d12013-02-20 22:23:23 +0000507 Optional<Loc> FirstStartLoc = FirstStart.getAs<Loc>();
Jordy Rose134a2362010-07-06 23:11:01 +0000508 if (!FirstStartLoc)
509 return state;
510
511 // Compute the end of the first buffer. Bail out if THAT fails.
Ted Kremenek90af9092010-12-02 07:49:45 +0000512 SVal FirstEnd = svalBuilder.evalBinOpLN(state, BO_Add,
Jordy Rose134a2362010-07-06 23:11:01 +0000513 *FirstStartLoc, *Length, CharPtrTy);
David Blaikie05785d12013-02-20 22:23:23 +0000514 Optional<Loc> FirstEndLoc = FirstEnd.getAs<Loc>();
Jordy Rose134a2362010-07-06 23:11:01 +0000515 if (!FirstEndLoc)
516 return state;
517
518 // Is the end of the first buffer past the start of the second buffer?
Ted Kremenek90af9092010-12-02 07:49:45 +0000519 SVal Overlap = svalBuilder.evalBinOpLL(state, BO_GT,
520 *FirstEndLoc, *secondLoc, cmpTy);
David Blaikie05785d12013-02-20 22:23:23 +0000521 Optional<DefinedOrUnknownSVal> OverlapTest =
David Blaikie2fdacbc2013-02-20 05:52:05 +0000522 Overlap.getAs<DefinedOrUnknownSVal>();
Jordy Rose134a2362010-07-06 23:11:01 +0000523 if (!OverlapTest)
524 return state;
525
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000526 std::tie(stateTrue, stateFalse) = state->assume(*OverlapTest);
Jordy Rose134a2362010-07-06 23:11:01 +0000527
528 if (stateTrue && !stateFalse) {
529 // Overlap!
Ted Kremenek90af9092010-12-02 07:49:45 +0000530 emitOverlapBug(C, stateTrue, First, Second);
Craig Topper0dbb7832014-05-27 02:45:47 +0000531 return nullptr;
Jordy Rose134a2362010-07-06 23:11:01 +0000532 }
533
Ted Kremenekc5bea1e2010-12-01 22:16:56 +0000534 // assume the two expressions don't overlap.
Jordy Rose134a2362010-07-06 23:11:01 +0000535 assert(stateFalse);
536 return stateFalse;
537}
538
Ted Kremenek49b1e382012-01-26 21:29:00 +0000539void CStringChecker::emitOverlapBug(CheckerContext &C, ProgramStateRef state,
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000540 const Stmt *First, const Stmt *Second) const {
Devin Coughline39bd402015-09-16 22:03:05 +0000541 ExplodedNode *N = C.generateErrorNode(state);
Jordy Rose134a2362010-07-06 23:11:01 +0000542 if (!N)
543 return;
544
545 if (!BT_Overlap)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000546 BT_Overlap.reset(new BugType(Filter.CheckNameCStringBufferOverlap,
547 categories::UnixAPI, "Improper arguments"));
Jordy Rose134a2362010-07-06 23:11:01 +0000548
549 // Generate a report for this bug.
Aaron Ballman8d3a7a52015-06-23 13:15:32 +0000550 auto report = llvm::make_unique<BugReport>(
551 *BT_Overlap, "Arguments must not be overlapping buffers", N);
Jordy Rose134a2362010-07-06 23:11:01 +0000552 report->addRange(First->getSourceRange());
553 report->addRange(Second->getSourceRange());
554
Aaron Ballman8d3a7a52015-06-23 13:15:32 +0000555 C.emitReport(std::move(report));
Jordy Rose134a2362010-07-06 23:11:01 +0000556}
557
Ted Kremenek49b1e382012-01-26 21:29:00 +0000558ProgramStateRef CStringChecker::checkAdditionOverflow(CheckerContext &C,
559 ProgramStateRef state,
Jordy Rose634c12d2011-06-15 05:52:56 +0000560 NonLoc left,
561 NonLoc right) const {
Anna Zakse0c7c272012-02-07 00:56:14 +0000562 // If out-of-bounds checking is turned off, skip the rest.
563 if (!Filter.CheckCStringOutOfBounds)
564 return state;
565
Jordy Rose634c12d2011-06-15 05:52:56 +0000566 // If a previous check has failed, propagate the failure.
567 if (!state)
Craig Topper0dbb7832014-05-27 02:45:47 +0000568 return nullptr;
Jordy Rose634c12d2011-06-15 05:52:56 +0000569
570 SValBuilder &svalBuilder = C.getSValBuilder();
571 BasicValueFactory &BVF = svalBuilder.getBasicValueFactory();
572
573 QualType sizeTy = svalBuilder.getContext().getSizeType();
574 const llvm::APSInt &maxValInt = BVF.getMaxValue(sizeTy);
575 NonLoc maxVal = svalBuilder.makeIntVal(maxValInt);
576
Anna Zaks7c96b7d2011-12-11 18:43:40 +0000577 SVal maxMinusRight;
David Blaikie2fdacbc2013-02-20 05:52:05 +0000578 if (right.getAs<nonloc::ConcreteInt>()) {
Anna Zaks7c96b7d2011-12-11 18:43:40 +0000579 maxMinusRight = svalBuilder.evalBinOpNN(state, BO_Sub, maxVal, right,
580 sizeTy);
581 } else {
Jordy Rose634c12d2011-06-15 05:52:56 +0000582 // Try switching the operands. (The order of these two assignments is
583 // important!)
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000584 maxMinusRight = svalBuilder.evalBinOpNN(state, BO_Sub, maxVal, left,
Jordy Rose634c12d2011-06-15 05:52:56 +0000585 sizeTy);
586 left = right;
587 }
588
David Blaikie05785d12013-02-20 22:23:23 +0000589 if (Optional<NonLoc> maxMinusRightNL = maxMinusRight.getAs<NonLoc>()) {
Jordy Rose634c12d2011-06-15 05:52:56 +0000590 QualType cmpTy = svalBuilder.getConditionType();
591 // If left > max - right, we have an overflow.
592 SVal willOverflow = svalBuilder.evalBinOpNN(state, BO_GT, left,
593 *maxMinusRightNL, cmpTy);
594
Ted Kremenek49b1e382012-01-26 21:29:00 +0000595 ProgramStateRef stateOverflow, stateOkay;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000596 std::tie(stateOverflow, stateOkay) =
David Blaikie2fdacbc2013-02-20 05:52:05 +0000597 state->assume(willOverflow.castAs<DefinedOrUnknownSVal>());
Jordy Rose634c12d2011-06-15 05:52:56 +0000598
599 if (stateOverflow && !stateOkay) {
600 // We have an overflow. Emit a bug report.
Devin Coughline39bd402015-09-16 22:03:05 +0000601 ExplodedNode *N = C.generateErrorNode(stateOverflow);
Jordy Rose634c12d2011-06-15 05:52:56 +0000602 if (!N)
Craig Topper0dbb7832014-05-27 02:45:47 +0000603 return nullptr;
Jordy Rose634c12d2011-06-15 05:52:56 +0000604
605 if (!BT_AdditionOverflow)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000606 BT_AdditionOverflow.reset(
607 new BuiltinBug(Filter.CheckNameCStringOutOfBounds, "API",
608 "Sum of expressions causes overflow"));
Jordy Rose634c12d2011-06-15 05:52:56 +0000609
Jordy Rose634c12d2011-06-15 05:52:56 +0000610 // This isn't a great error message, but this should never occur in real
611 // code anyway -- you'd have to create a buffer longer than a size_t can
612 // represent, which is sort of a contradiction.
Jordy Rose789adbb2011-06-20 03:51:53 +0000613 const char *warning =
614 "This expression will create a string whose length is too big to "
615 "be represented as a size_t";
Jordy Rose634c12d2011-06-15 05:52:56 +0000616
617 // Generate a report for this bug.
Aaron Ballman8d3a7a52015-06-23 13:15:32 +0000618 C.emitReport(
619 llvm::make_unique<BugReport>(*BT_AdditionOverflow, warning, N));
Jordy Rose634c12d2011-06-15 05:52:56 +0000620
Craig Topper0dbb7832014-05-27 02:45:47 +0000621 return nullptr;
Jordy Rose634c12d2011-06-15 05:52:56 +0000622 }
623
624 // From now on, assume an overflow didn't occur.
625 assert(stateOkay);
626 state = stateOkay;
627 }
628
629 return state;
630}
631
Ted Kremenek49b1e382012-01-26 21:29:00 +0000632ProgramStateRef CStringChecker::setCStringLength(ProgramStateRef state,
Jordy Rose722f5582010-08-16 07:51:42 +0000633 const MemRegion *MR,
Ted Kremenek90af9092010-12-02 07:49:45 +0000634 SVal strLength) {
635 assert(!strLength.isUndef() && "Attempt to set an undefined string length");
Jordy Rose722f5582010-08-16 07:51:42 +0000636
637 MR = MR->StripCasts();
638
639 switch (MR->getKind()) {
640 case MemRegion::StringRegionKind:
641 // FIXME: This can happen if we strcpy() into a string region. This is
642 // undefined [C99 6.4.5p6], but we should still warn about it.
643 return state;
644
645 case MemRegion::SymbolicRegionKind:
646 case MemRegion::AllocaRegionKind:
647 case MemRegion::VarRegionKind:
648 case MemRegion::FieldRegionKind:
649 case MemRegion::ObjCIvarRegionKind:
Jordy Rose0e9fb282011-06-15 05:14:03 +0000650 // These are the types we can currently track string lengths for.
651 break;
Jordy Rose722f5582010-08-16 07:51:42 +0000652
653 case MemRegion::ElementRegionKind:
654 // FIXME: Handle element regions by upper-bounding the parent region's
655 // string length.
656 return state;
657
658 default:
659 // Other regions (mostly non-data) can't have a reliable C string length.
660 // For now, just ignore the change.
661 // FIXME: These are rare but not impossible. We should output some kind of
662 // warning for things like strcpy((char[]){'a', 0}, "b");
663 return state;
664 }
Jordy Rose0e9fb282011-06-15 05:14:03 +0000665
666 if (strLength.isUnknown())
667 return state->remove<CStringLength>(MR);
668
669 return state->set<CStringLength>(MR, strLength);
Jordy Rose722f5582010-08-16 07:51:42 +0000670}
671
Ted Kremenek90af9092010-12-02 07:49:45 +0000672SVal CStringChecker::getCStringLengthForRegion(CheckerContext &C,
Ted Kremenek49b1e382012-01-26 21:29:00 +0000673 ProgramStateRef &state,
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000674 const Expr *Ex,
Jordy Rose634c12d2011-06-15 05:52:56 +0000675 const MemRegion *MR,
676 bool hypothetical) {
677 if (!hypothetical) {
678 // If there's a recorded length, go ahead and return it.
679 const SVal *Recorded = state->get<CStringLength>(MR);
680 if (Recorded)
681 return *Recorded;
682 }
Jordan Rose60619a62013-08-19 16:27:34 +0000683
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000684 // Otherwise, get a new symbol and update the state.
Ted Kremenek90af9092010-12-02 07:49:45 +0000685 SValBuilder &svalBuilder = C.getSValBuilder();
686 QualType sizeTy = svalBuilder.getContext().getSizeType();
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000687 SVal strLength = svalBuilder.getMetadataSymbolVal(CStringChecker::getTag(),
Ted Kremenekd94854a2012-08-22 06:26:15 +0000688 MR, Ex, sizeTy,
689 C.blockCount());
Jordy Rose634c12d2011-06-15 05:52:56 +0000690
Jordan Rose60619a62013-08-19 16:27:34 +0000691 if (!hypothetical) {
692 if (Optional<NonLoc> strLn = strLength.getAs<NonLoc>()) {
693 // In case of unbounded calls strlen etc bound the range to SIZE_MAX/4
694 BasicValueFactory &BVF = svalBuilder.getBasicValueFactory();
695 const llvm::APSInt &maxValInt = BVF.getMaxValue(sizeTy);
696 llvm::APSInt fourInt = APSIntType(maxValInt).getValue(4);
697 const llvm::APSInt *maxLengthInt = BVF.evalAPSInt(BO_Div, maxValInt,
698 fourInt);
699 NonLoc maxLength = svalBuilder.makeIntVal(*maxLengthInt);
700 SVal evalLength = svalBuilder.evalBinOpNN(state, BO_LE, *strLn,
701 maxLength, sizeTy);
702 state = state->assume(evalLength.castAs<DefinedOrUnknownSVal>(), true);
703 }
Jordy Rose634c12d2011-06-15 05:52:56 +0000704 state = state->set<CStringLength>(MR, strLength);
Jordan Rose60619a62013-08-19 16:27:34 +0000705 }
Jordy Rose634c12d2011-06-15 05:52:56 +0000706
Ted Kremenek90af9092010-12-02 07:49:45 +0000707 return strLength;
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000708}
709
Ted Kremenek49b1e382012-01-26 21:29:00 +0000710SVal CStringChecker::getCStringLength(CheckerContext &C, ProgramStateRef &state,
Jordy Rose634c12d2011-06-15 05:52:56 +0000711 const Expr *Ex, SVal Buf,
712 bool hypothetical) const {
Jordy Roseb052e8f2010-07-27 01:37:31 +0000713 const MemRegion *MR = Buf.getAsRegion();
714 if (!MR) {
715 // If we can't get a region, see if it's something we /know/ isn't a
716 // C string. In the context of locations, the only time we can issue such
717 // a warning is for labels.
David Blaikie05785d12013-02-20 22:23:23 +0000718 if (Optional<loc::GotoLabel> Label = Buf.getAs<loc::GotoLabel>()) {
Anna Zakse0c7c272012-02-07 00:56:14 +0000719 if (!Filter.CheckCStringNotNullTerm)
720 return UndefinedVal();
721
Devin Coughline39bd402015-09-16 22:03:05 +0000722 if (ExplodedNode *N = C.generateNonFatalErrorNode(state)) {
Jordy Roseb052e8f2010-07-27 01:37:31 +0000723 if (!BT_NotCString)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000724 BT_NotCString.reset(new BuiltinBug(
725 Filter.CheckNameCStringNotNullTerm, categories::UnixAPI,
726 "Argument is not a null-terminated string."));
Jordy Roseb052e8f2010-07-27 01:37:31 +0000727
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000728 SmallString<120> buf;
Jordy Roseb052e8f2010-07-27 01:37:31 +0000729 llvm::raw_svector_ostream os(buf);
Jordy Rosedceb0cf2011-06-20 02:06:40 +0000730 assert(CurrentFunctionDescription);
731 os << "Argument to " << CurrentFunctionDescription
732 << " is the address of the label '" << Label->getLabel()->getName()
Jordy Roseb052e8f2010-07-27 01:37:31 +0000733 << "', which is not a null-terminated string";
734
735 // Generate a report for this bug.
Aaron Ballman8d3a7a52015-06-23 13:15:32 +0000736 auto report = llvm::make_unique<BugReport>(*BT_NotCString, os.str(), N);
Jordy Roseb052e8f2010-07-27 01:37:31 +0000737
738 report->addRange(Ex->getSourceRange());
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000739 C.emitReport(std::move(report));
Jordy Roseb052e8f2010-07-27 01:37:31 +0000740 }
Jordy Roseb052e8f2010-07-27 01:37:31 +0000741 return UndefinedVal();
Anna Zakse0c7c272012-02-07 00:56:14 +0000742
Jordy Roseb052e8f2010-07-27 01:37:31 +0000743 }
744
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000745 // If it's not a region and not a label, give up.
746 return UnknownVal();
Jordy Roseb052e8f2010-07-27 01:37:31 +0000747 }
748
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000749 // If we have a region, strip casts from it and see if we can figure out
750 // its length. For anything we can't figure out, just return UnknownVal.
751 MR = MR->StripCasts();
752
753 switch (MR->getKind()) {
754 case MemRegion::StringRegionKind: {
755 // Modifying the contents of string regions is undefined [C99 6.4.5p6],
756 // so we can assume that the byte length is the correct C string length.
Ted Kremenek90af9092010-12-02 07:49:45 +0000757 SValBuilder &svalBuilder = C.getSValBuilder();
758 QualType sizeTy = svalBuilder.getContext().getSizeType();
759 const StringLiteral *strLit = cast<StringRegion>(MR)->getStringLiteral();
760 return svalBuilder.makeIntVal(strLit->getByteLength(), sizeTy);
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000761 }
762 case MemRegion::SymbolicRegionKind:
763 case MemRegion::AllocaRegionKind:
764 case MemRegion::VarRegionKind:
765 case MemRegion::FieldRegionKind:
766 case MemRegion::ObjCIvarRegionKind:
Jordy Rose634c12d2011-06-15 05:52:56 +0000767 return getCStringLengthForRegion(C, state, Ex, MR, hypothetical);
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000768 case MemRegion::CompoundLiteralRegionKind:
769 // FIXME: Can we track this? Is it necessary?
770 return UnknownVal();
771 case MemRegion::ElementRegionKind:
772 // FIXME: How can we handle this? It's not good enough to subtract the
773 // offset from the base string length; consider "123\x00567" and &a[5].
774 return UnknownVal();
775 default:
776 // Other regions (mostly non-data) can't have a reliable C string length.
777 // In this case, an error is emitted and UndefinedVal is returned.
778 // The caller should always be prepared to handle this case.
Anna Zakse0c7c272012-02-07 00:56:14 +0000779 if (!Filter.CheckCStringNotNullTerm)
780 return UndefinedVal();
781
Devin Coughline39bd402015-09-16 22:03:05 +0000782 if (ExplodedNode *N = C.generateNonFatalErrorNode(state)) {
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000783 if (!BT_NotCString)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000784 BT_NotCString.reset(new BuiltinBug(
785 Filter.CheckNameCStringNotNullTerm, categories::UnixAPI,
786 "Argument is not a null-terminated string."));
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000787
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000788 SmallString<120> buf;
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000789 llvm::raw_svector_ostream os(buf);
790
Jordy Rosedceb0cf2011-06-20 02:06:40 +0000791 assert(CurrentFunctionDescription);
792 os << "Argument to " << CurrentFunctionDescription << " is ";
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000793
794 if (SummarizeRegion(os, C.getASTContext(), MR))
795 os << ", which is not a null-terminated string";
796 else
797 os << "not a null-terminated string";
798
799 // Generate a report for this bug.
Aaron Ballman8d3a7a52015-06-23 13:15:32 +0000800 auto report = llvm::make_unique<BugReport>(*BT_NotCString, os.str(), N);
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000801
802 report->addRange(Ex->getSourceRange());
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000803 C.emitReport(std::move(report));
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000804 }
805
806 return UndefinedVal();
807 }
Jordy Roseb052e8f2010-07-27 01:37:31 +0000808}
809
Lenny Maioranif3539ad2011-04-12 17:08:43 +0000810const StringLiteral *CStringChecker::getCStringLiteral(CheckerContext &C,
Ted Kremenek49b1e382012-01-26 21:29:00 +0000811 ProgramStateRef &state, const Expr *expr, SVal val) const {
Lenny Maioranif3539ad2011-04-12 17:08:43 +0000812
813 // Get the memory region pointed to by the val.
814 const MemRegion *bufRegion = val.getAsRegion();
815 if (!bufRegion)
Craig Topper0dbb7832014-05-27 02:45:47 +0000816 return nullptr;
Lenny Maioranif3539ad2011-04-12 17:08:43 +0000817
818 // Strip casts off the memory region.
819 bufRegion = bufRegion->StripCasts();
820
821 // Cast the memory region to a string region.
822 const StringRegion *strRegion= dyn_cast<StringRegion>(bufRegion);
823 if (!strRegion)
Craig Topper0dbb7832014-05-27 02:45:47 +0000824 return nullptr;
Lenny Maioranif3539ad2011-04-12 17:08:43 +0000825
826 // Return the actual string in the string region.
827 return strRegion->getStringLiteral();
828}
829
Devin Coughlin0da2e932015-09-24 16:52:56 +0000830bool CStringChecker::IsFirstBufInBound(CheckerContext &C,
831 ProgramStateRef state,
832 const Expr *FirstBuf,
833 const Expr *Size) {
834 // If we do not know that the buffer is long enough we return 'true'.
835 // Otherwise the parent region of this field region would also get
836 // invalidated, which would lead to warnings based on an unknown state.
837
838 // Originally copied from CheckBufferAccess and CheckLocation.
839 SValBuilder &svalBuilder = C.getSValBuilder();
840 ASTContext &Ctx = svalBuilder.getContext();
841 const LocationContext *LCtx = C.getLocationContext();
842
843 QualType sizeTy = Size->getType();
844 QualType PtrTy = Ctx.getPointerType(Ctx.CharTy);
845 SVal BufVal = state->getSVal(FirstBuf, LCtx);
846
847 SVal LengthVal = state->getSVal(Size, LCtx);
848 Optional<NonLoc> Length = LengthVal.getAs<NonLoc>();
849 if (!Length)
850 return true; // cf top comment.
851
852 // Compute the offset of the last element to be accessed: size-1.
853 NonLoc One = svalBuilder.makeIntVal(1, sizeTy).castAs<NonLoc>();
854 NonLoc LastOffset =
855 svalBuilder.evalBinOpNN(state, BO_Sub, *Length, One, sizeTy)
856 .castAs<NonLoc>();
857
858 // Check that the first buffer is sufficiently long.
859 SVal BufStart = svalBuilder.evalCast(BufVal, PtrTy, FirstBuf->getType());
860 Optional<Loc> BufLoc = BufStart.getAs<Loc>();
861 if (!BufLoc)
862 return true; // cf top comment.
863
864 SVal BufEnd =
865 svalBuilder.evalBinOpLN(state, BO_Add, *BufLoc, LastOffset, PtrTy);
866
867 // Check for out of bound array element access.
868 const MemRegion *R = BufEnd.getAsRegion();
869 if (!R)
870 return true; // cf top comment.
871
872 const ElementRegion *ER = dyn_cast<ElementRegion>(R);
873 if (!ER)
874 return true; // cf top comment.
875
876 assert(ER->getValueType() == C.getASTContext().CharTy &&
877 "IsFirstBufInBound should only be called with char* ElementRegions");
878
879 // Get the size of the array.
880 const SubRegion *superReg = cast<SubRegion>(ER->getSuperRegion());
881 SVal Extent =
882 svalBuilder.convertToArrayIndex(superReg->getExtent(svalBuilder));
883 DefinedOrUnknownSVal ExtentSize = Extent.castAs<DefinedOrUnknownSVal>();
884
885 // Get the index of the accessed element.
886 DefinedOrUnknownSVal Idx = ER->getIndex().castAs<DefinedOrUnknownSVal>();
887
888 ProgramStateRef StInBound = state->assumeInBound(Idx, ExtentSize, true);
889
890 return static_cast<bool>(StInBound);
891}
892
Ted Kremenek49b1e382012-01-26 21:29:00 +0000893ProgramStateRef CStringChecker::InvalidateBuffer(CheckerContext &C,
Anton Yartsev968c60a2013-11-17 09:18:48 +0000894 ProgramStateRef state,
895 const Expr *E, SVal V,
Devin Coughlin0da2e932015-09-24 16:52:56 +0000896 bool IsSourceBuffer,
897 const Expr *Size) {
David Blaikie05785d12013-02-20 22:23:23 +0000898 Optional<Loc> L = V.getAs<Loc>();
Jordy Rose722f5582010-08-16 07:51:42 +0000899 if (!L)
900 return state;
901
902 // FIXME: This is a simplified version of what's in CFRefCount.cpp -- it makes
903 // some assumptions about the value that CFRefCount can't. Even so, it should
904 // probably be refactored.
David Blaikie05785d12013-02-20 22:23:23 +0000905 if (Optional<loc::MemRegionVal> MR = L->getAs<loc::MemRegionVal>()) {
Jordy Rose722f5582010-08-16 07:51:42 +0000906 const MemRegion *R = MR->getRegion()->StripCasts();
907
908 // Are we dealing with an ElementRegion? If so, we should be invalidating
909 // the super-region.
910 if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
911 R = ER->getSuperRegion();
912 // FIXME: What about layers of ElementRegions?
913 }
914
915 // Invalidate this region.
Ted Kremenekd519cae2012-02-17 23:13:45 +0000916 const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
Anton Yartsev968c60a2013-11-17 09:18:48 +0000917
918 bool CausesPointerEscape = false;
919 RegionAndSymbolInvalidationTraits ITraits;
920 // Invalidate and escape only indirect regions accessible through the source
921 // buffer.
922 if (IsSourceBuffer) {
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000923 ITraits.setTrait(R,
Anton Yartsev968c60a2013-11-17 09:18:48 +0000924 RegionAndSymbolInvalidationTraits::TK_PreserveContents);
925 ITraits.setTrait(R, RegionAndSymbolInvalidationTraits::TK_SuppressEscape);
926 CausesPointerEscape = true;
Devin Coughlin0da2e932015-09-24 16:52:56 +0000927 } else {
928 const MemRegion::Kind& K = R->getKind();
929 if (K == MemRegion::FieldRegionKind)
930 if (Size && IsFirstBufInBound(C, state, E, Size)) {
931 // If destination buffer is a field region and access is in bound,
932 // do not invalidate its super region.
933 ITraits.setTrait(
934 R,
935 RegionAndSymbolInvalidationTraits::TK_DoNotInvalidateSuperRegion);
936 }
Anton Yartsev968c60a2013-11-17 09:18:48 +0000937 }
938
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000939 return state->invalidateRegions(R, E, C.blockCount(), LCtx,
Craig Topper0dbb7832014-05-27 02:45:47 +0000940 CausesPointerEscape, nullptr, nullptr,
941 &ITraits);
Jordy Rose722f5582010-08-16 07:51:42 +0000942 }
943
944 // If we have a non-region value by chance, just remove the binding.
945 // FIXME: is this necessary or correct? This handles the non-Region
946 // cases. Is it ever valid to store to these?
Ted Kremenek62698882012-08-22 06:37:46 +0000947 return state->killBinding(*L);
Jordy Rose722f5582010-08-16 07:51:42 +0000948}
949
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000950bool CStringChecker::SummarizeRegion(raw_ostream &os, ASTContext &Ctx,
Jordy Roseb052e8f2010-07-27 01:37:31 +0000951 const MemRegion *MR) {
Ted Kremenek8df44b262011-08-12 20:02:48 +0000952 const TypedValueRegion *TVR = dyn_cast<TypedValueRegion>(MR);
Jordy Roseb052e8f2010-07-27 01:37:31 +0000953
Jordy Roseadd45b72011-08-12 21:41:07 +0000954 switch (MR->getKind()) {
Artem Dergachev73f018e2016-01-13 13:49:29 +0000955 case MemRegion::FunctionCodeRegionKind: {
956 const NamedDecl *FD = cast<FunctionCodeRegion>(MR)->getDecl();
Jordy Roseb052e8f2010-07-27 01:37:31 +0000957 if (FD)
Benjamin Kramerb89514a2011-10-14 18:45:37 +0000958 os << "the address of the function '" << *FD << '\'';
Jordy Roseb052e8f2010-07-27 01:37:31 +0000959 else
960 os << "the address of a function";
961 return true;
962 }
Artem Dergachev73f018e2016-01-13 13:49:29 +0000963 case MemRegion::BlockCodeRegionKind:
Jordy Roseb052e8f2010-07-27 01:37:31 +0000964 os << "block text";
965 return true;
966 case MemRegion::BlockDataRegionKind:
967 os << "a block";
968 return true;
969 case MemRegion::CXXThisRegionKind:
Zhongxing Xu03207162010-11-26 08:52:48 +0000970 case MemRegion::CXXTempObjectRegionKind:
Ted Kremenek8df44b262011-08-12 20:02:48 +0000971 os << "a C++ temp object of type " << TVR->getValueType().getAsString();
Jordy Roseb052e8f2010-07-27 01:37:31 +0000972 return true;
973 case MemRegion::VarRegionKind:
Ted Kremenek8df44b262011-08-12 20:02:48 +0000974 os << "a variable of type" << TVR->getValueType().getAsString();
Jordy Roseb052e8f2010-07-27 01:37:31 +0000975 return true;
976 case MemRegion::FieldRegionKind:
Ted Kremenek8df44b262011-08-12 20:02:48 +0000977 os << "a field of type " << TVR->getValueType().getAsString();
Jordy Roseb052e8f2010-07-27 01:37:31 +0000978 return true;
979 case MemRegion::ObjCIvarRegionKind:
Ted Kremenek8df44b262011-08-12 20:02:48 +0000980 os << "an instance variable of type " << TVR->getValueType().getAsString();
Jordy Roseb052e8f2010-07-27 01:37:31 +0000981 return true;
982 default:
983 return false;
984 }
985}
986
Jordy Rosed5d2e502010-07-08 23:57:29 +0000987//===----------------------------------------------------------------------===//
Ted Kremenekdc891422010-12-01 21:57:22 +0000988// evaluation of individual function calls.
Jordy Rosed5d2e502010-07-08 23:57:29 +0000989//===----------------------------------------------------------------------===//
990
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000991void CStringChecker::evalCopyCommon(CheckerContext &C,
Lenny Maiorani79d74142011-03-31 21:36:53 +0000992 const CallExpr *CE,
Ted Kremenek49b1e382012-01-26 21:29:00 +0000993 ProgramStateRef state,
Jordy Rosed5d2e502010-07-08 23:57:29 +0000994 const Expr *Size, const Expr *Dest,
Lenny Maiorani79d74142011-03-31 21:36:53 +0000995 const Expr *Source, bool Restricted,
996 bool IsMempcpy) const {
Jordy Rosedceb0cf2011-06-20 02:06:40 +0000997 CurrentFunctionDescription = "memory copy function";
998
Jordy Rosed5d2e502010-07-08 23:57:29 +0000999 // See if the size argument is zero.
Ted Kremenek632e3b72012-01-06 22:09:28 +00001000 const LocationContext *LCtx = C.getLocationContext();
1001 SVal sizeVal = state->getSVal(Size, LCtx);
Ted Kremenek90af9092010-12-02 07:49:45 +00001002 QualType sizeTy = Size->getType();
Jordy Rosed5d2e502010-07-08 23:57:29 +00001003
Ted Kremenek49b1e382012-01-26 21:29:00 +00001004 ProgramStateRef stateZeroSize, stateNonZeroSize;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001005 std::tie(stateZeroSize, stateNonZeroSize) =
Jordy Rose455bd582011-06-16 05:51:02 +00001006 assumeZero(C, state, sizeVal, sizeTy);
Jordy Rosed5d2e502010-07-08 23:57:29 +00001007
Lenny Maiorani79d74142011-03-31 21:36:53 +00001008 // Get the value of the Dest.
Ted Kremenek632e3b72012-01-06 22:09:28 +00001009 SVal destVal = state->getSVal(Dest, LCtx);
Lenny Maiorani79d74142011-03-31 21:36:53 +00001010
1011 // If the size is zero, there won't be any actual memory access, so
1012 // just bind the return value to the destination buffer and return.
Anna Zaksb3b56bb2012-05-03 18:21:28 +00001013 if (stateZeroSize && !stateNonZeroSize) {
Ted Kremenek632e3b72012-01-06 22:09:28 +00001014 stateZeroSize = stateZeroSize->BindExpr(CE, LCtx, destVal);
Anna Zaksda4c8d62011-10-26 21:06:34 +00001015 C.addTransition(stateZeroSize);
Anna Zaksb3b56bb2012-05-03 18:21:28 +00001016 return;
Lenny Maiorani79d74142011-03-31 21:36:53 +00001017 }
Jordy Rosed5d2e502010-07-08 23:57:29 +00001018
1019 // If the size can be nonzero, we have to check the other arguments.
Ted Kremenek90af9092010-12-02 07:49:45 +00001020 if (stateNonZeroSize) {
Jordy Rose63b84be2011-06-04 00:04:22 +00001021 state = stateNonZeroSize;
Lenny Maiorani79d74142011-03-31 21:36:53 +00001022
1023 // Ensure the destination is not null. If it is NULL there will be a
1024 // NULL pointer dereference.
1025 state = checkNonNull(C, state, Dest, destVal);
1026 if (!state)
1027 return;
1028
1029 // Get the value of the Src.
Ted Kremenek632e3b72012-01-06 22:09:28 +00001030 SVal srcVal = state->getSVal(Source, LCtx);
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001031
Lenny Maiorani79d74142011-03-31 21:36:53 +00001032 // Ensure the source is not null. If it is NULL there will be a
1033 // NULL pointer dereference.
1034 state = checkNonNull(C, state, Source, srcVal);
1035 if (!state)
1036 return;
1037
Jordy Rosefb5e8c22011-06-04 01:50:25 +00001038 // Ensure the accesses are valid and that the buffers do not overlap.
Jordy Rosedceb0cf2011-06-20 02:06:40 +00001039 const char * const writeWarning =
1040 "Memory copy function overflows destination buffer";
Jordy Rose722f5582010-08-16 07:51:42 +00001041 state = CheckBufferAccess(C, state, Size, Dest, Source,
Craig Topper0dbb7832014-05-27 02:45:47 +00001042 writeWarning, /* sourceWarning = */ nullptr);
Jordy Rosed5d2e502010-07-08 23:57:29 +00001043 if (Restricted)
1044 state = CheckOverlap(C, state, Size, Dest, Source);
Jordy Rose722f5582010-08-16 07:51:42 +00001045
Jordy Rosefb5e8c22011-06-04 01:50:25 +00001046 if (!state)
1047 return;
Lenny Maiorani79d74142011-03-31 21:36:53 +00001048
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001049 // If this is mempcpy, get the byte after the last byte copied and
Jordy Rosefb5e8c22011-06-04 01:50:25 +00001050 // bind the expr.
1051 if (IsMempcpy) {
David Blaikie2fdacbc2013-02-20 05:52:05 +00001052 loc::MemRegionVal destRegVal = destVal.castAs<loc::MemRegionVal>();
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001053
Jordy Rosefb5e8c22011-06-04 01:50:25 +00001054 // Get the length to copy.
David Blaikie05785d12013-02-20 22:23:23 +00001055 if (Optional<NonLoc> lenValNonLoc = sizeVal.getAs<NonLoc>()) {
Jordy Rosefb5e8c22011-06-04 01:50:25 +00001056 // Get the byte after the last byte copied.
Anna Zaks2d2f1372014-10-03 21:48:54 +00001057 SValBuilder &SvalBuilder = C.getSValBuilder();
1058 ASTContext &Ctx = SvalBuilder.getContext();
1059 QualType CharPtrTy = Ctx.getPointerType(Ctx.CharTy);
1060 loc::MemRegionVal DestRegCharVal = SvalBuilder.evalCast(destRegVal,
1061 CharPtrTy, Dest->getType()).castAs<loc::MemRegionVal>();
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001062 SVal lastElement = C.getSValBuilder().evalBinOpLN(state, BO_Add,
Anna Zaks2d2f1372014-10-03 21:48:54 +00001063 DestRegCharVal,
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001064 *lenValNonLoc,
Jordy Rosefb5e8c22011-06-04 01:50:25 +00001065 Dest->getType());
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001066
Jordy Rosefb5e8c22011-06-04 01:50:25 +00001067 // The byte after the last byte copied is the return value.
Ted Kremenek632e3b72012-01-06 22:09:28 +00001068 state = state->BindExpr(CE, LCtx, lastElement);
Jordy Rose097c5392011-06-04 01:47:27 +00001069 } else {
Jordy Rosefb5e8c22011-06-04 01:50:25 +00001070 // If we don't know how much we copied, we can at least
1071 // conjure a return value for later.
Craig Topper0dbb7832014-05-27 02:45:47 +00001072 SVal result = C.getSValBuilder().conjureSymbolVal(nullptr, CE, LCtx,
Ted Kremenekd94854a2012-08-22 06:26:15 +00001073 C.blockCount());
Ted Kremenek632e3b72012-01-06 22:09:28 +00001074 state = state->BindExpr(CE, LCtx, result);
Lenny Maiorani79d74142011-03-31 21:36:53 +00001075 }
1076
Jordy Rosefb5e8c22011-06-04 01:50:25 +00001077 } else {
1078 // All other copies return the destination buffer.
1079 // (Well, bcopy() has a void return type, but this won't hurt.)
Ted Kremenek632e3b72012-01-06 22:09:28 +00001080 state = state->BindExpr(CE, LCtx, destVal);
Jordy Rose722f5582010-08-16 07:51:42 +00001081 }
Jordy Rosefb5e8c22011-06-04 01:50:25 +00001082
Anton Yartsev968c60a2013-11-17 09:18:48 +00001083 // Invalidate the destination (regular invalidation without pointer-escaping
1084 // the address of the top-level region).
Jordy Rosefb5e8c22011-06-04 01:50:25 +00001085 // FIXME: Even if we can't perfectly model the copy, we should see if we
1086 // can use LazyCompoundVals to copy the source values into the destination.
1087 // This would probably remove any existing bindings past the end of the
1088 // copied region, but that's still an improvement over blank invalidation.
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001089 state = InvalidateBuffer(C, state, Dest, C.getSVal(Dest),
Devin Coughlin0da2e932015-09-24 16:52:56 +00001090 /*IsSourceBuffer*/false, Size);
Anton Yartsev968c60a2013-11-17 09:18:48 +00001091
1092 // Invalidate the source (const-invalidation without const-pointer-escaping
1093 // the address of the top-level region).
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001094 state = InvalidateBuffer(C, state, Source, C.getSVal(Source),
Devin Coughlin0da2e932015-09-24 16:52:56 +00001095 /*IsSourceBuffer*/true, nullptr);
Anton Yartsev968c60a2013-11-17 09:18:48 +00001096
Anna Zaksda4c8d62011-10-26 21:06:34 +00001097 C.addTransition(state);
Jordy Rosed5d2e502010-07-08 23:57:29 +00001098 }
1099}
1100
1101
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00001102void CStringChecker::evalMemcpy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaksb508d292012-04-10 23:41:11 +00001103 if (CE->getNumArgs() < 3)
1104 return;
1105
Jordy Rose134a2362010-07-06 23:11:01 +00001106 // void *memcpy(void *restrict dst, const void *restrict src, size_t n);
Jordy Rose134a2362010-07-06 23:11:01 +00001107 // The return value is the address of the destination buffer.
Jordy Rosed5d2e502010-07-08 23:57:29 +00001108 const Expr *Dest = CE->getArg(0);
Ted Kremenek49b1e382012-01-26 21:29:00 +00001109 ProgramStateRef state = C.getState();
Jordy Rose097c5392011-06-04 01:47:27 +00001110
Lenny Maiorani79d74142011-03-31 21:36:53 +00001111 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1), true);
1112}
1113
1114void CStringChecker::evalMempcpy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaksb508d292012-04-10 23:41:11 +00001115 if (CE->getNumArgs() < 3)
1116 return;
1117
Lenny Maiorani79d74142011-03-31 21:36:53 +00001118 // void *mempcpy(void *restrict dst, const void *restrict src, size_t n);
1119 // The return value is a pointer to the byte following the last written byte.
1120 const Expr *Dest = CE->getArg(0);
Ted Kremenek49b1e382012-01-26 21:29:00 +00001121 ProgramStateRef state = C.getState();
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001122
Lenny Maiorani79d74142011-03-31 21:36:53 +00001123 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1), true, true);
Jordy Rose134a2362010-07-06 23:11:01 +00001124}
1125
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00001126void CStringChecker::evalMemmove(CheckerContext &C, const CallExpr *CE) const {
Anna Zaksb508d292012-04-10 23:41:11 +00001127 if (CE->getNumArgs() < 3)
1128 return;
1129
Jordy Rosed5d2e502010-07-08 23:57:29 +00001130 // void *memmove(void *dst, const void *src, size_t n);
1131 // The return value is the address of the destination buffer.
1132 const Expr *Dest = CE->getArg(0);
Ted Kremenek49b1e382012-01-26 21:29:00 +00001133 ProgramStateRef state = C.getState();
Jordy Rose097c5392011-06-04 01:47:27 +00001134
Lenny Maiorani79d74142011-03-31 21:36:53 +00001135 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1));
Jordy Rosed5d2e502010-07-08 23:57:29 +00001136}
1137
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00001138void CStringChecker::evalBcopy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaksb508d292012-04-10 23:41:11 +00001139 if (CE->getNumArgs() < 3)
1140 return;
1141
Jordy Rosed5d2e502010-07-08 23:57:29 +00001142 // void bcopy(const void *src, void *dst, size_t n);
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001143 evalCopyCommon(C, CE, C.getState(),
Lenny Maiorani79d74142011-03-31 21:36:53 +00001144 CE->getArg(2), CE->getArg(1), CE->getArg(0));
Jordy Rosed5d2e502010-07-08 23:57:29 +00001145}
1146
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00001147void CStringChecker::evalMemcmp(CheckerContext &C, const CallExpr *CE) const {
Anna Zaksb508d292012-04-10 23:41:11 +00001148 if (CE->getNumArgs() < 3)
1149 return;
1150
Jordy Rose65136fb2010-07-07 08:15:01 +00001151 // int memcmp(const void *s1, const void *s2, size_t n);
Jordy Rosedceb0cf2011-06-20 02:06:40 +00001152 CurrentFunctionDescription = "memory comparison function";
1153
Jordy Rose65136fb2010-07-07 08:15:01 +00001154 const Expr *Left = CE->getArg(0);
1155 const Expr *Right = CE->getArg(1);
1156 const Expr *Size = CE->getArg(2);
1157
Ted Kremenek49b1e382012-01-26 21:29:00 +00001158 ProgramStateRef state = C.getState();
Ted Kremenek90af9092010-12-02 07:49:45 +00001159 SValBuilder &svalBuilder = C.getSValBuilder();
Jordy Rose65136fb2010-07-07 08:15:01 +00001160
Jordy Rosed5d2e502010-07-08 23:57:29 +00001161 // See if the size argument is zero.
Ted Kremenek632e3b72012-01-06 22:09:28 +00001162 const LocationContext *LCtx = C.getLocationContext();
1163 SVal sizeVal = state->getSVal(Size, LCtx);
Ted Kremenek90af9092010-12-02 07:49:45 +00001164 QualType sizeTy = Size->getType();
Jordy Rose65136fb2010-07-07 08:15:01 +00001165
Ted Kremenek49b1e382012-01-26 21:29:00 +00001166 ProgramStateRef stateZeroSize, stateNonZeroSize;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001167 std::tie(stateZeroSize, stateNonZeroSize) =
Ted Kremenek90af9092010-12-02 07:49:45 +00001168 assumeZero(C, state, sizeVal, sizeTy);
Jordy Rose65136fb2010-07-07 08:15:01 +00001169
Jordy Rosed5d2e502010-07-08 23:57:29 +00001170 // If the size can be zero, the result will be 0 in that case, and we don't
1171 // have to check either of the buffers.
Ted Kremenek90af9092010-12-02 07:49:45 +00001172 if (stateZeroSize) {
1173 state = stateZeroSize;
Ted Kremenek632e3b72012-01-06 22:09:28 +00001174 state = state->BindExpr(CE, LCtx,
1175 svalBuilder.makeZeroVal(CE->getType()));
Anna Zaksda4c8d62011-10-26 21:06:34 +00001176 C.addTransition(state);
Jordy Rose65136fb2010-07-07 08:15:01 +00001177 }
1178
Jordy Rosed5d2e502010-07-08 23:57:29 +00001179 // If the size can be nonzero, we have to check the other arguments.
Ted Kremenek90af9092010-12-02 07:49:45 +00001180 if (stateNonZeroSize) {
1181 state = stateNonZeroSize;
Jordy Rosed5d2e502010-07-08 23:57:29 +00001182 // If we know the two buffers are the same, we know the result is 0.
1183 // First, get the two buffers' addresses. Another checker will have already
1184 // made sure they're not undefined.
Ted Kremenek632e3b72012-01-06 22:09:28 +00001185 DefinedOrUnknownSVal LV =
David Blaikie2fdacbc2013-02-20 05:52:05 +00001186 state->getSVal(Left, LCtx).castAs<DefinedOrUnknownSVal>();
Ted Kremenek632e3b72012-01-06 22:09:28 +00001187 DefinedOrUnknownSVal RV =
David Blaikie2fdacbc2013-02-20 05:52:05 +00001188 state->getSVal(Right, LCtx).castAs<DefinedOrUnknownSVal>();
Jordy Rose65136fb2010-07-07 08:15:01 +00001189
Jordy Rosed5d2e502010-07-08 23:57:29 +00001190 // See if they are the same.
Ted Kremenek90af9092010-12-02 07:49:45 +00001191 DefinedOrUnknownSVal SameBuf = svalBuilder.evalEQ(state, LV, RV);
Ted Kremenek49b1e382012-01-26 21:29:00 +00001192 ProgramStateRef StSameBuf, StNotSameBuf;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001193 std::tie(StSameBuf, StNotSameBuf) = state->assume(SameBuf);
Jordy Rosed5d2e502010-07-08 23:57:29 +00001194
Jordy Rose455bd582011-06-16 05:51:02 +00001195 // If the two arguments might be the same buffer, we know the result is 0,
Jordy Rosed5d2e502010-07-08 23:57:29 +00001196 // and we only need to check one size.
1197 if (StSameBuf) {
1198 state = StSameBuf;
1199 state = CheckBufferAccess(C, state, Size, Left);
1200 if (state) {
Ted Kremenek632e3b72012-01-06 22:09:28 +00001201 state = StSameBuf->BindExpr(CE, LCtx,
1202 svalBuilder.makeZeroVal(CE->getType()));
Anna Zaksda4c8d62011-10-26 21:06:34 +00001203 C.addTransition(state);
Jordy Rosed5d2e502010-07-08 23:57:29 +00001204 }
1205 }
1206
1207 // If the two arguments might be different buffers, we have to check the
1208 // size of both of them.
1209 if (StNotSameBuf) {
1210 state = StNotSameBuf;
1211 state = CheckBufferAccess(C, state, Size, Left, Right);
1212 if (state) {
1213 // The return value is the comparison result, which we don't know.
Craig Topper0dbb7832014-05-27 02:45:47 +00001214 SVal CmpV = svalBuilder.conjureSymbolVal(nullptr, CE, LCtx,
1215 C.blockCount());
Ted Kremenek632e3b72012-01-06 22:09:28 +00001216 state = state->BindExpr(CE, LCtx, CmpV);
Anna Zaksda4c8d62011-10-26 21:06:34 +00001217 C.addTransition(state);
Jordy Rosed5d2e502010-07-08 23:57:29 +00001218 }
1219 }
1220 }
Jordy Rose65136fb2010-07-07 08:15:01 +00001221}
1222
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00001223void CStringChecker::evalstrLength(CheckerContext &C,
1224 const CallExpr *CE) const {
Anna Zaksb508d292012-04-10 23:41:11 +00001225 if (CE->getNumArgs() < 1)
1226 return;
1227
Jordy Roseb052e8f2010-07-27 01:37:31 +00001228 // size_t strlen(const char *s);
Ted Kremenek280a01f2011-02-22 04:55:05 +00001229 evalstrLengthCommon(C, CE, /* IsStrnlen = */ false);
1230}
1231
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00001232void CStringChecker::evalstrnLength(CheckerContext &C,
1233 const CallExpr *CE) const {
Anna Zaksb508d292012-04-10 23:41:11 +00001234 if (CE->getNumArgs() < 2)
1235 return;
1236
Ted Kremenek280a01f2011-02-22 04:55:05 +00001237 // size_t strnlen(const char *s, size_t maxlen);
1238 evalstrLengthCommon(C, CE, /* IsStrnlen = */ true);
1239}
1240
1241void CStringChecker::evalstrLengthCommon(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00001242 bool IsStrnlen) const {
Jordy Rosedceb0cf2011-06-20 02:06:40 +00001243 CurrentFunctionDescription = "string length function";
Ted Kremenek49b1e382012-01-26 21:29:00 +00001244 ProgramStateRef state = C.getState();
Ted Kremenek632e3b72012-01-06 22:09:28 +00001245 const LocationContext *LCtx = C.getLocationContext();
Jordy Rosed3592892011-06-14 01:15:31 +00001246
1247 if (IsStrnlen) {
1248 const Expr *maxlenExpr = CE->getArg(1);
Ted Kremenek632e3b72012-01-06 22:09:28 +00001249 SVal maxlenVal = state->getSVal(maxlenExpr, LCtx);
Jordy Rosed3592892011-06-14 01:15:31 +00001250
Ted Kremenek49b1e382012-01-26 21:29:00 +00001251 ProgramStateRef stateZeroSize, stateNonZeroSize;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001252 std::tie(stateZeroSize, stateNonZeroSize) =
Jordy Rosed3592892011-06-14 01:15:31 +00001253 assumeZero(C, state, maxlenVal, maxlenExpr->getType());
1254
1255 // If the size can be zero, the result will be 0 in that case, and we don't
1256 // have to check the string itself.
1257 if (stateZeroSize) {
1258 SVal zero = C.getSValBuilder().makeZeroVal(CE->getType());
Ted Kremenek632e3b72012-01-06 22:09:28 +00001259 stateZeroSize = stateZeroSize->BindExpr(CE, LCtx, zero);
Anna Zaksda4c8d62011-10-26 21:06:34 +00001260 C.addTransition(stateZeroSize);
Jordy Rosed3592892011-06-14 01:15:31 +00001261 }
1262
1263 // If the size is GUARANTEED to be zero, we're done!
1264 if (!stateNonZeroSize)
1265 return;
1266
1267 // Otherwise, record the assumption that the size is nonzero.
1268 state = stateNonZeroSize;
1269 }
1270
1271 // Check that the string argument is non-null.
Jordy Roseb052e8f2010-07-27 01:37:31 +00001272 const Expr *Arg = CE->getArg(0);
Ted Kremenek632e3b72012-01-06 22:09:28 +00001273 SVal ArgVal = state->getSVal(Arg, LCtx);
Jordy Roseb052e8f2010-07-27 01:37:31 +00001274
Ted Kremenek90af9092010-12-02 07:49:45 +00001275 state = checkNonNull(C, state, Arg, ArgVal);
Jordy Roseb052e8f2010-07-27 01:37:31 +00001276
Jordy Rose45d8c122011-06-14 01:26:48 +00001277 if (!state)
1278 return;
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001279
Jordy Rose45d8c122011-06-14 01:26:48 +00001280 SVal strLength = getCStringLength(C, state, Arg, ArgVal);
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001281
Jordy Rose45d8c122011-06-14 01:26:48 +00001282 // If the argument isn't a valid C string, there's no valid state to
1283 // transition to.
1284 if (strLength.isUndef())
1285 return;
Jordy Rosed3592892011-06-14 01:15:31 +00001286
Jordy Rose45d8c122011-06-14 01:26:48 +00001287 DefinedOrUnknownSVal result = UnknownVal();
Jordy Rosed3592892011-06-14 01:15:31 +00001288
Jordy Rose45d8c122011-06-14 01:26:48 +00001289 // If the check is for strnlen() then bind the return value to no more than
1290 // the maxlen value.
1291 if (IsStrnlen) {
Jordy Rose0585a612011-06-16 05:56:50 +00001292 QualType cmpTy = C.getSValBuilder().getConditionType();
Jordy Rosed3592892011-06-14 01:15:31 +00001293
Jordy Rose45d8c122011-06-14 01:26:48 +00001294 // It's a little unfortunate to be getting this again,
1295 // but it's not that expensive...
1296 const Expr *maxlenExpr = CE->getArg(1);
Ted Kremenek632e3b72012-01-06 22:09:28 +00001297 SVal maxlenVal = state->getSVal(maxlenExpr, LCtx);
Ted Kremenek280a01f2011-02-22 04:55:05 +00001298
David Blaikie05785d12013-02-20 22:23:23 +00001299 Optional<NonLoc> strLengthNL = strLength.getAs<NonLoc>();
1300 Optional<NonLoc> maxlenValNL = maxlenVal.getAs<NonLoc>();
Ted Kremenek280a01f2011-02-22 04:55:05 +00001301
Jordy Rose45d8c122011-06-14 01:26:48 +00001302 if (strLengthNL && maxlenValNL) {
Ted Kremenek49b1e382012-01-26 21:29:00 +00001303 ProgramStateRef stateStringTooLong, stateStringNotTooLong;
Jordy Rosed3592892011-06-14 01:15:31 +00001304
Jordy Rose45d8c122011-06-14 01:26:48 +00001305 // Check if the strLength is greater than the maxlen.
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001306 std::tie(stateStringTooLong, stateStringNotTooLong) = state->assume(
1307 C.getSValBuilder()
1308 .evalBinOpNN(state, BO_GT, *strLengthNL, *maxlenValNL, cmpTy)
1309 .castAs<DefinedOrUnknownSVal>());
Jordy Rosed3592892011-06-14 01:15:31 +00001310
Jordy Rose45d8c122011-06-14 01:26:48 +00001311 if (stateStringTooLong && !stateStringNotTooLong) {
1312 // If the string is longer than maxlen, return maxlen.
1313 result = *maxlenValNL;
1314 } else if (stateStringNotTooLong && !stateStringTooLong) {
1315 // If the string is shorter than maxlen, return its length.
1316 result = *strLengthNL;
Ted Kremenek280a01f2011-02-22 04:55:05 +00001317 }
1318 }
1319
Jordy Rose45d8c122011-06-14 01:26:48 +00001320 if (result.isUnknown()) {
1321 // If we don't have enough information for a comparison, there's
1322 // no guarantee the full string length will actually be returned.
1323 // All we know is the return value is the min of the string length
1324 // and the limit. This is better than nothing.
Craig Topper0dbb7832014-05-27 02:45:47 +00001325 result = C.getSValBuilder().conjureSymbolVal(nullptr, CE, LCtx,
1326 C.blockCount());
David Blaikie2fdacbc2013-02-20 05:52:05 +00001327 NonLoc resultNL = result.castAs<NonLoc>();
Jordy Rose45d8c122011-06-14 01:26:48 +00001328
1329 if (strLengthNL) {
David Blaikie2fdacbc2013-02-20 05:52:05 +00001330 state = state->assume(C.getSValBuilder().evalBinOpNN(
1331 state, BO_LE, resultNL, *strLengthNL, cmpTy)
1332 .castAs<DefinedOrUnknownSVal>(), true);
Jordy Rose45d8c122011-06-14 01:26:48 +00001333 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001334
Jordy Rose45d8c122011-06-14 01:26:48 +00001335 if (maxlenValNL) {
David Blaikie2fdacbc2013-02-20 05:52:05 +00001336 state = state->assume(C.getSValBuilder().evalBinOpNN(
1337 state, BO_LE, resultNL, *maxlenValNL, cmpTy)
1338 .castAs<DefinedOrUnknownSVal>(), true);
Jordy Rose45d8c122011-06-14 01:26:48 +00001339 }
1340 }
1341
1342 } else {
1343 // This is a plain strlen(), not strnlen().
David Blaikie2fdacbc2013-02-20 05:52:05 +00001344 result = strLength.castAs<DefinedOrUnknownSVal>();
Jordy Rose45d8c122011-06-14 01:26:48 +00001345
1346 // If we don't know the length of the string, conjure a return
1347 // value, so it can be used in constraints, at least.
1348 if (result.isUnknown()) {
Craig Topper0dbb7832014-05-27 02:45:47 +00001349 result = C.getSValBuilder().conjureSymbolVal(nullptr, CE, LCtx,
1350 C.blockCount());
Jordy Rose45d8c122011-06-14 01:26:48 +00001351 }
Jordy Roseb052e8f2010-07-27 01:37:31 +00001352 }
Jordy Rose45d8c122011-06-14 01:26:48 +00001353
1354 // Bind the return value.
1355 assert(!result.isUnknown() && "Should have conjured a value by now");
Ted Kremenek632e3b72012-01-06 22:09:28 +00001356 state = state->BindExpr(CE, LCtx, result);
Anna Zaksda4c8d62011-10-26 21:06:34 +00001357 C.addTransition(state);
Jordy Roseb052e8f2010-07-27 01:37:31 +00001358}
1359
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00001360void CStringChecker::evalStrcpy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaksb508d292012-04-10 23:41:11 +00001361 if (CE->getNumArgs() < 2)
1362 return;
1363
Jordy Rose722f5582010-08-16 07:51:42 +00001364 // char *strcpy(char *restrict dst, const char *restrict src);
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001365 evalStrcpyCommon(C, CE,
1366 /* returnEnd = */ false,
Lenny Maiorani467dbd52011-04-09 15:12:58 +00001367 /* isBounded = */ false,
1368 /* isAppending = */ false);
Ted Kremenekfb1a79a2011-02-22 04:58:34 +00001369}
1370
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00001371void CStringChecker::evalStrncpy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaksb508d292012-04-10 23:41:11 +00001372 if (CE->getNumArgs() < 3)
1373 return;
1374
Jordy Rose4451cd42011-06-04 00:05:23 +00001375 // char *strncpy(char *restrict dst, const char *restrict src, size_t n);
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001376 evalStrcpyCommon(C, CE,
1377 /* returnEnd = */ false,
Lenny Maiorani467dbd52011-04-09 15:12:58 +00001378 /* isBounded = */ true,
1379 /* isAppending = */ false);
Jordy Rose722f5582010-08-16 07:51:42 +00001380}
1381
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00001382void CStringChecker::evalStpcpy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaksb508d292012-04-10 23:41:11 +00001383 if (CE->getNumArgs() < 2)
1384 return;
1385
Jordy Rose722f5582010-08-16 07:51:42 +00001386 // char *stpcpy(char *restrict dst, const char *restrict src);
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001387 evalStrcpyCommon(C, CE,
1388 /* returnEnd = */ true,
Lenny Maiorani467dbd52011-04-09 15:12:58 +00001389 /* isBounded = */ false,
1390 /* isAppending = */ false);
1391}
1392
1393void CStringChecker::evalStrcat(CheckerContext &C, const CallExpr *CE) const {
Anna Zaksb508d292012-04-10 23:41:11 +00001394 if (CE->getNumArgs() < 2)
1395 return;
1396
Lenny Maiorani467dbd52011-04-09 15:12:58 +00001397 //char *strcat(char *restrict s1, const char *restrict s2);
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001398 evalStrcpyCommon(C, CE,
1399 /* returnEnd = */ false,
Lenny Maiorani467dbd52011-04-09 15:12:58 +00001400 /* isBounded = */ false,
1401 /* isAppending = */ true);
1402}
1403
1404void CStringChecker::evalStrncat(CheckerContext &C, const CallExpr *CE) const {
Anna Zaksb508d292012-04-10 23:41:11 +00001405 if (CE->getNumArgs() < 3)
1406 return;
1407
Lenny Maiorani467dbd52011-04-09 15:12:58 +00001408 //char *strncat(char *restrict s1, const char *restrict s2, size_t n);
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001409 evalStrcpyCommon(C, CE,
1410 /* returnEnd = */ false,
Lenny Maiorani467dbd52011-04-09 15:12:58 +00001411 /* isBounded = */ true,
1412 /* isAppending = */ true);
Jordy Rose722f5582010-08-16 07:51:42 +00001413}
1414
Ted Kremenekdc891422010-12-01 21:57:22 +00001415void CStringChecker::evalStrcpyCommon(CheckerContext &C, const CallExpr *CE,
Lenny Maiorani467dbd52011-04-09 15:12:58 +00001416 bool returnEnd, bool isBounded,
1417 bool isAppending) const {
Jordy Rosedceb0cf2011-06-20 02:06:40 +00001418 CurrentFunctionDescription = "string copy function";
Ted Kremenek49b1e382012-01-26 21:29:00 +00001419 ProgramStateRef state = C.getState();
Ted Kremenek632e3b72012-01-06 22:09:28 +00001420 const LocationContext *LCtx = C.getLocationContext();
Jordy Rose722f5582010-08-16 07:51:42 +00001421
Lenny Maiorani467dbd52011-04-09 15:12:58 +00001422 // Check that the destination is non-null.
Jordy Rose722f5582010-08-16 07:51:42 +00001423 const Expr *Dst = CE->getArg(0);
Ted Kremenek632e3b72012-01-06 22:09:28 +00001424 SVal DstVal = state->getSVal(Dst, LCtx);
Jordy Rose722f5582010-08-16 07:51:42 +00001425
Ted Kremenek90af9092010-12-02 07:49:45 +00001426 state = checkNonNull(C, state, Dst, DstVal);
Jordy Rose722f5582010-08-16 07:51:42 +00001427 if (!state)
1428 return;
1429
1430 // Check that the source is non-null.
Ted Kremenek90af9092010-12-02 07:49:45 +00001431 const Expr *srcExpr = CE->getArg(1);
Ted Kremenek632e3b72012-01-06 22:09:28 +00001432 SVal srcVal = state->getSVal(srcExpr, LCtx);
Ted Kremenek90af9092010-12-02 07:49:45 +00001433 state = checkNonNull(C, state, srcExpr, srcVal);
Jordy Rose722f5582010-08-16 07:51:42 +00001434 if (!state)
1435 return;
1436
1437 // Get the string length of the source.
Ted Kremenek90af9092010-12-02 07:49:45 +00001438 SVal strLength = getCStringLength(C, state, srcExpr, srcVal);
Jordy Rose722f5582010-08-16 07:51:42 +00001439
1440 // If the source isn't a valid C string, give up.
Ted Kremenek90af9092010-12-02 07:49:45 +00001441 if (strLength.isUndef())
Jordy Rose722f5582010-08-16 07:51:42 +00001442 return;
1443
Jordy Rose634c12d2011-06-15 05:52:56 +00001444 SValBuilder &svalBuilder = C.getSValBuilder();
1445 QualType cmpTy = svalBuilder.getConditionType();
Jordy Roseb41f7c52011-06-20 21:55:40 +00001446 QualType sizeTy = svalBuilder.getContext().getSizeType();
Jordy Rose634c12d2011-06-15 05:52:56 +00001447
Jordy Roseb41f7c52011-06-20 21:55:40 +00001448 // These two values allow checking two kinds of errors:
1449 // - actual overflows caused by a source that doesn't fit in the destination
1450 // - potential overflows caused by a bound that could exceed the destination
Jordy Rose634c12d2011-06-15 05:52:56 +00001451 SVal amountCopied = UnknownVal();
Jordy Roseb41f7c52011-06-20 21:55:40 +00001452 SVal maxLastElementIndex = UnknownVal();
Craig Topper0dbb7832014-05-27 02:45:47 +00001453 const char *boundWarning = nullptr;
Jordy Rose634c12d2011-06-15 05:52:56 +00001454
Lenny Maiorani467dbd52011-04-09 15:12:58 +00001455 // If the function is strncpy, strncat, etc... it is bounded.
1456 if (isBounded) {
1457 // Get the max number of characters to copy.
Ted Kremenekfb1a79a2011-02-22 04:58:34 +00001458 const Expr *lenExpr = CE->getArg(2);
Ted Kremenek632e3b72012-01-06 22:09:28 +00001459 SVal lenVal = state->getSVal(lenExpr, LCtx);
Ted Kremenekfb1a79a2011-02-22 04:58:34 +00001460
Jordy Rose634c12d2011-06-15 05:52:56 +00001461 // Protect against misdeclared strncpy().
Jordy Roseb41f7c52011-06-20 21:55:40 +00001462 lenVal = svalBuilder.evalCast(lenVal, sizeTy, lenExpr->getType());
Jordy Rose634c12d2011-06-15 05:52:56 +00001463
David Blaikie05785d12013-02-20 22:23:23 +00001464 Optional<NonLoc> strLengthNL = strLength.getAs<NonLoc>();
1465 Optional<NonLoc> lenValNL = lenVal.getAs<NonLoc>();
Ted Kremenekfb1a79a2011-02-22 04:58:34 +00001466
Jordy Rose634c12d2011-06-15 05:52:56 +00001467 // If we know both values, we might be able to figure out how much
1468 // we're copying.
1469 if (strLengthNL && lenValNL) {
Ted Kremenek49b1e382012-01-26 21:29:00 +00001470 ProgramStateRef stateSourceTooLong, stateSourceNotTooLong;
Ted Kremenekfb1a79a2011-02-22 04:58:34 +00001471
Jordy Rose634c12d2011-06-15 05:52:56 +00001472 // Check if the max number to copy is less than the length of the src.
Jordy Roseb41f7c52011-06-20 21:55:40 +00001473 // If the bound is equal to the source length, strncpy won't null-
1474 // terminate the result!
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001475 std::tie(stateSourceTooLong, stateSourceNotTooLong) = state->assume(
David Blaikie2fdacbc2013-02-20 05:52:05 +00001476 svalBuilder.evalBinOpNN(state, BO_GE, *strLengthNL, *lenValNL, cmpTy)
1477 .castAs<DefinedOrUnknownSVal>());
Jordy Rose634c12d2011-06-15 05:52:56 +00001478
1479 if (stateSourceTooLong && !stateSourceNotTooLong) {
1480 // Max number to copy is less than the length of the src, so the actual
1481 // strLength copied is the max number arg.
1482 state = stateSourceTooLong;
1483 amountCopied = lenVal;
1484
1485 } else if (!stateSourceTooLong && stateSourceNotTooLong) {
1486 // The source buffer entirely fits in the bound.
1487 state = stateSourceNotTooLong;
1488 amountCopied = strLength;
1489 }
1490 }
1491
Jordy Rose328deee2011-06-20 03:49:16 +00001492 // We still want to know if the bound is known to be too large.
Jordy Roseb41f7c52011-06-20 21:55:40 +00001493 if (lenValNL) {
1494 if (isAppending) {
1495 // For strncat, the check is strlen(dst) + lenVal < sizeof(dst)
1496
1497 // Get the string length of the destination. If the destination is
1498 // memory that can't have a string length, we shouldn't be copying
1499 // into it anyway.
1500 SVal dstStrLength = getCStringLength(C, state, Dst, DstVal);
1501 if (dstStrLength.isUndef())
1502 return;
1503
David Blaikie05785d12013-02-20 22:23:23 +00001504 if (Optional<NonLoc> dstStrLengthNL = dstStrLength.getAs<NonLoc>()) {
Jordy Roseb41f7c52011-06-20 21:55:40 +00001505 maxLastElementIndex = svalBuilder.evalBinOpNN(state, BO_Add,
1506 *lenValNL,
1507 *dstStrLengthNL,
1508 sizeTy);
1509 boundWarning = "Size argument is greater than the free space in the "
1510 "destination buffer";
1511 }
1512
1513 } else {
1514 // For strncpy, this is just checking that lenVal <= sizeof(dst)
1515 // (Yes, strncpy and strncat differ in how they treat termination.
1516 // strncat ALWAYS terminates, but strncpy doesn't.)
Jordy Rose459d5f62012-05-14 17:58:35 +00001517
1518 // We need a special case for when the copy size is zero, in which
1519 // case strncpy will do no work at all. Our bounds check uses n-1
1520 // as the last element accessed, so n == 0 is problematic.
1521 ProgramStateRef StateZeroSize, StateNonZeroSize;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001522 std::tie(StateZeroSize, StateNonZeroSize) =
Jordy Rose459d5f62012-05-14 17:58:35 +00001523 assumeZero(C, state, *lenValNL, sizeTy);
1524
1525 // If the size is known to be zero, we're done.
1526 if (StateZeroSize && !StateNonZeroSize) {
1527 StateZeroSize = StateZeroSize->BindExpr(CE, LCtx, DstVal);
1528 C.addTransition(StateZeroSize);
1529 return;
1530 }
1531
1532 // Otherwise, go ahead and figure out the last element we'll touch.
1533 // We don't record the non-zero assumption here because we can't
1534 // be sure. We won't warn on a possible zero.
David Blaikie2fdacbc2013-02-20 05:52:05 +00001535 NonLoc one = svalBuilder.makeIntVal(1, sizeTy).castAs<NonLoc>();
Jordy Roseb41f7c52011-06-20 21:55:40 +00001536 maxLastElementIndex = svalBuilder.evalBinOpNN(state, BO_Sub, *lenValNL,
1537 one, sizeTy);
1538 boundWarning = "Size argument is greater than the length of the "
1539 "destination buffer";
1540 }
1541 }
Jordy Rose328deee2011-06-20 03:49:16 +00001542
Jordy Rose634c12d2011-06-15 05:52:56 +00001543 // If we couldn't pin down the copy length, at least bound it.
Jordy Roseb41f7c52011-06-20 21:55:40 +00001544 // FIXME: We should actually run this code path for append as well, but
1545 // right now it creates problems with constraints (since we can end up
1546 // trying to pass constraints from symbol to symbol).
1547 if (amountCopied.isUnknown() && !isAppending) {
Jordy Rose634c12d2011-06-15 05:52:56 +00001548 // Try to get a "hypothetical" string length symbol, which we can later
1549 // set as a real value if that turns out to be the case.
1550 amountCopied = getCStringLength(C, state, lenExpr, srcVal, true);
1551 assert(!amountCopied.isUndef());
1552
David Blaikie05785d12013-02-20 22:23:23 +00001553 if (Optional<NonLoc> amountCopiedNL = amountCopied.getAs<NonLoc>()) {
Jordy Rose634c12d2011-06-15 05:52:56 +00001554 if (lenValNL) {
1555 // amountCopied <= lenVal
1556 SVal copiedLessThanBound = svalBuilder.evalBinOpNN(state, BO_LE,
1557 *amountCopiedNL,
1558 *lenValNL,
1559 cmpTy);
David Blaikie2fdacbc2013-02-20 05:52:05 +00001560 state = state->assume(
1561 copiedLessThanBound.castAs<DefinedOrUnknownSVal>(), true);
Jordy Rose634c12d2011-06-15 05:52:56 +00001562 if (!state)
1563 return;
1564 }
1565
1566 if (strLengthNL) {
1567 // amountCopied <= strlen(source)
1568 SVal copiedLessThanSrc = svalBuilder.evalBinOpNN(state, BO_LE,
1569 *amountCopiedNL,
1570 *strLengthNL,
1571 cmpTy);
David Blaikie2fdacbc2013-02-20 05:52:05 +00001572 state = state->assume(
1573 copiedLessThanSrc.castAs<DefinedOrUnknownSVal>(), true);
Jordy Rose634c12d2011-06-15 05:52:56 +00001574 if (!state)
1575 return;
1576 }
1577 }
1578 }
1579
1580 } else {
1581 // The function isn't bounded. The amount copied should match the length
1582 // of the source buffer.
1583 amountCopied = strLength;
Ted Kremenekfb1a79a2011-02-22 04:58:34 +00001584 }
1585
Jordy Rose634c12d2011-06-15 05:52:56 +00001586 assert(state);
1587
1588 // This represents the number of characters copied into the destination
1589 // buffer. (It may not actually be the strlen if the destination buffer
1590 // is not terminated.)
1591 SVal finalStrLength = UnknownVal();
1592
Lenny Maiorani467dbd52011-04-09 15:12:58 +00001593 // If this is an appending function (strcat, strncat...) then set the
1594 // string length to strlen(src) + strlen(dst) since the buffer will
1595 // ultimately contain both.
1596 if (isAppending) {
Jordy Rose455bd582011-06-16 05:51:02 +00001597 // Get the string length of the destination. If the destination is memory
1598 // that can't have a string length, we shouldn't be copying into it anyway.
Lenny Maiorani467dbd52011-04-09 15:12:58 +00001599 SVal dstStrLength = getCStringLength(C, state, Dst, DstVal);
1600 if (dstStrLength.isUndef())
1601 return;
1602
David Blaikie05785d12013-02-20 22:23:23 +00001603 Optional<NonLoc> srcStrLengthNL = amountCopied.getAs<NonLoc>();
1604 Optional<NonLoc> dstStrLengthNL = dstStrLength.getAs<NonLoc>();
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001605
Jordy Rose634c12d2011-06-15 05:52:56 +00001606 // If we know both string lengths, we might know the final string length.
1607 if (srcStrLengthNL && dstStrLengthNL) {
1608 // Make sure the two lengths together don't overflow a size_t.
1609 state = checkAdditionOverflow(C, state, *srcStrLengthNL, *dstStrLengthNL);
1610 if (!state)
1611 return;
Lenny Maiorani467dbd52011-04-09 15:12:58 +00001612
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001613 finalStrLength = svalBuilder.evalBinOpNN(state, BO_Add, *srcStrLengthNL,
Jordy Rose634c12d2011-06-15 05:52:56 +00001614 *dstStrLengthNL, sizeTy);
1615 }
Lenny Maiorani467dbd52011-04-09 15:12:58 +00001616
Jordy Rose634c12d2011-06-15 05:52:56 +00001617 // If we couldn't get a single value for the final string length,
1618 // we can at least bound it by the individual lengths.
1619 if (finalStrLength.isUnknown()) {
1620 // Try to get a "hypothetical" string length symbol, which we can later
1621 // set as a real value if that turns out to be the case.
1622 finalStrLength = getCStringLength(C, state, CE, DstVal, true);
1623 assert(!finalStrLength.isUndef());
1624
David Blaikie05785d12013-02-20 22:23:23 +00001625 if (Optional<NonLoc> finalStrLengthNL = finalStrLength.getAs<NonLoc>()) {
Jordy Rose634c12d2011-06-15 05:52:56 +00001626 if (srcStrLengthNL) {
1627 // finalStrLength >= srcStrLength
1628 SVal sourceInResult = svalBuilder.evalBinOpNN(state, BO_GE,
1629 *finalStrLengthNL,
1630 *srcStrLengthNL,
1631 cmpTy);
David Blaikie2fdacbc2013-02-20 05:52:05 +00001632 state = state->assume(sourceInResult.castAs<DefinedOrUnknownSVal>(),
Jordy Rose634c12d2011-06-15 05:52:56 +00001633 true);
1634 if (!state)
1635 return;
1636 }
1637
1638 if (dstStrLengthNL) {
1639 // finalStrLength >= dstStrLength
1640 SVal destInResult = svalBuilder.evalBinOpNN(state, BO_GE,
1641 *finalStrLengthNL,
1642 *dstStrLengthNL,
1643 cmpTy);
David Blaikie2fdacbc2013-02-20 05:52:05 +00001644 state =
1645 state->assume(destInResult.castAs<DefinedOrUnknownSVal>(), true);
Jordy Rose634c12d2011-06-15 05:52:56 +00001646 if (!state)
1647 return;
1648 }
1649 }
1650 }
1651
1652 } else {
1653 // Otherwise, this is a copy-over function (strcpy, strncpy, ...), and
1654 // the final string length will match the input string length.
1655 finalStrLength = amountCopied;
Lenny Maiorani467dbd52011-04-09 15:12:58 +00001656 }
1657
Jordy Rose634c12d2011-06-15 05:52:56 +00001658 // The final result of the function will either be a pointer past the last
1659 // copied element, or a pointer to the start of the destination buffer.
Ted Kremenek90af9092010-12-02 07:49:45 +00001660 SVal Result = (returnEnd ? UnknownVal() : DstVal);
Jordy Rose722f5582010-08-16 07:51:42 +00001661
Jordy Rose634c12d2011-06-15 05:52:56 +00001662 assert(state);
1663
Jordy Rose722f5582010-08-16 07:51:42 +00001664 // If the destination is a MemRegion, try to check for a buffer overflow and
1665 // record the new string length.
David Blaikie05785d12013-02-20 22:23:23 +00001666 if (Optional<loc::MemRegionVal> dstRegVal =
David Blaikie2fdacbc2013-02-20 05:52:05 +00001667 DstVal.getAs<loc::MemRegionVal>()) {
Jordy Roseb41f7c52011-06-20 21:55:40 +00001668 QualType ptrTy = Dst->getType();
1669
1670 // If we have an exact value on a bounded copy, use that to check for
1671 // overflows, rather than our estimate about how much is actually copied.
1672 if (boundWarning) {
David Blaikie05785d12013-02-20 22:23:23 +00001673 if (Optional<NonLoc> maxLastNL = maxLastElementIndex.getAs<NonLoc>()) {
Jordy Roseb41f7c52011-06-20 21:55:40 +00001674 SVal maxLastElement = svalBuilder.evalBinOpLN(state, BO_Add, *dstRegVal,
1675 *maxLastNL, ptrTy);
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001676 state = CheckLocation(C, state, CE->getArg(2), maxLastElement,
Jordy Roseb41f7c52011-06-20 21:55:40 +00001677 boundWarning);
1678 if (!state)
1679 return;
1680 }
1681 }
1682
1683 // Then, if the final length is known...
David Blaikie05785d12013-02-20 22:23:23 +00001684 if (Optional<NonLoc> knownStrLength = finalStrLength.getAs<NonLoc>()) {
Jordy Rose634c12d2011-06-15 05:52:56 +00001685 SVal lastElement = svalBuilder.evalBinOpLN(state, BO_Add, *dstRegVal,
Jordy Roseb41f7c52011-06-20 21:55:40 +00001686 *knownStrLength, ptrTy);
Jordy Rose722f5582010-08-16 07:51:42 +00001687
Jordy Roseb41f7c52011-06-20 21:55:40 +00001688 // ...and we haven't checked the bound, we'll check the actual copy.
1689 if (!boundWarning) {
1690 const char * const warningMsg =
1691 "String copy function overflows destination buffer";
1692 state = CheckLocation(C, state, Dst, lastElement, warningMsg);
1693 if (!state)
1694 return;
1695 }
Jordy Rose722f5582010-08-16 07:51:42 +00001696
1697 // If this is a stpcpy-style copy, the last element is the return value.
Ted Kremenek90af9092010-12-02 07:49:45 +00001698 if (returnEnd)
1699 Result = lastElement;
Jordy Rose722f5582010-08-16 07:51:42 +00001700 }
1701
Anton Yartsev968c60a2013-11-17 09:18:48 +00001702 // Invalidate the destination (regular invalidation without pointer-escaping
1703 // the address of the top-level region). This must happen before we set the
1704 // C string length because invalidation will clear the length.
Jordy Rose722f5582010-08-16 07:51:42 +00001705 // FIXME: Even if we can't perfectly model the copy, we should see if we
1706 // can use LazyCompoundVals to copy the source values into the destination.
1707 // This would probably remove any existing bindings past the end of the
1708 // string, but that's still an improvement over blank invalidation.
Anton Yartsev968c60a2013-11-17 09:18:48 +00001709 state = InvalidateBuffer(C, state, Dst, *dstRegVal,
Devin Coughlin0da2e932015-09-24 16:52:56 +00001710 /*IsSourceBuffer*/false, nullptr);
Anton Yartsev968c60a2013-11-17 09:18:48 +00001711
1712 // Invalidate the source (const-invalidation without const-pointer-escaping
1713 // the address of the top-level region).
Devin Coughlin0da2e932015-09-24 16:52:56 +00001714 state = InvalidateBuffer(C, state, srcExpr, srcVal, /*IsSourceBuffer*/true,
1715 nullptr);
Jordy Rose722f5582010-08-16 07:51:42 +00001716
Jordy Rose328deee2011-06-20 03:49:16 +00001717 // Set the C string length of the destination, if we know it.
Jordy Roseb41f7c52011-06-20 21:55:40 +00001718 if (isBounded && !isAppending) {
1719 // strncpy is annoying in that it doesn't guarantee to null-terminate
1720 // the result string. If the original string didn't fit entirely inside
1721 // the bound (including the null-terminator), we don't know how long the
1722 // result is.
1723 if (amountCopied != strLength)
1724 finalStrLength = UnknownVal();
1725 }
1726 state = setCStringLength(state, dstRegVal->getRegion(), finalStrLength);
Jordy Rose722f5582010-08-16 07:51:42 +00001727 }
1728
Jordy Rose634c12d2011-06-15 05:52:56 +00001729 assert(state);
1730
Jordy Rose722f5582010-08-16 07:51:42 +00001731 // If this is a stpcpy-style copy, but we were unable to check for a buffer
1732 // overflow, we still need a result. Conjure a return value.
Ted Kremenek90af9092010-12-02 07:49:45 +00001733 if (returnEnd && Result.isUnknown()) {
Craig Topper0dbb7832014-05-27 02:45:47 +00001734 Result = svalBuilder.conjureSymbolVal(nullptr, CE, LCtx, C.blockCount());
Jordy Rose722f5582010-08-16 07:51:42 +00001735 }
1736
1737 // Set the return value.
Ted Kremenek632e3b72012-01-06 22:09:28 +00001738 state = state->BindExpr(CE, LCtx, Result);
Anna Zaksda4c8d62011-10-26 21:06:34 +00001739 C.addTransition(state);
Jordy Rose722f5582010-08-16 07:51:42 +00001740}
1741
Lenny Maioranif3539ad2011-04-12 17:08:43 +00001742void CStringChecker::evalStrcmp(CheckerContext &C, const CallExpr *CE) const {
Anna Zaksb508d292012-04-10 23:41:11 +00001743 if (CE->getNumArgs() < 2)
1744 return;
1745
Jordy Rosec0263702011-06-16 07:13:34 +00001746 //int strcmp(const char *s1, const char *s2);
Lenny Maiorani4af23c82011-04-28 15:09:11 +00001747 evalStrcmpCommon(C, CE, /* isBounded = */ false, /* ignoreCase = */ false);
Lenny Maioranie553e402011-04-25 22:21:00 +00001748}
Lenny Maioranif3539ad2011-04-12 17:08:43 +00001749
Lenny Maioranie553e402011-04-25 22:21:00 +00001750void CStringChecker::evalStrncmp(CheckerContext &C, const CallExpr *CE) const {
Anna Zaksb508d292012-04-10 23:41:11 +00001751 if (CE->getNumArgs() < 3)
1752 return;
1753
Jordy Rosec0263702011-06-16 07:13:34 +00001754 //int strncmp(const char *s1, const char *s2, size_t n);
Lenny Maiorani4af23c82011-04-28 15:09:11 +00001755 evalStrcmpCommon(C, CE, /* isBounded = */ true, /* ignoreCase = */ false);
1756}
1757
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001758void CStringChecker::evalStrcasecmp(CheckerContext &C,
Lenny Maiorani4af23c82011-04-28 15:09:11 +00001759 const CallExpr *CE) const {
Anna Zaksb508d292012-04-10 23:41:11 +00001760 if (CE->getNumArgs() < 2)
1761 return;
1762
Jordy Rosec0263702011-06-16 07:13:34 +00001763 //int strcasecmp(const char *s1, const char *s2);
Lenny Maiorani4af23c82011-04-28 15:09:11 +00001764 evalStrcmpCommon(C, CE, /* isBounded = */ false, /* ignoreCase = */ true);
Lenny Maioranie553e402011-04-25 22:21:00 +00001765}
1766
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001767void CStringChecker::evalStrncasecmp(CheckerContext &C,
Lenny Maiorani0b510272011-05-02 19:05:49 +00001768 const CallExpr *CE) const {
Anna Zaksb508d292012-04-10 23:41:11 +00001769 if (CE->getNumArgs() < 3)
1770 return;
1771
Jordy Rosec0263702011-06-16 07:13:34 +00001772 //int strncasecmp(const char *s1, const char *s2, size_t n);
Lenny Maiorani0b510272011-05-02 19:05:49 +00001773 evalStrcmpCommon(C, CE, /* isBounded = */ true, /* ignoreCase = */ true);
1774}
1775
Lenny Maioranie553e402011-04-25 22:21:00 +00001776void CStringChecker::evalStrcmpCommon(CheckerContext &C, const CallExpr *CE,
Lenny Maiorani4af23c82011-04-28 15:09:11 +00001777 bool isBounded, bool ignoreCase) const {
Jordy Rosedceb0cf2011-06-20 02:06:40 +00001778 CurrentFunctionDescription = "string comparison function";
Ted Kremenek49b1e382012-01-26 21:29:00 +00001779 ProgramStateRef state = C.getState();
Ted Kremenek632e3b72012-01-06 22:09:28 +00001780 const LocationContext *LCtx = C.getLocationContext();
Lenny Maioranif3539ad2011-04-12 17:08:43 +00001781
1782 // Check that the first string is non-null
1783 const Expr *s1 = CE->getArg(0);
Ted Kremenek632e3b72012-01-06 22:09:28 +00001784 SVal s1Val = state->getSVal(s1, LCtx);
Lenny Maioranif3539ad2011-04-12 17:08:43 +00001785 state = checkNonNull(C, state, s1, s1Val);
1786 if (!state)
1787 return;
1788
1789 // Check that the second string is non-null.
1790 const Expr *s2 = CE->getArg(1);
Ted Kremenek632e3b72012-01-06 22:09:28 +00001791 SVal s2Val = state->getSVal(s2, LCtx);
Lenny Maioranif3539ad2011-04-12 17:08:43 +00001792 state = checkNonNull(C, state, s2, s2Val);
1793 if (!state)
1794 return;
1795
1796 // Get the string length of the first string or give up.
1797 SVal s1Length = getCStringLength(C, state, s1, s1Val);
1798 if (s1Length.isUndef())
1799 return;
1800
1801 // Get the string length of the second string or give up.
1802 SVal s2Length = getCStringLength(C, state, s2, s2Val);
1803 if (s2Length.isUndef())
1804 return;
1805
Jordy Rosec0263702011-06-16 07:13:34 +00001806 // If we know the two buffers are the same, we know the result is 0.
1807 // First, get the two buffers' addresses. Another checker will have already
1808 // made sure they're not undefined.
David Blaikie2fdacbc2013-02-20 05:52:05 +00001809 DefinedOrUnknownSVal LV = s1Val.castAs<DefinedOrUnknownSVal>();
1810 DefinedOrUnknownSVal RV = s2Val.castAs<DefinedOrUnknownSVal>();
Lenny Maioranif3539ad2011-04-12 17:08:43 +00001811
Jordy Rosec0263702011-06-16 07:13:34 +00001812 // See if they are the same.
Lenny Maioranif3539ad2011-04-12 17:08:43 +00001813 SValBuilder &svalBuilder = C.getSValBuilder();
Jordy Rosec0263702011-06-16 07:13:34 +00001814 DefinedOrUnknownSVal SameBuf = svalBuilder.evalEQ(state, LV, RV);
Ted Kremenek49b1e382012-01-26 21:29:00 +00001815 ProgramStateRef StSameBuf, StNotSameBuf;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001816 std::tie(StSameBuf, StNotSameBuf) = state->assume(SameBuf);
Lenny Maioranif3539ad2011-04-12 17:08:43 +00001817
Jordy Rosec0263702011-06-16 07:13:34 +00001818 // If the two arguments might be the same buffer, we know the result is 0,
1819 // and we only need to check one size.
1820 if (StSameBuf) {
Ted Kremenek632e3b72012-01-06 22:09:28 +00001821 StSameBuf = StSameBuf->BindExpr(CE, LCtx,
1822 svalBuilder.makeZeroVal(CE->getType()));
Anna Zaksda4c8d62011-10-26 21:06:34 +00001823 C.addTransition(StSameBuf);
Jordy Rosec0263702011-06-16 07:13:34 +00001824
1825 // If the two arguments are GUARANTEED to be the same, we're done!
1826 if (!StNotSameBuf)
1827 return;
1828 }
1829
1830 assert(StNotSameBuf);
1831 state = StNotSameBuf;
1832
1833 // At this point we can go about comparing the two buffers.
1834 // For now, we only do this if they're both known string literals.
1835
1836 // Attempt to extract string literals from both expressions.
1837 const StringLiteral *s1StrLiteral = getCStringLiteral(C, state, s1, s1Val);
1838 const StringLiteral *s2StrLiteral = getCStringLiteral(C, state, s2, s2Val);
1839 bool canComputeResult = false;
1840
1841 if (s1StrLiteral && s2StrLiteral) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001842 StringRef s1StrRef = s1StrLiteral->getString();
1843 StringRef s2StrRef = s2StrLiteral->getString();
Jordy Rosec0263702011-06-16 07:13:34 +00001844
1845 if (isBounded) {
1846 // Get the max number of characters to compare.
1847 const Expr *lenExpr = CE->getArg(2);
Ted Kremenek632e3b72012-01-06 22:09:28 +00001848 SVal lenVal = state->getSVal(lenExpr, LCtx);
Jordy Rosec0263702011-06-16 07:13:34 +00001849
1850 // If the length is known, we can get the right substrings.
1851 if (const llvm::APSInt *len = svalBuilder.getKnownValue(state, lenVal)) {
1852 // Create substrings of each to compare the prefix.
1853 s1StrRef = s1StrRef.substr(0, (size_t)len->getZExtValue());
1854 s2StrRef = s2StrRef.substr(0, (size_t)len->getZExtValue());
1855 canComputeResult = true;
1856 }
1857 } else {
1858 // This is a normal, unbounded strcmp.
1859 canComputeResult = true;
1860 }
1861
1862 if (canComputeResult) {
1863 // Real strcmp stops at null characters.
1864 size_t s1Term = s1StrRef.find('\0');
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001865 if (s1Term != StringRef::npos)
Jordy Rosec0263702011-06-16 07:13:34 +00001866 s1StrRef = s1StrRef.substr(0, s1Term);
1867
1868 size_t s2Term = s2StrRef.find('\0');
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001869 if (s2Term != StringRef::npos)
Jordy Rosec0263702011-06-16 07:13:34 +00001870 s2StrRef = s2StrRef.substr(0, s2Term);
1871
1872 // Use StringRef's comparison methods to compute the actual result.
1873 int result;
1874
1875 if (ignoreCase) {
1876 // Compare string 1 to string 2 the same way strcasecmp() does.
1877 result = s1StrRef.compare_lower(s2StrRef);
1878 } else {
1879 // Compare string 1 to string 2 the same way strcmp() does.
1880 result = s1StrRef.compare(s2StrRef);
1881 }
1882
1883 // Build the SVal of the comparison and bind the return value.
1884 SVal resultVal = svalBuilder.makeIntVal(result, CE->getType());
Ted Kremenek632e3b72012-01-06 22:09:28 +00001885 state = state->BindExpr(CE, LCtx, resultVal);
Jordy Rosec0263702011-06-16 07:13:34 +00001886 }
1887 }
1888
1889 if (!canComputeResult) {
1890 // Conjure a symbolic value. It's the best we can do.
Craig Topper0dbb7832014-05-27 02:45:47 +00001891 SVal resultVal = svalBuilder.conjureSymbolVal(nullptr, CE, LCtx,
1892 C.blockCount());
Ted Kremenek632e3b72012-01-06 22:09:28 +00001893 state = state->BindExpr(CE, LCtx, resultVal);
Jordy Rosec0263702011-06-16 07:13:34 +00001894 }
1895
1896 // Record this as a possible path.
Anna Zaksda4c8d62011-10-26 21:06:34 +00001897 C.addTransition(state);
Lenny Maioranif3539ad2011-04-12 17:08:43 +00001898}
1899
Jordan Rose6e3cf2b2013-04-22 23:18:42 +00001900void CStringChecker::evalStrsep(CheckerContext &C, const CallExpr *CE) const {
1901 //char *strsep(char **stringp, const char *delim);
1902 if (CE->getNumArgs() < 2)
1903 return;
1904
1905 // Sanity: does the search string parameter match the return type?
1906 const Expr *SearchStrPtr = CE->getArg(0);
1907 QualType CharPtrTy = SearchStrPtr->getType()->getPointeeType();
1908 if (CharPtrTy.isNull() ||
1909 CE->getType().getUnqualifiedType() != CharPtrTy.getUnqualifiedType())
1910 return;
1911
1912 CurrentFunctionDescription = "strsep()";
1913 ProgramStateRef State = C.getState();
1914 const LocationContext *LCtx = C.getLocationContext();
1915
1916 // Check that the search string pointer is non-null (though it may point to
1917 // a null string).
1918 SVal SearchStrVal = State->getSVal(SearchStrPtr, LCtx);
1919 State = checkNonNull(C, State, SearchStrPtr, SearchStrVal);
1920 if (!State)
1921 return;
1922
1923 // Check that the delimiter string is non-null.
1924 const Expr *DelimStr = CE->getArg(1);
1925 SVal DelimStrVal = State->getSVal(DelimStr, LCtx);
1926 State = checkNonNull(C, State, DelimStr, DelimStrVal);
1927 if (!State)
1928 return;
1929
1930 SValBuilder &SVB = C.getSValBuilder();
1931 SVal Result;
1932 if (Optional<Loc> SearchStrLoc = SearchStrVal.getAs<Loc>()) {
1933 // Get the current value of the search string pointer, as a char*.
1934 Result = State->getSVal(*SearchStrLoc, CharPtrTy);
1935
1936 // Invalidate the search string, representing the change of one delimiter
1937 // character to NUL.
Anton Yartsev968c60a2013-11-17 09:18:48 +00001938 State = InvalidateBuffer(C, State, SearchStrPtr, Result,
Devin Coughlin0da2e932015-09-24 16:52:56 +00001939 /*IsSourceBuffer*/false, nullptr);
Jordan Rose6e3cf2b2013-04-22 23:18:42 +00001940
1941 // Overwrite the search string pointer. The new value is either an address
1942 // further along in the same string, or NULL if there are no more tokens.
1943 State = State->bindLoc(*SearchStrLoc,
1944 SVB.conjureSymbolVal(getTag(), CE, LCtx, CharPtrTy,
1945 C.blockCount()));
1946 } else {
1947 assert(SearchStrVal.isUnknown());
1948 // Conjure a symbolic value. It's the best we can do.
Craig Topper0dbb7832014-05-27 02:45:47 +00001949 Result = SVB.conjureSymbolVal(nullptr, CE, LCtx, C.blockCount());
Jordan Rose6e3cf2b2013-04-22 23:18:42 +00001950 }
1951
1952 // Set the return value, and finish.
1953 State = State->BindExpr(CE, LCtx, Result);
1954 C.addTransition(State);
1955}
1956
Devin Coughlin9165df12016-02-07 16:55:44 +00001957// These should probably be moved into a C++ standard library checker.
1958void CStringChecker::evalStdCopy(CheckerContext &C, const CallExpr *CE) const {
1959 evalStdCopyCommon(C, CE);
1960}
Jordan Rose6e3cf2b2013-04-22 23:18:42 +00001961
Devin Coughlin9165df12016-02-07 16:55:44 +00001962void CStringChecker::evalStdCopyBackward(CheckerContext &C,
1963 const CallExpr *CE) const {
1964 evalStdCopyCommon(C, CE);
1965}
1966
1967void CStringChecker::evalStdCopyCommon(CheckerContext &C,
1968 const CallExpr *CE) const {
1969 if (CE->getNumArgs() < 3)
1970 return;
1971
1972 ProgramStateRef State = C.getState();
1973
1974 const LocationContext *LCtx = C.getLocationContext();
1975
1976 // template <class _InputIterator, class _OutputIterator>
1977 // _OutputIterator
1978 // copy(_InputIterator __first, _InputIterator __last,
1979 // _OutputIterator __result)
1980
1981 // Invalidate the destination buffer
1982 const Expr *Dst = CE->getArg(2);
1983 SVal DstVal = State->getSVal(Dst, LCtx);
1984 State = InvalidateBuffer(C, State, Dst, DstVal, /*IsSource=*/false,
1985 /*Size=*/nullptr);
1986
1987 SValBuilder &SVB = C.getSValBuilder();
1988
1989 SVal ResultVal = SVB.conjureSymbolVal(nullptr, CE, LCtx, C.blockCount());
1990 State = State->BindExpr(CE, LCtx, ResultVal);
1991
1992 C.addTransition(State);
1993}
1994
1995static bool isCPPStdLibraryFunction(const FunctionDecl *FD, StringRef Name) {
1996 IdentifierInfo *II = FD->getIdentifier();
1997 if (!II)
1998 return false;
1999
2000 if (!AnalysisDeclContext::isInStdNamespace(FD))
2001 return false;
2002
2003 if (II->getName().equals(Name))
2004 return true;
2005
2006 return false;
2007}
Jordy Rosed5d2e502010-07-08 23:57:29 +00002008//===----------------------------------------------------------------------===//
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002009// The driver method, and other Checker callbacks.
Jordy Rosed5d2e502010-07-08 23:57:29 +00002010//===----------------------------------------------------------------------===//
Jordy Rose134a2362010-07-06 23:11:01 +00002011
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00002012bool CStringChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
Anna Zaks6348a812012-02-17 22:35:26 +00002013 const FunctionDecl *FDecl = C.getCalleeDecl(CE);
2014
2015 if (!FDecl)
Jordy Rose134a2362010-07-06 23:11:01 +00002016 return false;
Jordy Rose134a2362010-07-06 23:11:01 +00002017
Jordan Rose6e3cf2b2013-04-22 23:18:42 +00002018 // FIXME: Poorly-factored string switches are slow.
Craig Topper0dbb7832014-05-27 02:45:47 +00002019 FnCheck evalFunction = nullptr;
Anna Zaks6348a812012-02-17 22:35:26 +00002020 if (C.isCLibraryFunction(FDecl, "memcpy"))
2021 evalFunction = &CStringChecker::evalMemcpy;
2022 else if (C.isCLibraryFunction(FDecl, "mempcpy"))
2023 evalFunction = &CStringChecker::evalMempcpy;
2024 else if (C.isCLibraryFunction(FDecl, "memcmp"))
2025 evalFunction = &CStringChecker::evalMemcmp;
2026 else if (C.isCLibraryFunction(FDecl, "memmove"))
2027 evalFunction = &CStringChecker::evalMemmove;
2028 else if (C.isCLibraryFunction(FDecl, "strcpy"))
2029 evalFunction = &CStringChecker::evalStrcpy;
2030 else if (C.isCLibraryFunction(FDecl, "strncpy"))
2031 evalFunction = &CStringChecker::evalStrncpy;
2032 else if (C.isCLibraryFunction(FDecl, "stpcpy"))
2033 evalFunction = &CStringChecker::evalStpcpy;
2034 else if (C.isCLibraryFunction(FDecl, "strcat"))
2035 evalFunction = &CStringChecker::evalStrcat;
2036 else if (C.isCLibraryFunction(FDecl, "strncat"))
2037 evalFunction = &CStringChecker::evalStrncat;
2038 else if (C.isCLibraryFunction(FDecl, "strlen"))
2039 evalFunction = &CStringChecker::evalstrLength;
2040 else if (C.isCLibraryFunction(FDecl, "strnlen"))
2041 evalFunction = &CStringChecker::evalstrnLength;
2042 else if (C.isCLibraryFunction(FDecl, "strcmp"))
2043 evalFunction = &CStringChecker::evalStrcmp;
2044 else if (C.isCLibraryFunction(FDecl, "strncmp"))
2045 evalFunction = &CStringChecker::evalStrncmp;
2046 else if (C.isCLibraryFunction(FDecl, "strcasecmp"))
2047 evalFunction = &CStringChecker::evalStrcasecmp;
2048 else if (C.isCLibraryFunction(FDecl, "strncasecmp"))
2049 evalFunction = &CStringChecker::evalStrncasecmp;
Jordan Rose6e3cf2b2013-04-22 23:18:42 +00002050 else if (C.isCLibraryFunction(FDecl, "strsep"))
2051 evalFunction = &CStringChecker::evalStrsep;
Anna Zaks6348a812012-02-17 22:35:26 +00002052 else if (C.isCLibraryFunction(FDecl, "bcopy"))
2053 evalFunction = &CStringChecker::evalBcopy;
2054 else if (C.isCLibraryFunction(FDecl, "bcmp"))
2055 evalFunction = &CStringChecker::evalMemcmp;
Devin Coughlin9165df12016-02-07 16:55:44 +00002056 else if (isCPPStdLibraryFunction(FDecl, "copy"))
2057 evalFunction = &CStringChecker::evalStdCopy;
2058 else if (isCPPStdLibraryFunction(FDecl, "copy_backward"))
2059 evalFunction = &CStringChecker::evalStdCopyBackward;
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002060
Jordy Rosed5d2e502010-07-08 23:57:29 +00002061 // If the callee isn't a string function, let another checker handle it.
Ted Kremenekdc891422010-12-01 21:57:22 +00002062 if (!evalFunction)
Jordy Rose134a2362010-07-06 23:11:01 +00002063 return false;
2064
Jordy Rosed5d2e502010-07-08 23:57:29 +00002065 // Check and evaluate the call.
Ted Kremenekdc891422010-12-01 21:57:22 +00002066 (this->*evalFunction)(C, CE);
Anna Zakse0c7c272012-02-07 00:56:14 +00002067
2068 // If the evaluate call resulted in no change, chain to the next eval call
2069 // handler.
2070 // Note, the custom CString evaluation calls assume that basic safety
2071 // properties are held. However, if the user chooses to turn off some of these
2072 // checks, we ignore the issues and leave the call evaluation to a generic
2073 // handler.
Alexander Kornienko9c104902015-12-28 13:06:58 +00002074 return C.isDifferent();
Jordy Rose134a2362010-07-06 23:11:01 +00002075}
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002076
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00002077void CStringChecker::checkPreStmt(const DeclStmt *DS, CheckerContext &C) const {
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002078 // Record string length for char a[] = "abc";
Ted Kremenek49b1e382012-01-26 21:29:00 +00002079 ProgramStateRef state = C.getState();
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002080
Aaron Ballman535bbcc2014-03-14 17:01:24 +00002081 for (const auto *I : DS->decls()) {
2082 const VarDecl *D = dyn_cast<VarDecl>(I);
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002083 if (!D)
2084 continue;
2085
2086 // FIXME: Handle array fields of structs.
2087 if (!D->getType()->isArrayType())
2088 continue;
2089
2090 const Expr *Init = D->getInit();
2091 if (!Init)
2092 continue;
2093 if (!isa<StringLiteral>(Init))
2094 continue;
2095
Anna Zaksc9abbe22011-10-26 21:06:44 +00002096 Loc VarLoc = state->getLValue(D, C.getLocationContext());
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002097 const MemRegion *MR = VarLoc.getAsRegion();
2098 if (!MR)
2099 continue;
2100
Ted Kremenek632e3b72012-01-06 22:09:28 +00002101 SVal StrVal = state->getSVal(Init, C.getLocationContext());
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002102 assert(StrVal.isValid() && "Initializer string is unknown or undefined");
David Blaikie2fdacbc2013-02-20 05:52:05 +00002103 DefinedOrUnknownSVal strLength =
2104 getCStringLength(C, state, Init, StrVal).castAs<DefinedOrUnknownSVal>();
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002105
Ted Kremenek90af9092010-12-02 07:49:45 +00002106 state = state->set<CStringLength>(MR, strLength);
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002107 }
2108
Anna Zaksda4c8d62011-10-26 21:06:34 +00002109 C.addTransition(state);
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002110}
2111
Ted Kremenek49b1e382012-01-26 21:29:00 +00002112bool CStringChecker::wantsRegionChangeUpdate(ProgramStateRef state) const {
Jordan Rose0c153cb2012-11-02 01:54:06 +00002113 CStringLengthTy Entries = state->get<CStringLength>();
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002114 return !Entries.isEmpty();
2115}
2116
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002117ProgramStateRef
Ted Kremenek49b1e382012-01-26 21:29:00 +00002118CStringChecker::checkRegionChanges(ProgramStateRef state,
Anna Zaksdc154152012-12-20 00:38:25 +00002119 const InvalidatedSymbols *,
Jordy Rose1fad6632011-08-27 22:51:26 +00002120 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks3d348342012-02-14 21:55:24 +00002121 ArrayRef<const MemRegion *> Regions,
Jordan Rose742920c2012-07-02 19:27:35 +00002122 const CallEvent *Call) const {
Jordan Rose0c153cb2012-11-02 01:54:06 +00002123 CStringLengthTy Entries = state->get<CStringLength>();
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002124 if (Entries.isEmpty())
2125 return state;
2126
2127 llvm::SmallPtrSet<const MemRegion *, 8> Invalidated;
2128 llvm::SmallPtrSet<const MemRegion *, 32> SuperRegions;
2129
2130 // First build sets for the changed regions and their super-regions.
Jordy Rose1fad6632011-08-27 22:51:26 +00002131 for (ArrayRef<const MemRegion *>::iterator
2132 I = Regions.begin(), E = Regions.end(); I != E; ++I) {
2133 const MemRegion *MR = *I;
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002134 Invalidated.insert(MR);
2135
2136 SuperRegions.insert(MR);
2137 while (const SubRegion *SR = dyn_cast<SubRegion>(MR)) {
2138 MR = SR->getSuperRegion();
2139 SuperRegions.insert(MR);
2140 }
2141 }
2142
Jordan Rose0c153cb2012-11-02 01:54:06 +00002143 CStringLengthTy::Factory &F = state->get_context<CStringLength>();
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002144
2145 // Then loop over the entries in the current state.
Jordan Rose0c153cb2012-11-02 01:54:06 +00002146 for (CStringLengthTy::iterator I = Entries.begin(),
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002147 E = Entries.end(); I != E; ++I) {
2148 const MemRegion *MR = I.getKey();
2149
2150 // Is this entry for a super-region of a changed region?
2151 if (SuperRegions.count(MR)) {
Ted Kremenekb3b56c62010-11-24 00:54:37 +00002152 Entries = F.remove(Entries, MR);
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002153 continue;
2154 }
2155
2156 // Is this entry for a sub-region of a changed region?
2157 const MemRegion *Super = MR;
2158 while (const SubRegion *SR = dyn_cast<SubRegion>(Super)) {
2159 Super = SR->getSuperRegion();
2160 if (Invalidated.count(Super)) {
Ted Kremenekb3b56c62010-11-24 00:54:37 +00002161 Entries = F.remove(Entries, MR);
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002162 break;
2163 }
2164 }
2165 }
2166
2167 return state->set<CStringLength>(Entries);
2168}
2169
Ted Kremenek49b1e382012-01-26 21:29:00 +00002170void CStringChecker::checkLiveSymbols(ProgramStateRef state,
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00002171 SymbolReaper &SR) const {
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002172 // Mark all symbols in our string length map as valid.
Jordan Rose0c153cb2012-11-02 01:54:06 +00002173 CStringLengthTy Entries = state->get<CStringLength>();
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002174
Jordan Rose0c153cb2012-11-02 01:54:06 +00002175 for (CStringLengthTy::iterator I = Entries.begin(), E = Entries.end();
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002176 I != E; ++I) {
2177 SVal Len = I.getData();
Jordy Rose634c12d2011-06-15 05:52:56 +00002178
Anna Zaksee1a4352011-12-06 23:12:33 +00002179 for (SymExpr::symbol_iterator si = Len.symbol_begin(),
2180 se = Len.symbol_end(); si != se; ++si)
Jordy Rose634c12d2011-06-15 05:52:56 +00002181 SR.markInUse(*si);
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002182 }
2183}
2184
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00002185void CStringChecker::checkDeadSymbols(SymbolReaper &SR,
2186 CheckerContext &C) const {
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002187 if (!SR.hasDeadSymbols())
2188 return;
2189
Ted Kremenek49b1e382012-01-26 21:29:00 +00002190 ProgramStateRef state = C.getState();
Jordan Rose0c153cb2012-11-02 01:54:06 +00002191 CStringLengthTy Entries = state->get<CStringLength>();
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002192 if (Entries.isEmpty())
2193 return;
2194
Jordan Rose0c153cb2012-11-02 01:54:06 +00002195 CStringLengthTy::Factory &F = state->get_context<CStringLength>();
2196 for (CStringLengthTy::iterator I = Entries.begin(), E = Entries.end();
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002197 I != E; ++I) {
2198 SVal Len = I.getData();
2199 if (SymbolRef Sym = Len.getAsSymbol()) {
2200 if (SR.isDead(Sym))
Ted Kremenekb3b56c62010-11-24 00:54:37 +00002201 Entries = F.remove(Entries, I.getKey());
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002202 }
2203 }
2204
2205 state = state->set<CStringLength>(Entries);
Anna Zaksda4c8d62011-10-26 21:06:34 +00002206 C.addTransition(state);
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002207}
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00002208
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002209#define REGISTER_CHECKER(name) \
2210 void ento::register##name(CheckerManager &mgr) { \
2211 CStringChecker *checker = mgr.registerChecker<CStringChecker>(); \
2212 checker->Filter.Check##name = true; \
2213 checker->Filter.CheckName##name = mgr.getCurrentCheckName(); \
2214 }
Anna Zakse0c7c272012-02-07 00:56:14 +00002215
2216REGISTER_CHECKER(CStringNullArg)
2217REGISTER_CHECKER(CStringOutOfBounds)
2218REGISTER_CHECKER(CStringBufferOverlap)
2219REGISTER_CHECKER(CStringNotNullTerm)
Anna Zakse56167e2012-02-17 22:35:31 +00002220
2221void ento::registerCStringCheckerBasic(CheckerManager &Mgr) {
2222 registerCStringNullArg(Mgr);
2223}