blob: 17537445d66c5c87dc68b6e0fde6a2f1ec7942f7 [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
Jordy Rose134a2362010-07-06 23:11:01 +0000121 // Utility methods
Ted Kremenek49b1e382012-01-26 21:29:00 +0000122 std::pair<ProgramStateRef , ProgramStateRef >
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000123 static assumeZero(CheckerContext &C,
Ted Kremenek49b1e382012-01-26 21:29:00 +0000124 ProgramStateRef state, SVal V, QualType Ty);
Jordy Rosed5d2e502010-07-08 23:57:29 +0000125
Ted Kremenek49b1e382012-01-26 21:29:00 +0000126 static ProgramStateRef setCStringLength(ProgramStateRef state,
Ted Kremenek001fd5b2011-08-15 22:09:50 +0000127 const MemRegion *MR,
128 SVal strLength);
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000129 static SVal getCStringLengthForRegion(CheckerContext &C,
Ted Kremenek49b1e382012-01-26 21:29:00 +0000130 ProgramStateRef &state,
Ted Kremenek001fd5b2011-08-15 22:09:50 +0000131 const Expr *Ex,
132 const MemRegion *MR,
Jordy Rose634c12d2011-06-15 05:52:56 +0000133 bool hypothetical);
Ted Kremenek001fd5b2011-08-15 22:09:50 +0000134 SVal getCStringLength(CheckerContext &C,
Ted Kremenek49b1e382012-01-26 21:29:00 +0000135 ProgramStateRef &state,
Ted Kremenek001fd5b2011-08-15 22:09:50 +0000136 const Expr *Ex,
137 SVal Buf,
Jordy Rose634c12d2011-06-15 05:52:56 +0000138 bool hypothetical = false) const;
Jordy Roseb052e8f2010-07-27 01:37:31 +0000139
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000140 const StringLiteral *getCStringLiteral(CheckerContext &C,
Ted Kremenek49b1e382012-01-26 21:29:00 +0000141 ProgramStateRef &state,
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000142 const Expr *expr,
Lenny Maioranif3539ad2011-04-12 17:08:43 +0000143 SVal val) const;
144
Ted Kremenek49b1e382012-01-26 21:29:00 +0000145 static ProgramStateRef InvalidateBuffer(CheckerContext &C,
Anton Yartsev968c60a2013-11-17 09:18:48 +0000146 ProgramStateRef state,
147 const Expr *Ex, SVal V,
Devin Coughlin0da2e932015-09-24 16:52:56 +0000148 bool IsSourceBuffer,
149 const Expr *Size);
Jordy Rose722f5582010-08-16 07:51:42 +0000150
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000151 static bool SummarizeRegion(raw_ostream &os, ASTContext &Ctx,
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000152 const MemRegion *MR);
Jordy Roseb052e8f2010-07-27 01:37:31 +0000153
154 // Re-usable checks
Ted Kremenek49b1e382012-01-26 21:29:00 +0000155 ProgramStateRef checkNonNull(CheckerContext &C,
156 ProgramStateRef state,
Ted Kremenek001fd5b2011-08-15 22:09:50 +0000157 const Expr *S,
158 SVal l) const;
Ted Kremenek49b1e382012-01-26 21:29:00 +0000159 ProgramStateRef CheckLocation(CheckerContext &C,
160 ProgramStateRef state,
Ted Kremenek001fd5b2011-08-15 22:09:50 +0000161 const Expr *S,
162 SVal l,
Craig Topper0dbb7832014-05-27 02:45:47 +0000163 const char *message = nullptr) const;
Ted Kremenek49b1e382012-01-26 21:29:00 +0000164 ProgramStateRef CheckBufferAccess(CheckerContext &C,
165 ProgramStateRef state,
Ted Kremenek001fd5b2011-08-15 22:09:50 +0000166 const Expr *Size,
167 const Expr *FirstBuf,
168 const Expr *SecondBuf,
Craig Topper0dbb7832014-05-27 02:45:47 +0000169 const char *firstMessage = nullptr,
170 const char *secondMessage = nullptr,
Ted Kremenek001fd5b2011-08-15 22:09:50 +0000171 bool WarnAboutSize = false) const;
172
Ted Kremenek49b1e382012-01-26 21:29:00 +0000173 ProgramStateRef CheckBufferAccess(CheckerContext &C,
174 ProgramStateRef state,
Ted Kremenek001fd5b2011-08-15 22:09:50 +0000175 const Expr *Size,
176 const Expr *Buf,
Craig Topper0dbb7832014-05-27 02:45:47 +0000177 const char *message = nullptr,
Ted Kremenek001fd5b2011-08-15 22:09:50 +0000178 bool WarnAboutSize = false) const {
Jordy Rosedceb0cf2011-06-20 02:06:40 +0000179 // This is a convenience override.
Craig Topper0dbb7832014-05-27 02:45:47 +0000180 return CheckBufferAccess(C, state, Size, Buf, nullptr, message, nullptr,
Jordy Rose328deee2011-06-20 03:49:16 +0000181 WarnAboutSize);
Jordy Rosedceb0cf2011-06-20 02:06:40 +0000182 }
Ted Kremenek49b1e382012-01-26 21:29:00 +0000183 ProgramStateRef CheckOverlap(CheckerContext &C,
184 ProgramStateRef state,
Ted Kremenek001fd5b2011-08-15 22:09:50 +0000185 const Expr *Size,
186 const Expr *First,
187 const Expr *Second) const;
188 void emitOverlapBug(CheckerContext &C,
Ted Kremenek49b1e382012-01-26 21:29:00 +0000189 ProgramStateRef state,
Ted Kremenek001fd5b2011-08-15 22:09:50 +0000190 const Stmt *First,
191 const Stmt *Second) const;
192
Ted Kremenek49b1e382012-01-26 21:29:00 +0000193 ProgramStateRef checkAdditionOverflow(CheckerContext &C,
194 ProgramStateRef state,
Ted Kremenek001fd5b2011-08-15 22:09:50 +0000195 NonLoc left,
196 NonLoc right) const;
Devin Coughlin0da2e932015-09-24 16:52:56 +0000197
198 // Return true if the destination buffer of the copy function may be in bound.
199 // Expects SVal of Size to be positive and unsigned.
200 // Expects SVal of FirstBuf to be a FieldRegion.
201 static bool IsFirstBufInBound(CheckerContext &C,
202 ProgramStateRef state,
203 const Expr *FirstBuf,
204 const Expr *Size);
Jordy Rose134a2362010-07-06 23:11:01 +0000205};
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000206
Jordy Rose134a2362010-07-06 23:11:01 +0000207} //end anonymous namespace
208
Jordan Rose0c153cb2012-11-02 01:54:06 +0000209REGISTER_MAP_WITH_PROGRAMSTATE(CStringLength, const MemRegion *, SVal)
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000210
Jordy Rosed5d2e502010-07-08 23:57:29 +0000211//===----------------------------------------------------------------------===//
212// Individual checks and utility methods.
213//===----------------------------------------------------------------------===//
214
Ted Kremenek49b1e382012-01-26 21:29:00 +0000215std::pair<ProgramStateRef , ProgramStateRef >
216CStringChecker::assumeZero(CheckerContext &C, ProgramStateRef state, SVal V,
Jordy Rosed5d2e502010-07-08 23:57:29 +0000217 QualType Ty) {
David Blaikie05785d12013-02-20 22:23:23 +0000218 Optional<DefinedSVal> val = V.getAs<DefinedSVal>();
Ted Kremenek90af9092010-12-02 07:49:45 +0000219 if (!val)
Ted Kremenek49b1e382012-01-26 21:29:00 +0000220 return std::pair<ProgramStateRef , ProgramStateRef >(state, state);
Jordy Rose33c829a2010-07-07 07:48:06 +0000221
Ted Kremenek90af9092010-12-02 07:49:45 +0000222 SValBuilder &svalBuilder = C.getSValBuilder();
223 DefinedOrUnknownSVal zero = svalBuilder.makeZeroVal(Ty);
224 return state->assume(svalBuilder.evalEQ(state, *val, zero));
Jordy Rosed5d2e502010-07-08 23:57:29 +0000225}
Jordy Rose33c829a2010-07-07 07:48:06 +0000226
Ted Kremenek49b1e382012-01-26 21:29:00 +0000227ProgramStateRef CStringChecker::checkNonNull(CheckerContext &C,
228 ProgramStateRef state,
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000229 const Expr *S, SVal l) const {
Jordy Rosed5d2e502010-07-08 23:57:29 +0000230 // If a previous check has failed, propagate the failure.
231 if (!state)
Craig Topper0dbb7832014-05-27 02:45:47 +0000232 return nullptr;
Jordy Rosed5d2e502010-07-08 23:57:29 +0000233
Ted Kremenek49b1e382012-01-26 21:29:00 +0000234 ProgramStateRef stateNull, stateNonNull;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000235 std::tie(stateNull, stateNonNull) = assumeZero(C, state, l, S->getType());
Jordy Rosed5d2e502010-07-08 23:57:29 +0000236
237 if (stateNull && !stateNonNull) {
Anna Zakse0c7c272012-02-07 00:56:14 +0000238 if (!Filter.CheckCStringNullArg)
Craig Topper0dbb7832014-05-27 02:45:47 +0000239 return nullptr;
Anna Zakse0c7c272012-02-07 00:56:14 +0000240
Devin Coughline39bd402015-09-16 22:03:05 +0000241 ExplodedNode *N = C.generateErrorNode(stateNull);
Jordy Rose33c829a2010-07-07 07:48:06 +0000242 if (!N)
Craig Topper0dbb7832014-05-27 02:45:47 +0000243 return nullptr;
Jordy Rose33c829a2010-07-07 07:48:06 +0000244
Jordy Rosed5d2e502010-07-08 23:57:29 +0000245 if (!BT_Null)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000246 BT_Null.reset(new BuiltinBug(
247 Filter.CheckNameCStringNullArg, categories::UnixAPI,
248 "Null pointer argument in call to byte string function"));
Jordy Rose33c829a2010-07-07 07:48:06 +0000249
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000250 SmallString<80> buf;
Jordy Rosedceb0cf2011-06-20 02:06:40 +0000251 llvm::raw_svector_ostream os(buf);
252 assert(CurrentFunctionDescription);
253 os << "Null pointer argument in call to " << CurrentFunctionDescription;
254
Jordy Rose33c829a2010-07-07 07:48:06 +0000255 // Generate a report for this bug.
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000256 BuiltinBug *BT = static_cast<BuiltinBug*>(BT_Null.get());
Aaron Ballman8d3a7a52015-06-23 13:15:32 +0000257 auto report = llvm::make_unique<BugReport>(*BT, os.str(), N);
Jordy Rose33c829a2010-07-07 07:48:06 +0000258
259 report->addRange(S->getSourceRange());
Jordan Rosea0f7d352012-08-28 00:50:51 +0000260 bugreporter::trackNullOrUndefValue(N, S, *report);
Aaron Ballman8d3a7a52015-06-23 13:15:32 +0000261 C.emitReport(std::move(report));
Craig Topper0dbb7832014-05-27 02:45:47 +0000262 return nullptr;
Jordy Rose33c829a2010-07-07 07:48:06 +0000263 }
264
265 // From here on, assume that the value is non-null.
Jordy Rosed5d2e502010-07-08 23:57:29 +0000266 assert(stateNonNull);
267 return stateNonNull;
Jordy Rose33c829a2010-07-07 07:48:06 +0000268}
269
Jordy Rose134a2362010-07-06 23:11:01 +0000270// FIXME: This was originally copied from ArrayBoundChecker.cpp. Refactor?
Ted Kremenek49b1e382012-01-26 21:29:00 +0000271ProgramStateRef CStringChecker::CheckLocation(CheckerContext &C,
272 ProgramStateRef state,
Jordy Rose722f5582010-08-16 07:51:42 +0000273 const Expr *S, SVal l,
Jordy Rosedceb0cf2011-06-20 02:06:40 +0000274 const char *warningMsg) const {
Jordy Rosed5d2e502010-07-08 23:57:29 +0000275 // If a previous check has failed, propagate the failure.
276 if (!state)
Craig Topper0dbb7832014-05-27 02:45:47 +0000277 return nullptr;
Jordy Rosed5d2e502010-07-08 23:57:29 +0000278
Jordy Rose134a2362010-07-06 23:11:01 +0000279 // Check for out of bound array element access.
280 const MemRegion *R = l.getAsRegion();
281 if (!R)
282 return state;
283
Jordy Rose134a2362010-07-06 23:11:01 +0000284 const ElementRegion *ER = dyn_cast<ElementRegion>(R);
285 if (!ER)
286 return state;
287
Zhongxing Xu8de0a3d2010-08-11 06:10:55 +0000288 assert(ER->getValueType() == C.getASTContext().CharTy &&
Jordy Rose134a2362010-07-06 23:11:01 +0000289 "CheckLocation should only be called with char* ElementRegions");
290
291 // Get the size of the array.
Ted Kremenek90af9092010-12-02 07:49:45 +0000292 const SubRegion *superReg = cast<SubRegion>(ER->getSuperRegion());
293 SValBuilder &svalBuilder = C.getSValBuilder();
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000294 SVal Extent =
Jordy Rose455bd582011-06-16 05:51:02 +0000295 svalBuilder.convertToArrayIndex(superReg->getExtent(svalBuilder));
David Blaikie2fdacbc2013-02-20 05:52:05 +0000296 DefinedOrUnknownSVal Size = Extent.castAs<DefinedOrUnknownSVal>();
Jordy Rose134a2362010-07-06 23:11:01 +0000297
298 // Get the index of the accessed element.
David Blaikie87396b92013-02-21 22:23:56 +0000299 DefinedOrUnknownSVal Idx = ER->getIndex().castAs<DefinedOrUnknownSVal>();
Jordy Rose134a2362010-07-06 23:11:01 +0000300
Ted Kremenek49b1e382012-01-26 21:29:00 +0000301 ProgramStateRef StInBound = state->assumeInBound(Idx, Size, true);
302 ProgramStateRef StOutBound = state->assumeInBound(Idx, Size, false);
Jordy Rose134a2362010-07-06 23:11:01 +0000303 if (StOutBound && !StInBound) {
Devin Coughline39bd402015-09-16 22:03:05 +0000304 ExplodedNode *N = C.generateErrorNode(StOutBound);
Jordy Rose134a2362010-07-06 23:11:01 +0000305 if (!N)
Craig Topper0dbb7832014-05-27 02:45:47 +0000306 return nullptr;
Jordy Rose134a2362010-07-06 23:11:01 +0000307
Jordy Rosedceb0cf2011-06-20 02:06:40 +0000308 if (!BT_Bounds) {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000309 BT_Bounds.reset(new BuiltinBug(
310 Filter.CheckNameCStringOutOfBounds, "Out-of-bound array access",
311 "Byte string function accesses out-of-bound array element"));
Jordy Rosedceb0cf2011-06-20 02:06:40 +0000312 }
313 BuiltinBug *BT = static_cast<BuiltinBug*>(BT_Bounds.get());
314
315 // Generate a report for this bug.
Aaron Ballman8d3a7a52015-06-23 13:15:32 +0000316 std::unique_ptr<BugReport> report;
Jordy Rosedceb0cf2011-06-20 02:06:40 +0000317 if (warningMsg) {
Aaron Ballman8d3a7a52015-06-23 13:15:32 +0000318 report = llvm::make_unique<BugReport>(*BT, warningMsg, N);
Jordy Rose722f5582010-08-16 07:51:42 +0000319 } else {
Jordy Rosedceb0cf2011-06-20 02:06:40 +0000320 assert(CurrentFunctionDescription);
321 assert(CurrentFunctionDescription[0] != '\0');
322
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000323 SmallString<80> buf;
Jordy Rosedceb0cf2011-06-20 02:06:40 +0000324 llvm::raw_svector_ostream os(buf);
Jordan Rose4938f272013-02-09 10:09:43 +0000325 os << toUppercase(CurrentFunctionDescription[0])
Jordy Rosedceb0cf2011-06-20 02:06:40 +0000326 << &CurrentFunctionDescription[1]
327 << " accesses out-of-bound array element";
Aaron Ballman8d3a7a52015-06-23 13:15:32 +0000328 report = llvm::make_unique<BugReport>(*BT, os.str(), N);
Jordy Rose722f5582010-08-16 07:51:42 +0000329 }
Jordy Rose134a2362010-07-06 23:11:01 +0000330
331 // FIXME: It would be nice to eventually make this diagnostic more clear,
332 // e.g., by referencing the original declaration or by saying *why* this
333 // reference is outside the range.
334
Jordy Rose134a2362010-07-06 23:11:01 +0000335 report->addRange(S->getSourceRange());
Aaron Ballman8d3a7a52015-06-23 13:15:32 +0000336 C.emitReport(std::move(report));
Craig Topper0dbb7832014-05-27 02:45:47 +0000337 return nullptr;
Jordy Rose134a2362010-07-06 23:11:01 +0000338 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000339
Jordy Rose134a2362010-07-06 23:11:01 +0000340 // Array bound check succeeded. From this point forward the array bound
341 // should always succeed.
342 return StInBound;
343}
344
Ted Kremenek49b1e382012-01-26 21:29:00 +0000345ProgramStateRef CStringChecker::CheckBufferAccess(CheckerContext &C,
346 ProgramStateRef state,
Jordy Rose134a2362010-07-06 23:11:01 +0000347 const Expr *Size,
348 const Expr *FirstBuf,
Jordy Rose722f5582010-08-16 07:51:42 +0000349 const Expr *SecondBuf,
Jordy Rosedceb0cf2011-06-20 02:06:40 +0000350 const char *firstMessage,
Jordy Rose328deee2011-06-20 03:49:16 +0000351 const char *secondMessage,
352 bool WarnAboutSize) const {
Jordy Rosed5d2e502010-07-08 23:57:29 +0000353 // If a previous check has failed, propagate the failure.
354 if (!state)
Craig Topper0dbb7832014-05-27 02:45:47 +0000355 return nullptr;
Jordy Rosed5d2e502010-07-08 23:57:29 +0000356
Ted Kremenek90af9092010-12-02 07:49:45 +0000357 SValBuilder &svalBuilder = C.getSValBuilder();
Jordy Rose455bd582011-06-16 05:51:02 +0000358 ASTContext &Ctx = svalBuilder.getContext();
Ted Kremenek632e3b72012-01-06 22:09:28 +0000359 const LocationContext *LCtx = C.getLocationContext();
Jordy Rose134a2362010-07-06 23:11:01 +0000360
Ted Kremenek90af9092010-12-02 07:49:45 +0000361 QualType sizeTy = Size->getType();
Jordy Rose134a2362010-07-06 23:11:01 +0000362 QualType PtrTy = Ctx.getPointerType(Ctx.CharTy);
363
Jordy Rose33c829a2010-07-07 07:48:06 +0000364 // Check that the first buffer is non-null.
Ted Kremenek632e3b72012-01-06 22:09:28 +0000365 SVal BufVal = state->getSVal(FirstBuf, LCtx);
Ted Kremenek90af9092010-12-02 07:49:45 +0000366 state = checkNonNull(C, state, FirstBuf, BufVal);
Jordy Rose33c829a2010-07-07 07:48:06 +0000367 if (!state)
Craig Topper0dbb7832014-05-27 02:45:47 +0000368 return nullptr;
Jordy Rose33c829a2010-07-07 07:48:06 +0000369
Anna Zakse0c7c272012-02-07 00:56:14 +0000370 // If out-of-bounds checking is turned off, skip the rest.
371 if (!Filter.CheckCStringOutOfBounds)
372 return state;
373
Jordy Rosed5d2e502010-07-08 23:57:29 +0000374 // Get the access length and make sure it is known.
Jordy Rosedceb0cf2011-06-20 02:06:40 +0000375 // FIXME: This assumes the caller has already checked that the access length
376 // is positive. And that it's unsigned.
Ted Kremenek632e3b72012-01-06 22:09:28 +0000377 SVal LengthVal = state->getSVal(Size, LCtx);
David Blaikie05785d12013-02-20 22:23:23 +0000378 Optional<NonLoc> Length = LengthVal.getAs<NonLoc>();
Jordy Rosed5d2e502010-07-08 23:57:29 +0000379 if (!Length)
380 return state;
381
Jordy Rose134a2362010-07-06 23:11:01 +0000382 // Compute the offset of the last element to be accessed: size-1.
David Blaikie2fdacbc2013-02-20 05:52:05 +0000383 NonLoc One = svalBuilder.makeIntVal(1, sizeTy).castAs<NonLoc>();
384 NonLoc LastOffset = svalBuilder
385 .evalBinOpNN(state, BO_Sub, *Length, One, sizeTy).castAs<NonLoc>();
Jordy Rose134a2362010-07-06 23:11:01 +0000386
Chris Lattner57540c52011-04-15 05:22:18 +0000387 // Check that the first buffer is sufficiently long.
Ted Kremenek90af9092010-12-02 07:49:45 +0000388 SVal BufStart = svalBuilder.evalCast(BufVal, PtrTy, FirstBuf->getType());
David Blaikie05785d12013-02-20 22:23:23 +0000389 if (Optional<Loc> BufLoc = BufStart.getAs<Loc>()) {
Jordy Rose328deee2011-06-20 03:49:16 +0000390 const Expr *warningExpr = (WarnAboutSize ? Size : FirstBuf);
391
Ted Kremenek90af9092010-12-02 07:49:45 +0000392 SVal BufEnd = svalBuilder.evalBinOpLN(state, BO_Add, *BufLoc,
393 LastOffset, PtrTy);
Jordy Rose328deee2011-06-20 03:49:16 +0000394 state = CheckLocation(C, state, warningExpr, BufEnd, firstMessage);
Jordy Rose134a2362010-07-06 23:11:01 +0000395
Jordy Roseafdb0532010-08-05 23:11:30 +0000396 // If the buffer isn't large enough, abort.
397 if (!state)
Craig Topper0dbb7832014-05-27 02:45:47 +0000398 return nullptr;
Jordy Roseafdb0532010-08-05 23:11:30 +0000399 }
Jordy Rose134a2362010-07-06 23:11:01 +0000400
401 // If there's a second buffer, check it as well.
402 if (SecondBuf) {
Ted Kremenek632e3b72012-01-06 22:09:28 +0000403 BufVal = state->getSVal(SecondBuf, LCtx);
Ted Kremenek90af9092010-12-02 07:49:45 +0000404 state = checkNonNull(C, state, SecondBuf, BufVal);
Jordy Rose33c829a2010-07-07 07:48:06 +0000405 if (!state)
Craig Topper0dbb7832014-05-27 02:45:47 +0000406 return nullptr;
Jordy Rose33c829a2010-07-07 07:48:06 +0000407
Ted Kremenek90af9092010-12-02 07:49:45 +0000408 BufStart = svalBuilder.evalCast(BufVal, PtrTy, SecondBuf->getType());
David Blaikie05785d12013-02-20 22:23:23 +0000409 if (Optional<Loc> BufLoc = BufStart.getAs<Loc>()) {
Jordy Rose328deee2011-06-20 03:49:16 +0000410 const Expr *warningExpr = (WarnAboutSize ? Size : SecondBuf);
411
Ted Kremenek90af9092010-12-02 07:49:45 +0000412 SVal BufEnd = svalBuilder.evalBinOpLN(state, BO_Add, *BufLoc,
413 LastOffset, PtrTy);
Jordy Rose328deee2011-06-20 03:49:16 +0000414 state = CheckLocation(C, state, warningExpr, BufEnd, secondMessage);
Jordy Roseafdb0532010-08-05 23:11:30 +0000415 }
Jordy Rose134a2362010-07-06 23:11:01 +0000416 }
417
418 // Large enough or not, return this state!
419 return state;
420}
421
Ted Kremenek49b1e382012-01-26 21:29:00 +0000422ProgramStateRef CStringChecker::CheckOverlap(CheckerContext &C,
423 ProgramStateRef state,
Jordy Rosed5d2e502010-07-08 23:57:29 +0000424 const Expr *Size,
Jordy Rose134a2362010-07-06 23:11:01 +0000425 const Expr *First,
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000426 const Expr *Second) const {
Anna Zakse0c7c272012-02-07 00:56:14 +0000427 if (!Filter.CheckCStringBufferOverlap)
428 return state;
429
Jordy Rose134a2362010-07-06 23:11:01 +0000430 // Do a simple check for overlap: if the two arguments are from the same
431 // buffer, see if the end of the first is greater than the start of the second
432 // or vice versa.
433
Jordy Rosed5d2e502010-07-08 23:57:29 +0000434 // If a previous check has failed, propagate the failure.
435 if (!state)
Craig Topper0dbb7832014-05-27 02:45:47 +0000436 return nullptr;
Jordy Rosed5d2e502010-07-08 23:57:29 +0000437
Ted Kremenek49b1e382012-01-26 21:29:00 +0000438 ProgramStateRef stateTrue, stateFalse;
Jordy Rose134a2362010-07-06 23:11:01 +0000439
440 // Get the buffer values and make sure they're known locations.
Ted Kremenek632e3b72012-01-06 22:09:28 +0000441 const LocationContext *LCtx = C.getLocationContext();
442 SVal firstVal = state->getSVal(First, LCtx);
443 SVal secondVal = state->getSVal(Second, LCtx);
Jordy Rose134a2362010-07-06 23:11:01 +0000444
David Blaikie05785d12013-02-20 22:23:23 +0000445 Optional<Loc> firstLoc = firstVal.getAs<Loc>();
Ted Kremenek90af9092010-12-02 07:49:45 +0000446 if (!firstLoc)
Jordy Rose134a2362010-07-06 23:11:01 +0000447 return state;
448
David Blaikie05785d12013-02-20 22:23:23 +0000449 Optional<Loc> secondLoc = secondVal.getAs<Loc>();
Ted Kremenek90af9092010-12-02 07:49:45 +0000450 if (!secondLoc)
Jordy Rose134a2362010-07-06 23:11:01 +0000451 return state;
452
453 // Are the two values the same?
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000454 SValBuilder &svalBuilder = C.getSValBuilder();
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000455 std::tie(stateTrue, stateFalse) =
Ted Kremenek90af9092010-12-02 07:49:45 +0000456 state->assume(svalBuilder.evalEQ(state, *firstLoc, *secondLoc));
Jordy Rose134a2362010-07-06 23:11:01 +0000457
458 if (stateTrue && !stateFalse) {
459 // If the values are known to be equal, that's automatically an overlap.
Ted Kremenek90af9092010-12-02 07:49:45 +0000460 emitOverlapBug(C, stateTrue, First, Second);
Craig Topper0dbb7832014-05-27 02:45:47 +0000461 return nullptr;
Jordy Rose134a2362010-07-06 23:11:01 +0000462 }
463
Ted Kremenekc5bea1e2010-12-01 22:16:56 +0000464 // assume the two expressions are not equal.
Jordy Rose134a2362010-07-06 23:11:01 +0000465 assert(stateFalse);
466 state = stateFalse;
467
468 // Which value comes first?
Jordy Rose0585a612011-06-16 05:56:50 +0000469 QualType cmpTy = svalBuilder.getConditionType();
Ted Kremenek90af9092010-12-02 07:49:45 +0000470 SVal reverse = svalBuilder.evalBinOpLL(state, BO_GT,
471 *firstLoc, *secondLoc, cmpTy);
David Blaikie05785d12013-02-20 22:23:23 +0000472 Optional<DefinedOrUnknownSVal> reverseTest =
David Blaikie2fdacbc2013-02-20 05:52:05 +0000473 reverse.getAs<DefinedOrUnknownSVal>();
Ted Kremenek90af9092010-12-02 07:49:45 +0000474 if (!reverseTest)
Jordy Rose134a2362010-07-06 23:11:01 +0000475 return state;
476
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000477 std::tie(stateTrue, stateFalse) = state->assume(*reverseTest);
Jordy Rose134a2362010-07-06 23:11:01 +0000478 if (stateTrue) {
479 if (stateFalse) {
480 // If we don't know which one comes first, we can't perform this test.
481 return state;
482 } else {
Ted Kremenek90af9092010-12-02 07:49:45 +0000483 // Switch the values so that firstVal is before secondVal.
David Blaikie2fdacbc2013-02-20 05:52:05 +0000484 std::swap(firstLoc, secondLoc);
Jordy Rose134a2362010-07-06 23:11:01 +0000485
486 // Switch the Exprs as well, so that they still correspond.
David Blaikie2fdacbc2013-02-20 05:52:05 +0000487 std::swap(First, Second);
Jordy Rose134a2362010-07-06 23:11:01 +0000488 }
489 }
490
491 // Get the length, and make sure it too is known.
Ted Kremenek632e3b72012-01-06 22:09:28 +0000492 SVal LengthVal = state->getSVal(Size, LCtx);
David Blaikie05785d12013-02-20 22:23:23 +0000493 Optional<NonLoc> Length = LengthVal.getAs<NonLoc>();
Jordy Rose134a2362010-07-06 23:11:01 +0000494 if (!Length)
495 return state;
496
497 // Convert the first buffer's start address to char*.
498 // Bail out if the cast fails.
Jordy Rose0585a612011-06-16 05:56:50 +0000499 ASTContext &Ctx = svalBuilder.getContext();
Jordy Rose134a2362010-07-06 23:11:01 +0000500 QualType CharPtrTy = Ctx.getPointerType(Ctx.CharTy);
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000501 SVal FirstStart = svalBuilder.evalCast(*firstLoc, CharPtrTy,
Jordy Rose455bd582011-06-16 05:51:02 +0000502 First->getType());
David Blaikie05785d12013-02-20 22:23:23 +0000503 Optional<Loc> FirstStartLoc = FirstStart.getAs<Loc>();
Jordy Rose134a2362010-07-06 23:11:01 +0000504 if (!FirstStartLoc)
505 return state;
506
507 // Compute the end of the first buffer. Bail out if THAT fails.
Ted Kremenek90af9092010-12-02 07:49:45 +0000508 SVal FirstEnd = svalBuilder.evalBinOpLN(state, BO_Add,
Jordy Rose134a2362010-07-06 23:11:01 +0000509 *FirstStartLoc, *Length, CharPtrTy);
David Blaikie05785d12013-02-20 22:23:23 +0000510 Optional<Loc> FirstEndLoc = FirstEnd.getAs<Loc>();
Jordy Rose134a2362010-07-06 23:11:01 +0000511 if (!FirstEndLoc)
512 return state;
513
514 // Is the end of the first buffer past the start of the second buffer?
Ted Kremenek90af9092010-12-02 07:49:45 +0000515 SVal Overlap = svalBuilder.evalBinOpLL(state, BO_GT,
516 *FirstEndLoc, *secondLoc, cmpTy);
David Blaikie05785d12013-02-20 22:23:23 +0000517 Optional<DefinedOrUnknownSVal> OverlapTest =
David Blaikie2fdacbc2013-02-20 05:52:05 +0000518 Overlap.getAs<DefinedOrUnknownSVal>();
Jordy Rose134a2362010-07-06 23:11:01 +0000519 if (!OverlapTest)
520 return state;
521
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000522 std::tie(stateTrue, stateFalse) = state->assume(*OverlapTest);
Jordy Rose134a2362010-07-06 23:11:01 +0000523
524 if (stateTrue && !stateFalse) {
525 // Overlap!
Ted Kremenek90af9092010-12-02 07:49:45 +0000526 emitOverlapBug(C, stateTrue, First, Second);
Craig Topper0dbb7832014-05-27 02:45:47 +0000527 return nullptr;
Jordy Rose134a2362010-07-06 23:11:01 +0000528 }
529
Ted Kremenekc5bea1e2010-12-01 22:16:56 +0000530 // assume the two expressions don't overlap.
Jordy Rose134a2362010-07-06 23:11:01 +0000531 assert(stateFalse);
532 return stateFalse;
533}
534
Ted Kremenek49b1e382012-01-26 21:29:00 +0000535void CStringChecker::emitOverlapBug(CheckerContext &C, ProgramStateRef state,
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000536 const Stmt *First, const Stmt *Second) const {
Devin Coughline39bd402015-09-16 22:03:05 +0000537 ExplodedNode *N = C.generateErrorNode(state);
Jordy Rose134a2362010-07-06 23:11:01 +0000538 if (!N)
539 return;
540
541 if (!BT_Overlap)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000542 BT_Overlap.reset(new BugType(Filter.CheckNameCStringBufferOverlap,
543 categories::UnixAPI, "Improper arguments"));
Jordy Rose134a2362010-07-06 23:11:01 +0000544
545 // Generate a report for this bug.
Aaron Ballman8d3a7a52015-06-23 13:15:32 +0000546 auto report = llvm::make_unique<BugReport>(
547 *BT_Overlap, "Arguments must not be overlapping buffers", N);
Jordy Rose134a2362010-07-06 23:11:01 +0000548 report->addRange(First->getSourceRange());
549 report->addRange(Second->getSourceRange());
550
Aaron Ballman8d3a7a52015-06-23 13:15:32 +0000551 C.emitReport(std::move(report));
Jordy Rose134a2362010-07-06 23:11:01 +0000552}
553
Ted Kremenek49b1e382012-01-26 21:29:00 +0000554ProgramStateRef CStringChecker::checkAdditionOverflow(CheckerContext &C,
555 ProgramStateRef state,
Jordy Rose634c12d2011-06-15 05:52:56 +0000556 NonLoc left,
557 NonLoc right) const {
Anna Zakse0c7c272012-02-07 00:56:14 +0000558 // If out-of-bounds checking is turned off, skip the rest.
559 if (!Filter.CheckCStringOutOfBounds)
560 return state;
561
Jordy Rose634c12d2011-06-15 05:52:56 +0000562 // If a previous check has failed, propagate the failure.
563 if (!state)
Craig Topper0dbb7832014-05-27 02:45:47 +0000564 return nullptr;
Jordy Rose634c12d2011-06-15 05:52:56 +0000565
566 SValBuilder &svalBuilder = C.getSValBuilder();
567 BasicValueFactory &BVF = svalBuilder.getBasicValueFactory();
568
569 QualType sizeTy = svalBuilder.getContext().getSizeType();
570 const llvm::APSInt &maxValInt = BVF.getMaxValue(sizeTy);
571 NonLoc maxVal = svalBuilder.makeIntVal(maxValInt);
572
Anna Zaks7c96b7d2011-12-11 18:43:40 +0000573 SVal maxMinusRight;
David Blaikie2fdacbc2013-02-20 05:52:05 +0000574 if (right.getAs<nonloc::ConcreteInt>()) {
Anna Zaks7c96b7d2011-12-11 18:43:40 +0000575 maxMinusRight = svalBuilder.evalBinOpNN(state, BO_Sub, maxVal, right,
576 sizeTy);
577 } else {
Jordy Rose634c12d2011-06-15 05:52:56 +0000578 // Try switching the operands. (The order of these two assignments is
579 // important!)
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000580 maxMinusRight = svalBuilder.evalBinOpNN(state, BO_Sub, maxVal, left,
Jordy Rose634c12d2011-06-15 05:52:56 +0000581 sizeTy);
582 left = right;
583 }
584
David Blaikie05785d12013-02-20 22:23:23 +0000585 if (Optional<NonLoc> maxMinusRightNL = maxMinusRight.getAs<NonLoc>()) {
Jordy Rose634c12d2011-06-15 05:52:56 +0000586 QualType cmpTy = svalBuilder.getConditionType();
587 // If left > max - right, we have an overflow.
588 SVal willOverflow = svalBuilder.evalBinOpNN(state, BO_GT, left,
589 *maxMinusRightNL, cmpTy);
590
Ted Kremenek49b1e382012-01-26 21:29:00 +0000591 ProgramStateRef stateOverflow, stateOkay;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000592 std::tie(stateOverflow, stateOkay) =
David Blaikie2fdacbc2013-02-20 05:52:05 +0000593 state->assume(willOverflow.castAs<DefinedOrUnknownSVal>());
Jordy Rose634c12d2011-06-15 05:52:56 +0000594
595 if (stateOverflow && !stateOkay) {
596 // We have an overflow. Emit a bug report.
Devin Coughline39bd402015-09-16 22:03:05 +0000597 ExplodedNode *N = C.generateErrorNode(stateOverflow);
Jordy Rose634c12d2011-06-15 05:52:56 +0000598 if (!N)
Craig Topper0dbb7832014-05-27 02:45:47 +0000599 return nullptr;
Jordy Rose634c12d2011-06-15 05:52:56 +0000600
601 if (!BT_AdditionOverflow)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000602 BT_AdditionOverflow.reset(
603 new BuiltinBug(Filter.CheckNameCStringOutOfBounds, "API",
604 "Sum of expressions causes overflow"));
Jordy Rose634c12d2011-06-15 05:52:56 +0000605
Jordy Rose634c12d2011-06-15 05:52:56 +0000606 // This isn't a great error message, but this should never occur in real
607 // code anyway -- you'd have to create a buffer longer than a size_t can
608 // represent, which is sort of a contradiction.
Jordy Rose789adbb2011-06-20 03:51:53 +0000609 const char *warning =
610 "This expression will create a string whose length is too big to "
611 "be represented as a size_t";
Jordy Rose634c12d2011-06-15 05:52:56 +0000612
613 // Generate a report for this bug.
Aaron Ballman8d3a7a52015-06-23 13:15:32 +0000614 C.emitReport(
615 llvm::make_unique<BugReport>(*BT_AdditionOverflow, warning, N));
Jordy Rose634c12d2011-06-15 05:52:56 +0000616
Craig Topper0dbb7832014-05-27 02:45:47 +0000617 return nullptr;
Jordy Rose634c12d2011-06-15 05:52:56 +0000618 }
619
620 // From now on, assume an overflow didn't occur.
621 assert(stateOkay);
622 state = stateOkay;
623 }
624
625 return state;
626}
627
Ted Kremenek49b1e382012-01-26 21:29:00 +0000628ProgramStateRef CStringChecker::setCStringLength(ProgramStateRef state,
Jordy Rose722f5582010-08-16 07:51:42 +0000629 const MemRegion *MR,
Ted Kremenek90af9092010-12-02 07:49:45 +0000630 SVal strLength) {
631 assert(!strLength.isUndef() && "Attempt to set an undefined string length");
Jordy Rose722f5582010-08-16 07:51:42 +0000632
633 MR = MR->StripCasts();
634
635 switch (MR->getKind()) {
636 case MemRegion::StringRegionKind:
637 // FIXME: This can happen if we strcpy() into a string region. This is
638 // undefined [C99 6.4.5p6], but we should still warn about it.
639 return state;
640
641 case MemRegion::SymbolicRegionKind:
642 case MemRegion::AllocaRegionKind:
643 case MemRegion::VarRegionKind:
644 case MemRegion::FieldRegionKind:
645 case MemRegion::ObjCIvarRegionKind:
Jordy Rose0e9fb282011-06-15 05:14:03 +0000646 // These are the types we can currently track string lengths for.
647 break;
Jordy Rose722f5582010-08-16 07:51:42 +0000648
649 case MemRegion::ElementRegionKind:
650 // FIXME: Handle element regions by upper-bounding the parent region's
651 // string length.
652 return state;
653
654 default:
655 // Other regions (mostly non-data) can't have a reliable C string length.
656 // For now, just ignore the change.
657 // FIXME: These are rare but not impossible. We should output some kind of
658 // warning for things like strcpy((char[]){'a', 0}, "b");
659 return state;
660 }
Jordy Rose0e9fb282011-06-15 05:14:03 +0000661
662 if (strLength.isUnknown())
663 return state->remove<CStringLength>(MR);
664
665 return state->set<CStringLength>(MR, strLength);
Jordy Rose722f5582010-08-16 07:51:42 +0000666}
667
Ted Kremenek90af9092010-12-02 07:49:45 +0000668SVal CStringChecker::getCStringLengthForRegion(CheckerContext &C,
Ted Kremenek49b1e382012-01-26 21:29:00 +0000669 ProgramStateRef &state,
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000670 const Expr *Ex,
Jordy Rose634c12d2011-06-15 05:52:56 +0000671 const MemRegion *MR,
672 bool hypothetical) {
673 if (!hypothetical) {
674 // If there's a recorded length, go ahead and return it.
675 const SVal *Recorded = state->get<CStringLength>(MR);
676 if (Recorded)
677 return *Recorded;
678 }
Jordan Rose60619a62013-08-19 16:27:34 +0000679
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000680 // Otherwise, get a new symbol and update the state.
Ted Kremenek90af9092010-12-02 07:49:45 +0000681 SValBuilder &svalBuilder = C.getSValBuilder();
682 QualType sizeTy = svalBuilder.getContext().getSizeType();
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000683 SVal strLength = svalBuilder.getMetadataSymbolVal(CStringChecker::getTag(),
Ted Kremenekd94854a2012-08-22 06:26:15 +0000684 MR, Ex, sizeTy,
685 C.blockCount());
Jordy Rose634c12d2011-06-15 05:52:56 +0000686
Jordan Rose60619a62013-08-19 16:27:34 +0000687 if (!hypothetical) {
688 if (Optional<NonLoc> strLn = strLength.getAs<NonLoc>()) {
689 // In case of unbounded calls strlen etc bound the range to SIZE_MAX/4
690 BasicValueFactory &BVF = svalBuilder.getBasicValueFactory();
691 const llvm::APSInt &maxValInt = BVF.getMaxValue(sizeTy);
692 llvm::APSInt fourInt = APSIntType(maxValInt).getValue(4);
693 const llvm::APSInt *maxLengthInt = BVF.evalAPSInt(BO_Div, maxValInt,
694 fourInt);
695 NonLoc maxLength = svalBuilder.makeIntVal(*maxLengthInt);
696 SVal evalLength = svalBuilder.evalBinOpNN(state, BO_LE, *strLn,
697 maxLength, sizeTy);
698 state = state->assume(evalLength.castAs<DefinedOrUnknownSVal>(), true);
699 }
Jordy Rose634c12d2011-06-15 05:52:56 +0000700 state = state->set<CStringLength>(MR, strLength);
Jordan Rose60619a62013-08-19 16:27:34 +0000701 }
Jordy Rose634c12d2011-06-15 05:52:56 +0000702
Ted Kremenek90af9092010-12-02 07:49:45 +0000703 return strLength;
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000704}
705
Ted Kremenek49b1e382012-01-26 21:29:00 +0000706SVal CStringChecker::getCStringLength(CheckerContext &C, ProgramStateRef &state,
Jordy Rose634c12d2011-06-15 05:52:56 +0000707 const Expr *Ex, SVal Buf,
708 bool hypothetical) const {
Jordy Roseb052e8f2010-07-27 01:37:31 +0000709 const MemRegion *MR = Buf.getAsRegion();
710 if (!MR) {
711 // If we can't get a region, see if it's something we /know/ isn't a
712 // C string. In the context of locations, the only time we can issue such
713 // a warning is for labels.
David Blaikie05785d12013-02-20 22:23:23 +0000714 if (Optional<loc::GotoLabel> Label = Buf.getAs<loc::GotoLabel>()) {
Anna Zakse0c7c272012-02-07 00:56:14 +0000715 if (!Filter.CheckCStringNotNullTerm)
716 return UndefinedVal();
717
Devin Coughline39bd402015-09-16 22:03:05 +0000718 if (ExplodedNode *N = C.generateNonFatalErrorNode(state)) {
Jordy Roseb052e8f2010-07-27 01:37:31 +0000719 if (!BT_NotCString)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000720 BT_NotCString.reset(new BuiltinBug(
721 Filter.CheckNameCStringNotNullTerm, categories::UnixAPI,
722 "Argument is not a null-terminated string."));
Jordy Roseb052e8f2010-07-27 01:37:31 +0000723
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000724 SmallString<120> buf;
Jordy Roseb052e8f2010-07-27 01:37:31 +0000725 llvm::raw_svector_ostream os(buf);
Jordy Rosedceb0cf2011-06-20 02:06:40 +0000726 assert(CurrentFunctionDescription);
727 os << "Argument to " << CurrentFunctionDescription
728 << " is the address of the label '" << Label->getLabel()->getName()
Jordy Roseb052e8f2010-07-27 01:37:31 +0000729 << "', which is not a null-terminated string";
730
731 // Generate a report for this bug.
Aaron Ballman8d3a7a52015-06-23 13:15:32 +0000732 auto report = llvm::make_unique<BugReport>(*BT_NotCString, os.str(), N);
Jordy Roseb052e8f2010-07-27 01:37:31 +0000733
734 report->addRange(Ex->getSourceRange());
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000735 C.emitReport(std::move(report));
Jordy Roseb052e8f2010-07-27 01:37:31 +0000736 }
Jordy Roseb052e8f2010-07-27 01:37:31 +0000737 return UndefinedVal();
Anna Zakse0c7c272012-02-07 00:56:14 +0000738
Jordy Roseb052e8f2010-07-27 01:37:31 +0000739 }
740
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000741 // If it's not a region and not a label, give up.
742 return UnknownVal();
Jordy Roseb052e8f2010-07-27 01:37:31 +0000743 }
744
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000745 // If we have a region, strip casts from it and see if we can figure out
746 // its length. For anything we can't figure out, just return UnknownVal.
747 MR = MR->StripCasts();
748
749 switch (MR->getKind()) {
750 case MemRegion::StringRegionKind: {
751 // Modifying the contents of string regions is undefined [C99 6.4.5p6],
752 // so we can assume that the byte length is the correct C string length.
Ted Kremenek90af9092010-12-02 07:49:45 +0000753 SValBuilder &svalBuilder = C.getSValBuilder();
754 QualType sizeTy = svalBuilder.getContext().getSizeType();
755 const StringLiteral *strLit = cast<StringRegion>(MR)->getStringLiteral();
756 return svalBuilder.makeIntVal(strLit->getByteLength(), sizeTy);
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000757 }
758 case MemRegion::SymbolicRegionKind:
759 case MemRegion::AllocaRegionKind:
760 case MemRegion::VarRegionKind:
761 case MemRegion::FieldRegionKind:
762 case MemRegion::ObjCIvarRegionKind:
Jordy Rose634c12d2011-06-15 05:52:56 +0000763 return getCStringLengthForRegion(C, state, Ex, MR, hypothetical);
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000764 case MemRegion::CompoundLiteralRegionKind:
765 // FIXME: Can we track this? Is it necessary?
766 return UnknownVal();
767 case MemRegion::ElementRegionKind:
768 // FIXME: How can we handle this? It's not good enough to subtract the
769 // offset from the base string length; consider "123\x00567" and &a[5].
770 return UnknownVal();
771 default:
772 // Other regions (mostly non-data) can't have a reliable C string length.
773 // In this case, an error is emitted and UndefinedVal is returned.
774 // The caller should always be prepared to handle this case.
Anna Zakse0c7c272012-02-07 00:56:14 +0000775 if (!Filter.CheckCStringNotNullTerm)
776 return UndefinedVal();
777
Devin Coughline39bd402015-09-16 22:03:05 +0000778 if (ExplodedNode *N = C.generateNonFatalErrorNode(state)) {
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000779 if (!BT_NotCString)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000780 BT_NotCString.reset(new BuiltinBug(
781 Filter.CheckNameCStringNotNullTerm, categories::UnixAPI,
782 "Argument is not a null-terminated string."));
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000783
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000784 SmallString<120> buf;
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000785 llvm::raw_svector_ostream os(buf);
786
Jordy Rosedceb0cf2011-06-20 02:06:40 +0000787 assert(CurrentFunctionDescription);
788 os << "Argument to " << CurrentFunctionDescription << " is ";
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000789
790 if (SummarizeRegion(os, C.getASTContext(), MR))
791 os << ", which is not a null-terminated string";
792 else
793 os << "not a null-terminated string";
794
795 // Generate a report for this bug.
Aaron Ballman8d3a7a52015-06-23 13:15:32 +0000796 auto report = llvm::make_unique<BugReport>(*BT_NotCString, os.str(), N);
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000797
798 report->addRange(Ex->getSourceRange());
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000799 C.emitReport(std::move(report));
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000800 }
801
802 return UndefinedVal();
803 }
Jordy Roseb052e8f2010-07-27 01:37:31 +0000804}
805
Lenny Maioranif3539ad2011-04-12 17:08:43 +0000806const StringLiteral *CStringChecker::getCStringLiteral(CheckerContext &C,
Ted Kremenek49b1e382012-01-26 21:29:00 +0000807 ProgramStateRef &state, const Expr *expr, SVal val) const {
Lenny Maioranif3539ad2011-04-12 17:08:43 +0000808
809 // Get the memory region pointed to by the val.
810 const MemRegion *bufRegion = val.getAsRegion();
811 if (!bufRegion)
Craig Topper0dbb7832014-05-27 02:45:47 +0000812 return nullptr;
Lenny Maioranif3539ad2011-04-12 17:08:43 +0000813
814 // Strip casts off the memory region.
815 bufRegion = bufRegion->StripCasts();
816
817 // Cast the memory region to a string region.
818 const StringRegion *strRegion= dyn_cast<StringRegion>(bufRegion);
819 if (!strRegion)
Craig Topper0dbb7832014-05-27 02:45:47 +0000820 return nullptr;
Lenny Maioranif3539ad2011-04-12 17:08:43 +0000821
822 // Return the actual string in the string region.
823 return strRegion->getStringLiteral();
824}
825
Devin Coughlin0da2e932015-09-24 16:52:56 +0000826bool CStringChecker::IsFirstBufInBound(CheckerContext &C,
827 ProgramStateRef state,
828 const Expr *FirstBuf,
829 const Expr *Size) {
830 // If we do not know that the buffer is long enough we return 'true'.
831 // Otherwise the parent region of this field region would also get
832 // invalidated, which would lead to warnings based on an unknown state.
833
834 // Originally copied from CheckBufferAccess and CheckLocation.
835 SValBuilder &svalBuilder = C.getSValBuilder();
836 ASTContext &Ctx = svalBuilder.getContext();
837 const LocationContext *LCtx = C.getLocationContext();
838
839 QualType sizeTy = Size->getType();
840 QualType PtrTy = Ctx.getPointerType(Ctx.CharTy);
841 SVal BufVal = state->getSVal(FirstBuf, LCtx);
842
843 SVal LengthVal = state->getSVal(Size, LCtx);
844 Optional<NonLoc> Length = LengthVal.getAs<NonLoc>();
845 if (!Length)
846 return true; // cf top comment.
847
848 // Compute the offset of the last element to be accessed: size-1.
849 NonLoc One = svalBuilder.makeIntVal(1, sizeTy).castAs<NonLoc>();
850 NonLoc LastOffset =
851 svalBuilder.evalBinOpNN(state, BO_Sub, *Length, One, sizeTy)
852 .castAs<NonLoc>();
853
854 // Check that the first buffer is sufficiently long.
855 SVal BufStart = svalBuilder.evalCast(BufVal, PtrTy, FirstBuf->getType());
856 Optional<Loc> BufLoc = BufStart.getAs<Loc>();
857 if (!BufLoc)
858 return true; // cf top comment.
859
860 SVal BufEnd =
861 svalBuilder.evalBinOpLN(state, BO_Add, *BufLoc, LastOffset, PtrTy);
862
863 // Check for out of bound array element access.
864 const MemRegion *R = BufEnd.getAsRegion();
865 if (!R)
866 return true; // cf top comment.
867
868 const ElementRegion *ER = dyn_cast<ElementRegion>(R);
869 if (!ER)
870 return true; // cf top comment.
871
872 assert(ER->getValueType() == C.getASTContext().CharTy &&
873 "IsFirstBufInBound should only be called with char* ElementRegions");
874
875 // Get the size of the array.
876 const SubRegion *superReg = cast<SubRegion>(ER->getSuperRegion());
877 SVal Extent =
878 svalBuilder.convertToArrayIndex(superReg->getExtent(svalBuilder));
879 DefinedOrUnknownSVal ExtentSize = Extent.castAs<DefinedOrUnknownSVal>();
880
881 // Get the index of the accessed element.
882 DefinedOrUnknownSVal Idx = ER->getIndex().castAs<DefinedOrUnknownSVal>();
883
884 ProgramStateRef StInBound = state->assumeInBound(Idx, ExtentSize, true);
885
886 return static_cast<bool>(StInBound);
887}
888
Ted Kremenek49b1e382012-01-26 21:29:00 +0000889ProgramStateRef CStringChecker::InvalidateBuffer(CheckerContext &C,
Anton Yartsev968c60a2013-11-17 09:18:48 +0000890 ProgramStateRef state,
891 const Expr *E, SVal V,
Devin Coughlin0da2e932015-09-24 16:52:56 +0000892 bool IsSourceBuffer,
893 const Expr *Size) {
David Blaikie05785d12013-02-20 22:23:23 +0000894 Optional<Loc> L = V.getAs<Loc>();
Jordy Rose722f5582010-08-16 07:51:42 +0000895 if (!L)
896 return state;
897
898 // FIXME: This is a simplified version of what's in CFRefCount.cpp -- it makes
899 // some assumptions about the value that CFRefCount can't. Even so, it should
900 // probably be refactored.
David Blaikie05785d12013-02-20 22:23:23 +0000901 if (Optional<loc::MemRegionVal> MR = L->getAs<loc::MemRegionVal>()) {
Jordy Rose722f5582010-08-16 07:51:42 +0000902 const MemRegion *R = MR->getRegion()->StripCasts();
903
904 // Are we dealing with an ElementRegion? If so, we should be invalidating
905 // the super-region.
906 if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
907 R = ER->getSuperRegion();
908 // FIXME: What about layers of ElementRegions?
909 }
910
911 // Invalidate this region.
Ted Kremenekd519cae2012-02-17 23:13:45 +0000912 const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
Anton Yartsev968c60a2013-11-17 09:18:48 +0000913
914 bool CausesPointerEscape = false;
915 RegionAndSymbolInvalidationTraits ITraits;
916 // Invalidate and escape only indirect regions accessible through the source
917 // buffer.
918 if (IsSourceBuffer) {
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000919 ITraits.setTrait(R,
Anton Yartsev968c60a2013-11-17 09:18:48 +0000920 RegionAndSymbolInvalidationTraits::TK_PreserveContents);
921 ITraits.setTrait(R, RegionAndSymbolInvalidationTraits::TK_SuppressEscape);
922 CausesPointerEscape = true;
Devin Coughlin0da2e932015-09-24 16:52:56 +0000923 } else {
924 const MemRegion::Kind& K = R->getKind();
925 if (K == MemRegion::FieldRegionKind)
926 if (Size && IsFirstBufInBound(C, state, E, Size)) {
927 // If destination buffer is a field region and access is in bound,
928 // do not invalidate its super region.
929 ITraits.setTrait(
930 R,
931 RegionAndSymbolInvalidationTraits::TK_DoNotInvalidateSuperRegion);
932 }
Anton Yartsev968c60a2013-11-17 09:18:48 +0000933 }
934
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000935 return state->invalidateRegions(R, E, C.blockCount(), LCtx,
Craig Topper0dbb7832014-05-27 02:45:47 +0000936 CausesPointerEscape, nullptr, nullptr,
937 &ITraits);
Jordy Rose722f5582010-08-16 07:51:42 +0000938 }
939
940 // If we have a non-region value by chance, just remove the binding.
941 // FIXME: is this necessary or correct? This handles the non-Region
942 // cases. Is it ever valid to store to these?
Ted Kremenek62698882012-08-22 06:37:46 +0000943 return state->killBinding(*L);
Jordy Rose722f5582010-08-16 07:51:42 +0000944}
945
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000946bool CStringChecker::SummarizeRegion(raw_ostream &os, ASTContext &Ctx,
Jordy Roseb052e8f2010-07-27 01:37:31 +0000947 const MemRegion *MR) {
Ted Kremenek8df44b262011-08-12 20:02:48 +0000948 const TypedValueRegion *TVR = dyn_cast<TypedValueRegion>(MR);
Jordy Roseb052e8f2010-07-27 01:37:31 +0000949
Jordy Roseadd45b72011-08-12 21:41:07 +0000950 switch (MR->getKind()) {
Artem Dergachev73f018e2016-01-13 13:49:29 +0000951 case MemRegion::FunctionCodeRegionKind: {
952 const NamedDecl *FD = cast<FunctionCodeRegion>(MR)->getDecl();
Jordy Roseb052e8f2010-07-27 01:37:31 +0000953 if (FD)
Benjamin Kramerb89514a2011-10-14 18:45:37 +0000954 os << "the address of the function '" << *FD << '\'';
Jordy Roseb052e8f2010-07-27 01:37:31 +0000955 else
956 os << "the address of a function";
957 return true;
958 }
Artem Dergachev73f018e2016-01-13 13:49:29 +0000959 case MemRegion::BlockCodeRegionKind:
Jordy Roseb052e8f2010-07-27 01:37:31 +0000960 os << "block text";
961 return true;
962 case MemRegion::BlockDataRegionKind:
963 os << "a block";
964 return true;
965 case MemRegion::CXXThisRegionKind:
Zhongxing Xu03207162010-11-26 08:52:48 +0000966 case MemRegion::CXXTempObjectRegionKind:
Ted Kremenek8df44b262011-08-12 20:02:48 +0000967 os << "a C++ temp object of type " << TVR->getValueType().getAsString();
Jordy Roseb052e8f2010-07-27 01:37:31 +0000968 return true;
969 case MemRegion::VarRegionKind:
Ted Kremenek8df44b262011-08-12 20:02:48 +0000970 os << "a variable of type" << TVR->getValueType().getAsString();
Jordy Roseb052e8f2010-07-27 01:37:31 +0000971 return true;
972 case MemRegion::FieldRegionKind:
Ted Kremenek8df44b262011-08-12 20:02:48 +0000973 os << "a field of type " << TVR->getValueType().getAsString();
Jordy Roseb052e8f2010-07-27 01:37:31 +0000974 return true;
975 case MemRegion::ObjCIvarRegionKind:
Ted Kremenek8df44b262011-08-12 20:02:48 +0000976 os << "an instance variable of type " << TVR->getValueType().getAsString();
Jordy Roseb052e8f2010-07-27 01:37:31 +0000977 return true;
978 default:
979 return false;
980 }
981}
982
Jordy Rosed5d2e502010-07-08 23:57:29 +0000983//===----------------------------------------------------------------------===//
Ted Kremenekdc891422010-12-01 21:57:22 +0000984// evaluation of individual function calls.
Jordy Rosed5d2e502010-07-08 23:57:29 +0000985//===----------------------------------------------------------------------===//
986
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000987void CStringChecker::evalCopyCommon(CheckerContext &C,
Lenny Maiorani79d74142011-03-31 21:36:53 +0000988 const CallExpr *CE,
Ted Kremenek49b1e382012-01-26 21:29:00 +0000989 ProgramStateRef state,
Jordy Rosed5d2e502010-07-08 23:57:29 +0000990 const Expr *Size, const Expr *Dest,
Lenny Maiorani79d74142011-03-31 21:36:53 +0000991 const Expr *Source, bool Restricted,
992 bool IsMempcpy) const {
Jordy Rosedceb0cf2011-06-20 02:06:40 +0000993 CurrentFunctionDescription = "memory copy function";
994
Jordy Rosed5d2e502010-07-08 23:57:29 +0000995 // See if the size argument is zero.
Ted Kremenek632e3b72012-01-06 22:09:28 +0000996 const LocationContext *LCtx = C.getLocationContext();
997 SVal sizeVal = state->getSVal(Size, LCtx);
Ted Kremenek90af9092010-12-02 07:49:45 +0000998 QualType sizeTy = Size->getType();
Jordy Rosed5d2e502010-07-08 23:57:29 +0000999
Ted Kremenek49b1e382012-01-26 21:29:00 +00001000 ProgramStateRef stateZeroSize, stateNonZeroSize;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001001 std::tie(stateZeroSize, stateNonZeroSize) =
Jordy Rose455bd582011-06-16 05:51:02 +00001002 assumeZero(C, state, sizeVal, sizeTy);
Jordy Rosed5d2e502010-07-08 23:57:29 +00001003
Lenny Maiorani79d74142011-03-31 21:36:53 +00001004 // Get the value of the Dest.
Ted Kremenek632e3b72012-01-06 22:09:28 +00001005 SVal destVal = state->getSVal(Dest, LCtx);
Lenny Maiorani79d74142011-03-31 21:36:53 +00001006
1007 // If the size is zero, there won't be any actual memory access, so
1008 // just bind the return value to the destination buffer and return.
Anna Zaksb3b56bb2012-05-03 18:21:28 +00001009 if (stateZeroSize && !stateNonZeroSize) {
Ted Kremenek632e3b72012-01-06 22:09:28 +00001010 stateZeroSize = stateZeroSize->BindExpr(CE, LCtx, destVal);
Anna Zaksda4c8d62011-10-26 21:06:34 +00001011 C.addTransition(stateZeroSize);
Anna Zaksb3b56bb2012-05-03 18:21:28 +00001012 return;
Lenny Maiorani79d74142011-03-31 21:36:53 +00001013 }
Jordy Rosed5d2e502010-07-08 23:57:29 +00001014
1015 // If the size can be nonzero, we have to check the other arguments.
Ted Kremenek90af9092010-12-02 07:49:45 +00001016 if (stateNonZeroSize) {
Jordy Rose63b84be2011-06-04 00:04:22 +00001017 state = stateNonZeroSize;
Lenny Maiorani79d74142011-03-31 21:36:53 +00001018
1019 // Ensure the destination is not null. If it is NULL there will be a
1020 // NULL pointer dereference.
1021 state = checkNonNull(C, state, Dest, destVal);
1022 if (!state)
1023 return;
1024
1025 // Get the value of the Src.
Ted Kremenek632e3b72012-01-06 22:09:28 +00001026 SVal srcVal = state->getSVal(Source, LCtx);
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001027
Lenny Maiorani79d74142011-03-31 21:36:53 +00001028 // Ensure the source is not null. If it is NULL there will be a
1029 // NULL pointer dereference.
1030 state = checkNonNull(C, state, Source, srcVal);
1031 if (!state)
1032 return;
1033
Jordy Rosefb5e8c22011-06-04 01:50:25 +00001034 // Ensure the accesses are valid and that the buffers do not overlap.
Jordy Rosedceb0cf2011-06-20 02:06:40 +00001035 const char * const writeWarning =
1036 "Memory copy function overflows destination buffer";
Jordy Rose722f5582010-08-16 07:51:42 +00001037 state = CheckBufferAccess(C, state, Size, Dest, Source,
Craig Topper0dbb7832014-05-27 02:45:47 +00001038 writeWarning, /* sourceWarning = */ nullptr);
Jordy Rosed5d2e502010-07-08 23:57:29 +00001039 if (Restricted)
1040 state = CheckOverlap(C, state, Size, Dest, Source);
Jordy Rose722f5582010-08-16 07:51:42 +00001041
Jordy Rosefb5e8c22011-06-04 01:50:25 +00001042 if (!state)
1043 return;
Lenny Maiorani79d74142011-03-31 21:36:53 +00001044
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001045 // If this is mempcpy, get the byte after the last byte copied and
Jordy Rosefb5e8c22011-06-04 01:50:25 +00001046 // bind the expr.
1047 if (IsMempcpy) {
David Blaikie2fdacbc2013-02-20 05:52:05 +00001048 loc::MemRegionVal destRegVal = destVal.castAs<loc::MemRegionVal>();
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001049
Jordy Rosefb5e8c22011-06-04 01:50:25 +00001050 // Get the length to copy.
David Blaikie05785d12013-02-20 22:23:23 +00001051 if (Optional<NonLoc> lenValNonLoc = sizeVal.getAs<NonLoc>()) {
Jordy Rosefb5e8c22011-06-04 01:50:25 +00001052 // Get the byte after the last byte copied.
Anna Zaks2d2f1372014-10-03 21:48:54 +00001053 SValBuilder &SvalBuilder = C.getSValBuilder();
1054 ASTContext &Ctx = SvalBuilder.getContext();
1055 QualType CharPtrTy = Ctx.getPointerType(Ctx.CharTy);
1056 loc::MemRegionVal DestRegCharVal = SvalBuilder.evalCast(destRegVal,
1057 CharPtrTy, Dest->getType()).castAs<loc::MemRegionVal>();
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001058 SVal lastElement = C.getSValBuilder().evalBinOpLN(state, BO_Add,
Anna Zaks2d2f1372014-10-03 21:48:54 +00001059 DestRegCharVal,
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001060 *lenValNonLoc,
Jordy Rosefb5e8c22011-06-04 01:50:25 +00001061 Dest->getType());
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001062
Jordy Rosefb5e8c22011-06-04 01:50:25 +00001063 // The byte after the last byte copied is the return value.
Ted Kremenek632e3b72012-01-06 22:09:28 +00001064 state = state->BindExpr(CE, LCtx, lastElement);
Jordy Rose097c5392011-06-04 01:47:27 +00001065 } else {
Jordy Rosefb5e8c22011-06-04 01:50:25 +00001066 // If we don't know how much we copied, we can at least
1067 // conjure a return value for later.
Craig Topper0dbb7832014-05-27 02:45:47 +00001068 SVal result = C.getSValBuilder().conjureSymbolVal(nullptr, CE, LCtx,
Ted Kremenekd94854a2012-08-22 06:26:15 +00001069 C.blockCount());
Ted Kremenek632e3b72012-01-06 22:09:28 +00001070 state = state->BindExpr(CE, LCtx, result);
Lenny Maiorani79d74142011-03-31 21:36:53 +00001071 }
1072
Jordy Rosefb5e8c22011-06-04 01:50:25 +00001073 } else {
1074 // All other copies return the destination buffer.
1075 // (Well, bcopy() has a void return type, but this won't hurt.)
Ted Kremenek632e3b72012-01-06 22:09:28 +00001076 state = state->BindExpr(CE, LCtx, destVal);
Jordy Rose722f5582010-08-16 07:51:42 +00001077 }
Jordy Rosefb5e8c22011-06-04 01:50:25 +00001078
Anton Yartsev968c60a2013-11-17 09:18:48 +00001079 // Invalidate the destination (regular invalidation without pointer-escaping
1080 // the address of the top-level region).
Jordy Rosefb5e8c22011-06-04 01:50:25 +00001081 // FIXME: Even if we can't perfectly model the copy, we should see if we
1082 // can use LazyCompoundVals to copy the source values into the destination.
1083 // This would probably remove any existing bindings past the end of the
1084 // copied region, but that's still an improvement over blank invalidation.
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001085 state = InvalidateBuffer(C, state, Dest, C.getSVal(Dest),
Devin Coughlin0da2e932015-09-24 16:52:56 +00001086 /*IsSourceBuffer*/false, Size);
Anton Yartsev968c60a2013-11-17 09:18:48 +00001087
1088 // Invalidate the source (const-invalidation without const-pointer-escaping
1089 // the address of the top-level region).
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001090 state = InvalidateBuffer(C, state, Source, C.getSVal(Source),
Devin Coughlin0da2e932015-09-24 16:52:56 +00001091 /*IsSourceBuffer*/true, nullptr);
Anton Yartsev968c60a2013-11-17 09:18:48 +00001092
Anna Zaksda4c8d62011-10-26 21:06:34 +00001093 C.addTransition(state);
Jordy Rosed5d2e502010-07-08 23:57:29 +00001094 }
1095}
1096
1097
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00001098void CStringChecker::evalMemcpy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaksb508d292012-04-10 23:41:11 +00001099 if (CE->getNumArgs() < 3)
1100 return;
1101
Jordy Rose134a2362010-07-06 23:11:01 +00001102 // void *memcpy(void *restrict dst, const void *restrict src, size_t n);
Jordy Rose134a2362010-07-06 23:11:01 +00001103 // The return value is the address of the destination buffer.
Jordy Rosed5d2e502010-07-08 23:57:29 +00001104 const Expr *Dest = CE->getArg(0);
Ted Kremenek49b1e382012-01-26 21:29:00 +00001105 ProgramStateRef state = C.getState();
Jordy Rose097c5392011-06-04 01:47:27 +00001106
Lenny Maiorani79d74142011-03-31 21:36:53 +00001107 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1), true);
1108}
1109
1110void CStringChecker::evalMempcpy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaksb508d292012-04-10 23:41:11 +00001111 if (CE->getNumArgs() < 3)
1112 return;
1113
Lenny Maiorani79d74142011-03-31 21:36:53 +00001114 // void *mempcpy(void *restrict dst, const void *restrict src, size_t n);
1115 // The return value is a pointer to the byte following the last written byte.
1116 const Expr *Dest = CE->getArg(0);
Ted Kremenek49b1e382012-01-26 21:29:00 +00001117 ProgramStateRef state = C.getState();
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001118
Lenny Maiorani79d74142011-03-31 21:36:53 +00001119 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1), true, true);
Jordy Rose134a2362010-07-06 23:11:01 +00001120}
1121
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00001122void CStringChecker::evalMemmove(CheckerContext &C, const CallExpr *CE) const {
Anna Zaksb508d292012-04-10 23:41:11 +00001123 if (CE->getNumArgs() < 3)
1124 return;
1125
Jordy Rosed5d2e502010-07-08 23:57:29 +00001126 // void *memmove(void *dst, const void *src, size_t n);
1127 // The return value is the address of the destination buffer.
1128 const Expr *Dest = CE->getArg(0);
Ted Kremenek49b1e382012-01-26 21:29:00 +00001129 ProgramStateRef state = C.getState();
Jordy Rose097c5392011-06-04 01:47:27 +00001130
Lenny Maiorani79d74142011-03-31 21:36:53 +00001131 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1));
Jordy Rosed5d2e502010-07-08 23:57:29 +00001132}
1133
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00001134void CStringChecker::evalBcopy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaksb508d292012-04-10 23:41:11 +00001135 if (CE->getNumArgs() < 3)
1136 return;
1137
Jordy Rosed5d2e502010-07-08 23:57:29 +00001138 // void bcopy(const void *src, void *dst, size_t n);
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001139 evalCopyCommon(C, CE, C.getState(),
Lenny Maiorani79d74142011-03-31 21:36:53 +00001140 CE->getArg(2), CE->getArg(1), CE->getArg(0));
Jordy Rosed5d2e502010-07-08 23:57:29 +00001141}
1142
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00001143void CStringChecker::evalMemcmp(CheckerContext &C, const CallExpr *CE) const {
Anna Zaksb508d292012-04-10 23:41:11 +00001144 if (CE->getNumArgs() < 3)
1145 return;
1146
Jordy Rose65136fb2010-07-07 08:15:01 +00001147 // int memcmp(const void *s1, const void *s2, size_t n);
Jordy Rosedceb0cf2011-06-20 02:06:40 +00001148 CurrentFunctionDescription = "memory comparison function";
1149
Jordy Rose65136fb2010-07-07 08:15:01 +00001150 const Expr *Left = CE->getArg(0);
1151 const Expr *Right = CE->getArg(1);
1152 const Expr *Size = CE->getArg(2);
1153
Ted Kremenek49b1e382012-01-26 21:29:00 +00001154 ProgramStateRef state = C.getState();
Ted Kremenek90af9092010-12-02 07:49:45 +00001155 SValBuilder &svalBuilder = C.getSValBuilder();
Jordy Rose65136fb2010-07-07 08:15:01 +00001156
Jordy Rosed5d2e502010-07-08 23:57:29 +00001157 // See if the size argument is zero.
Ted Kremenek632e3b72012-01-06 22:09:28 +00001158 const LocationContext *LCtx = C.getLocationContext();
1159 SVal sizeVal = state->getSVal(Size, LCtx);
Ted Kremenek90af9092010-12-02 07:49:45 +00001160 QualType sizeTy = Size->getType();
Jordy Rose65136fb2010-07-07 08:15:01 +00001161
Ted Kremenek49b1e382012-01-26 21:29:00 +00001162 ProgramStateRef stateZeroSize, stateNonZeroSize;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001163 std::tie(stateZeroSize, stateNonZeroSize) =
Ted Kremenek90af9092010-12-02 07:49:45 +00001164 assumeZero(C, state, sizeVal, sizeTy);
Jordy Rose65136fb2010-07-07 08:15:01 +00001165
Jordy Rosed5d2e502010-07-08 23:57:29 +00001166 // If the size can be zero, the result will be 0 in that case, and we don't
1167 // have to check either of the buffers.
Ted Kremenek90af9092010-12-02 07:49:45 +00001168 if (stateZeroSize) {
1169 state = stateZeroSize;
Ted Kremenek632e3b72012-01-06 22:09:28 +00001170 state = state->BindExpr(CE, LCtx,
1171 svalBuilder.makeZeroVal(CE->getType()));
Anna Zaksda4c8d62011-10-26 21:06:34 +00001172 C.addTransition(state);
Jordy Rose65136fb2010-07-07 08:15:01 +00001173 }
1174
Jordy Rosed5d2e502010-07-08 23:57:29 +00001175 // If the size can be nonzero, we have to check the other arguments.
Ted Kremenek90af9092010-12-02 07:49:45 +00001176 if (stateNonZeroSize) {
1177 state = stateNonZeroSize;
Jordy Rosed5d2e502010-07-08 23:57:29 +00001178 // If we know the two buffers are the same, we know the result is 0.
1179 // First, get the two buffers' addresses. Another checker will have already
1180 // made sure they're not undefined.
Ted Kremenek632e3b72012-01-06 22:09:28 +00001181 DefinedOrUnknownSVal LV =
David Blaikie2fdacbc2013-02-20 05:52:05 +00001182 state->getSVal(Left, LCtx).castAs<DefinedOrUnknownSVal>();
Ted Kremenek632e3b72012-01-06 22:09:28 +00001183 DefinedOrUnknownSVal RV =
David Blaikie2fdacbc2013-02-20 05:52:05 +00001184 state->getSVal(Right, LCtx).castAs<DefinedOrUnknownSVal>();
Jordy Rose65136fb2010-07-07 08:15:01 +00001185
Jordy Rosed5d2e502010-07-08 23:57:29 +00001186 // See if they are the same.
Ted Kremenek90af9092010-12-02 07:49:45 +00001187 DefinedOrUnknownSVal SameBuf = svalBuilder.evalEQ(state, LV, RV);
Ted Kremenek49b1e382012-01-26 21:29:00 +00001188 ProgramStateRef StSameBuf, StNotSameBuf;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001189 std::tie(StSameBuf, StNotSameBuf) = state->assume(SameBuf);
Jordy Rosed5d2e502010-07-08 23:57:29 +00001190
Jordy Rose455bd582011-06-16 05:51:02 +00001191 // If the two arguments might be the same buffer, we know the result is 0,
Jordy Rosed5d2e502010-07-08 23:57:29 +00001192 // and we only need to check one size.
1193 if (StSameBuf) {
1194 state = StSameBuf;
1195 state = CheckBufferAccess(C, state, Size, Left);
1196 if (state) {
Ted Kremenek632e3b72012-01-06 22:09:28 +00001197 state = StSameBuf->BindExpr(CE, LCtx,
1198 svalBuilder.makeZeroVal(CE->getType()));
Anna Zaksda4c8d62011-10-26 21:06:34 +00001199 C.addTransition(state);
Jordy Rosed5d2e502010-07-08 23:57:29 +00001200 }
1201 }
1202
1203 // If the two arguments might be different buffers, we have to check the
1204 // size of both of them.
1205 if (StNotSameBuf) {
1206 state = StNotSameBuf;
1207 state = CheckBufferAccess(C, state, Size, Left, Right);
1208 if (state) {
1209 // The return value is the comparison result, which we don't know.
Craig Topper0dbb7832014-05-27 02:45:47 +00001210 SVal CmpV = svalBuilder.conjureSymbolVal(nullptr, CE, LCtx,
1211 C.blockCount());
Ted Kremenek632e3b72012-01-06 22:09:28 +00001212 state = state->BindExpr(CE, LCtx, CmpV);
Anna Zaksda4c8d62011-10-26 21:06:34 +00001213 C.addTransition(state);
Jordy Rosed5d2e502010-07-08 23:57:29 +00001214 }
1215 }
1216 }
Jordy Rose65136fb2010-07-07 08:15:01 +00001217}
1218
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00001219void CStringChecker::evalstrLength(CheckerContext &C,
1220 const CallExpr *CE) const {
Anna Zaksb508d292012-04-10 23:41:11 +00001221 if (CE->getNumArgs() < 1)
1222 return;
1223
Jordy Roseb052e8f2010-07-27 01:37:31 +00001224 // size_t strlen(const char *s);
Ted Kremenek280a01f2011-02-22 04:55:05 +00001225 evalstrLengthCommon(C, CE, /* IsStrnlen = */ false);
1226}
1227
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00001228void CStringChecker::evalstrnLength(CheckerContext &C,
1229 const CallExpr *CE) const {
Anna Zaksb508d292012-04-10 23:41:11 +00001230 if (CE->getNumArgs() < 2)
1231 return;
1232
Ted Kremenek280a01f2011-02-22 04:55:05 +00001233 // size_t strnlen(const char *s, size_t maxlen);
1234 evalstrLengthCommon(C, CE, /* IsStrnlen = */ true);
1235}
1236
1237void CStringChecker::evalstrLengthCommon(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00001238 bool IsStrnlen) const {
Jordy Rosedceb0cf2011-06-20 02:06:40 +00001239 CurrentFunctionDescription = "string length function";
Ted Kremenek49b1e382012-01-26 21:29:00 +00001240 ProgramStateRef state = C.getState();
Ted Kremenek632e3b72012-01-06 22:09:28 +00001241 const LocationContext *LCtx = C.getLocationContext();
Jordy Rosed3592892011-06-14 01:15:31 +00001242
1243 if (IsStrnlen) {
1244 const Expr *maxlenExpr = CE->getArg(1);
Ted Kremenek632e3b72012-01-06 22:09:28 +00001245 SVal maxlenVal = state->getSVal(maxlenExpr, LCtx);
Jordy Rosed3592892011-06-14 01:15:31 +00001246
Ted Kremenek49b1e382012-01-26 21:29:00 +00001247 ProgramStateRef stateZeroSize, stateNonZeroSize;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001248 std::tie(stateZeroSize, stateNonZeroSize) =
Jordy Rosed3592892011-06-14 01:15:31 +00001249 assumeZero(C, state, maxlenVal, maxlenExpr->getType());
1250
1251 // If the size can be zero, the result will be 0 in that case, and we don't
1252 // have to check the string itself.
1253 if (stateZeroSize) {
1254 SVal zero = C.getSValBuilder().makeZeroVal(CE->getType());
Ted Kremenek632e3b72012-01-06 22:09:28 +00001255 stateZeroSize = stateZeroSize->BindExpr(CE, LCtx, zero);
Anna Zaksda4c8d62011-10-26 21:06:34 +00001256 C.addTransition(stateZeroSize);
Jordy Rosed3592892011-06-14 01:15:31 +00001257 }
1258
1259 // If the size is GUARANTEED to be zero, we're done!
1260 if (!stateNonZeroSize)
1261 return;
1262
1263 // Otherwise, record the assumption that the size is nonzero.
1264 state = stateNonZeroSize;
1265 }
1266
1267 // Check that the string argument is non-null.
Jordy Roseb052e8f2010-07-27 01:37:31 +00001268 const Expr *Arg = CE->getArg(0);
Ted Kremenek632e3b72012-01-06 22:09:28 +00001269 SVal ArgVal = state->getSVal(Arg, LCtx);
Jordy Roseb052e8f2010-07-27 01:37:31 +00001270
Ted Kremenek90af9092010-12-02 07:49:45 +00001271 state = checkNonNull(C, state, Arg, ArgVal);
Jordy Roseb052e8f2010-07-27 01:37:31 +00001272
Jordy Rose45d8c122011-06-14 01:26:48 +00001273 if (!state)
1274 return;
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001275
Jordy Rose45d8c122011-06-14 01:26:48 +00001276 SVal strLength = getCStringLength(C, state, Arg, ArgVal);
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001277
Jordy Rose45d8c122011-06-14 01:26:48 +00001278 // If the argument isn't a valid C string, there's no valid state to
1279 // transition to.
1280 if (strLength.isUndef())
1281 return;
Jordy Rosed3592892011-06-14 01:15:31 +00001282
Jordy Rose45d8c122011-06-14 01:26:48 +00001283 DefinedOrUnknownSVal result = UnknownVal();
Jordy Rosed3592892011-06-14 01:15:31 +00001284
Jordy Rose45d8c122011-06-14 01:26:48 +00001285 // If the check is for strnlen() then bind the return value to no more than
1286 // the maxlen value.
1287 if (IsStrnlen) {
Jordy Rose0585a612011-06-16 05:56:50 +00001288 QualType cmpTy = C.getSValBuilder().getConditionType();
Jordy Rosed3592892011-06-14 01:15:31 +00001289
Jordy Rose45d8c122011-06-14 01:26:48 +00001290 // It's a little unfortunate to be getting this again,
1291 // but it's not that expensive...
1292 const Expr *maxlenExpr = CE->getArg(1);
Ted Kremenek632e3b72012-01-06 22:09:28 +00001293 SVal maxlenVal = state->getSVal(maxlenExpr, LCtx);
Ted Kremenek280a01f2011-02-22 04:55:05 +00001294
David Blaikie05785d12013-02-20 22:23:23 +00001295 Optional<NonLoc> strLengthNL = strLength.getAs<NonLoc>();
1296 Optional<NonLoc> maxlenValNL = maxlenVal.getAs<NonLoc>();
Ted Kremenek280a01f2011-02-22 04:55:05 +00001297
Jordy Rose45d8c122011-06-14 01:26:48 +00001298 if (strLengthNL && maxlenValNL) {
Ted Kremenek49b1e382012-01-26 21:29:00 +00001299 ProgramStateRef stateStringTooLong, stateStringNotTooLong;
Jordy Rosed3592892011-06-14 01:15:31 +00001300
Jordy Rose45d8c122011-06-14 01:26:48 +00001301 // Check if the strLength is greater than the maxlen.
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001302 std::tie(stateStringTooLong, stateStringNotTooLong) = state->assume(
1303 C.getSValBuilder()
1304 .evalBinOpNN(state, BO_GT, *strLengthNL, *maxlenValNL, cmpTy)
1305 .castAs<DefinedOrUnknownSVal>());
Jordy Rosed3592892011-06-14 01:15:31 +00001306
Jordy Rose45d8c122011-06-14 01:26:48 +00001307 if (stateStringTooLong && !stateStringNotTooLong) {
1308 // If the string is longer than maxlen, return maxlen.
1309 result = *maxlenValNL;
1310 } else if (stateStringNotTooLong && !stateStringTooLong) {
1311 // If the string is shorter than maxlen, return its length.
1312 result = *strLengthNL;
Ted Kremenek280a01f2011-02-22 04:55:05 +00001313 }
1314 }
1315
Jordy Rose45d8c122011-06-14 01:26:48 +00001316 if (result.isUnknown()) {
1317 // If we don't have enough information for a comparison, there's
1318 // no guarantee the full string length will actually be returned.
1319 // All we know is the return value is the min of the string length
1320 // and the limit. This is better than nothing.
Craig Topper0dbb7832014-05-27 02:45:47 +00001321 result = C.getSValBuilder().conjureSymbolVal(nullptr, CE, LCtx,
1322 C.blockCount());
David Blaikie2fdacbc2013-02-20 05:52:05 +00001323 NonLoc resultNL = result.castAs<NonLoc>();
Jordy Rose45d8c122011-06-14 01:26:48 +00001324
1325 if (strLengthNL) {
David Blaikie2fdacbc2013-02-20 05:52:05 +00001326 state = state->assume(C.getSValBuilder().evalBinOpNN(
1327 state, BO_LE, resultNL, *strLengthNL, cmpTy)
1328 .castAs<DefinedOrUnknownSVal>(), true);
Jordy Rose45d8c122011-06-14 01:26:48 +00001329 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001330
Jordy Rose45d8c122011-06-14 01:26:48 +00001331 if (maxlenValNL) {
David Blaikie2fdacbc2013-02-20 05:52:05 +00001332 state = state->assume(C.getSValBuilder().evalBinOpNN(
1333 state, BO_LE, resultNL, *maxlenValNL, cmpTy)
1334 .castAs<DefinedOrUnknownSVal>(), true);
Jordy Rose45d8c122011-06-14 01:26:48 +00001335 }
1336 }
1337
1338 } else {
1339 // This is a plain strlen(), not strnlen().
David Blaikie2fdacbc2013-02-20 05:52:05 +00001340 result = strLength.castAs<DefinedOrUnknownSVal>();
Jordy Rose45d8c122011-06-14 01:26:48 +00001341
1342 // If we don't know the length of the string, conjure a return
1343 // value, so it can be used in constraints, at least.
1344 if (result.isUnknown()) {
Craig Topper0dbb7832014-05-27 02:45:47 +00001345 result = C.getSValBuilder().conjureSymbolVal(nullptr, CE, LCtx,
1346 C.blockCount());
Jordy Rose45d8c122011-06-14 01:26:48 +00001347 }
Jordy Roseb052e8f2010-07-27 01:37:31 +00001348 }
Jordy Rose45d8c122011-06-14 01:26:48 +00001349
1350 // Bind the return value.
1351 assert(!result.isUnknown() && "Should have conjured a value by now");
Ted Kremenek632e3b72012-01-06 22:09:28 +00001352 state = state->BindExpr(CE, LCtx, result);
Anna Zaksda4c8d62011-10-26 21:06:34 +00001353 C.addTransition(state);
Jordy Roseb052e8f2010-07-27 01:37:31 +00001354}
1355
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00001356void CStringChecker::evalStrcpy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaksb508d292012-04-10 23:41:11 +00001357 if (CE->getNumArgs() < 2)
1358 return;
1359
Jordy Rose722f5582010-08-16 07:51:42 +00001360 // char *strcpy(char *restrict dst, const char *restrict src);
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001361 evalStrcpyCommon(C, CE,
1362 /* returnEnd = */ false,
Lenny Maiorani467dbd52011-04-09 15:12:58 +00001363 /* isBounded = */ false,
1364 /* isAppending = */ false);
Ted Kremenekfb1a79a2011-02-22 04:58:34 +00001365}
1366
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00001367void CStringChecker::evalStrncpy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaksb508d292012-04-10 23:41:11 +00001368 if (CE->getNumArgs() < 3)
1369 return;
1370
Jordy Rose4451cd42011-06-04 00:05:23 +00001371 // char *strncpy(char *restrict dst, const char *restrict src, size_t n);
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001372 evalStrcpyCommon(C, CE,
1373 /* returnEnd = */ false,
Lenny Maiorani467dbd52011-04-09 15:12:58 +00001374 /* isBounded = */ true,
1375 /* isAppending = */ false);
Jordy Rose722f5582010-08-16 07:51:42 +00001376}
1377
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00001378void CStringChecker::evalStpcpy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaksb508d292012-04-10 23:41:11 +00001379 if (CE->getNumArgs() < 2)
1380 return;
1381
Jordy Rose722f5582010-08-16 07:51:42 +00001382 // char *stpcpy(char *restrict dst, const char *restrict src);
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001383 evalStrcpyCommon(C, CE,
1384 /* returnEnd = */ true,
Lenny Maiorani467dbd52011-04-09 15:12:58 +00001385 /* isBounded = */ false,
1386 /* isAppending = */ false);
1387}
1388
1389void CStringChecker::evalStrcat(CheckerContext &C, const CallExpr *CE) const {
Anna Zaksb508d292012-04-10 23:41:11 +00001390 if (CE->getNumArgs() < 2)
1391 return;
1392
Lenny Maiorani467dbd52011-04-09 15:12:58 +00001393 //char *strcat(char *restrict s1, const char *restrict s2);
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001394 evalStrcpyCommon(C, CE,
1395 /* returnEnd = */ false,
Lenny Maiorani467dbd52011-04-09 15:12:58 +00001396 /* isBounded = */ false,
1397 /* isAppending = */ true);
1398}
1399
1400void CStringChecker::evalStrncat(CheckerContext &C, const CallExpr *CE) const {
Anna Zaksb508d292012-04-10 23:41:11 +00001401 if (CE->getNumArgs() < 3)
1402 return;
1403
Lenny Maiorani467dbd52011-04-09 15:12:58 +00001404 //char *strncat(char *restrict s1, const char *restrict s2, size_t n);
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001405 evalStrcpyCommon(C, CE,
1406 /* returnEnd = */ false,
Lenny Maiorani467dbd52011-04-09 15:12:58 +00001407 /* isBounded = */ true,
1408 /* isAppending = */ true);
Jordy Rose722f5582010-08-16 07:51:42 +00001409}
1410
Ted Kremenekdc891422010-12-01 21:57:22 +00001411void CStringChecker::evalStrcpyCommon(CheckerContext &C, const CallExpr *CE,
Lenny Maiorani467dbd52011-04-09 15:12:58 +00001412 bool returnEnd, bool isBounded,
1413 bool isAppending) const {
Jordy Rosedceb0cf2011-06-20 02:06:40 +00001414 CurrentFunctionDescription = "string copy function";
Ted Kremenek49b1e382012-01-26 21:29:00 +00001415 ProgramStateRef state = C.getState();
Ted Kremenek632e3b72012-01-06 22:09:28 +00001416 const LocationContext *LCtx = C.getLocationContext();
Jordy Rose722f5582010-08-16 07:51:42 +00001417
Lenny Maiorani467dbd52011-04-09 15:12:58 +00001418 // Check that the destination is non-null.
Jordy Rose722f5582010-08-16 07:51:42 +00001419 const Expr *Dst = CE->getArg(0);
Ted Kremenek632e3b72012-01-06 22:09:28 +00001420 SVal DstVal = state->getSVal(Dst, LCtx);
Jordy Rose722f5582010-08-16 07:51:42 +00001421
Ted Kremenek90af9092010-12-02 07:49:45 +00001422 state = checkNonNull(C, state, Dst, DstVal);
Jordy Rose722f5582010-08-16 07:51:42 +00001423 if (!state)
1424 return;
1425
1426 // Check that the source is non-null.
Ted Kremenek90af9092010-12-02 07:49:45 +00001427 const Expr *srcExpr = CE->getArg(1);
Ted Kremenek632e3b72012-01-06 22:09:28 +00001428 SVal srcVal = state->getSVal(srcExpr, LCtx);
Ted Kremenek90af9092010-12-02 07:49:45 +00001429 state = checkNonNull(C, state, srcExpr, srcVal);
Jordy Rose722f5582010-08-16 07:51:42 +00001430 if (!state)
1431 return;
1432
1433 // Get the string length of the source.
Ted Kremenek90af9092010-12-02 07:49:45 +00001434 SVal strLength = getCStringLength(C, state, srcExpr, srcVal);
Jordy Rose722f5582010-08-16 07:51:42 +00001435
1436 // If the source isn't a valid C string, give up.
Ted Kremenek90af9092010-12-02 07:49:45 +00001437 if (strLength.isUndef())
Jordy Rose722f5582010-08-16 07:51:42 +00001438 return;
1439
Jordy Rose634c12d2011-06-15 05:52:56 +00001440 SValBuilder &svalBuilder = C.getSValBuilder();
1441 QualType cmpTy = svalBuilder.getConditionType();
Jordy Roseb41f7c52011-06-20 21:55:40 +00001442 QualType sizeTy = svalBuilder.getContext().getSizeType();
Jordy Rose634c12d2011-06-15 05:52:56 +00001443
Jordy Roseb41f7c52011-06-20 21:55:40 +00001444 // These two values allow checking two kinds of errors:
1445 // - actual overflows caused by a source that doesn't fit in the destination
1446 // - potential overflows caused by a bound that could exceed the destination
Jordy Rose634c12d2011-06-15 05:52:56 +00001447 SVal amountCopied = UnknownVal();
Jordy Roseb41f7c52011-06-20 21:55:40 +00001448 SVal maxLastElementIndex = UnknownVal();
Craig Topper0dbb7832014-05-27 02:45:47 +00001449 const char *boundWarning = nullptr;
Jordy Rose634c12d2011-06-15 05:52:56 +00001450
Lenny Maiorani467dbd52011-04-09 15:12:58 +00001451 // If the function is strncpy, strncat, etc... it is bounded.
1452 if (isBounded) {
1453 // Get the max number of characters to copy.
Ted Kremenekfb1a79a2011-02-22 04:58:34 +00001454 const Expr *lenExpr = CE->getArg(2);
Ted Kremenek632e3b72012-01-06 22:09:28 +00001455 SVal lenVal = state->getSVal(lenExpr, LCtx);
Ted Kremenekfb1a79a2011-02-22 04:58:34 +00001456
Jordy Rose634c12d2011-06-15 05:52:56 +00001457 // Protect against misdeclared strncpy().
Jordy Roseb41f7c52011-06-20 21:55:40 +00001458 lenVal = svalBuilder.evalCast(lenVal, sizeTy, lenExpr->getType());
Jordy Rose634c12d2011-06-15 05:52:56 +00001459
David Blaikie05785d12013-02-20 22:23:23 +00001460 Optional<NonLoc> strLengthNL = strLength.getAs<NonLoc>();
1461 Optional<NonLoc> lenValNL = lenVal.getAs<NonLoc>();
Ted Kremenekfb1a79a2011-02-22 04:58:34 +00001462
Jordy Rose634c12d2011-06-15 05:52:56 +00001463 // If we know both values, we might be able to figure out how much
1464 // we're copying.
1465 if (strLengthNL && lenValNL) {
Ted Kremenek49b1e382012-01-26 21:29:00 +00001466 ProgramStateRef stateSourceTooLong, stateSourceNotTooLong;
Ted Kremenekfb1a79a2011-02-22 04:58:34 +00001467
Jordy Rose634c12d2011-06-15 05:52:56 +00001468 // Check if the max number to copy is less than the length of the src.
Jordy Roseb41f7c52011-06-20 21:55:40 +00001469 // If the bound is equal to the source length, strncpy won't null-
1470 // terminate the result!
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001471 std::tie(stateSourceTooLong, stateSourceNotTooLong) = state->assume(
David Blaikie2fdacbc2013-02-20 05:52:05 +00001472 svalBuilder.evalBinOpNN(state, BO_GE, *strLengthNL, *lenValNL, cmpTy)
1473 .castAs<DefinedOrUnknownSVal>());
Jordy Rose634c12d2011-06-15 05:52:56 +00001474
1475 if (stateSourceTooLong && !stateSourceNotTooLong) {
1476 // Max number to copy is less than the length of the src, so the actual
1477 // strLength copied is the max number arg.
1478 state = stateSourceTooLong;
1479 amountCopied = lenVal;
1480
1481 } else if (!stateSourceTooLong && stateSourceNotTooLong) {
1482 // The source buffer entirely fits in the bound.
1483 state = stateSourceNotTooLong;
1484 amountCopied = strLength;
1485 }
1486 }
1487
Jordy Rose328deee2011-06-20 03:49:16 +00001488 // We still want to know if the bound is known to be too large.
Jordy Roseb41f7c52011-06-20 21:55:40 +00001489 if (lenValNL) {
1490 if (isAppending) {
1491 // For strncat, the check is strlen(dst) + lenVal < sizeof(dst)
1492
1493 // Get the string length of the destination. If the destination is
1494 // memory that can't have a string length, we shouldn't be copying
1495 // into it anyway.
1496 SVal dstStrLength = getCStringLength(C, state, Dst, DstVal);
1497 if (dstStrLength.isUndef())
1498 return;
1499
David Blaikie05785d12013-02-20 22:23:23 +00001500 if (Optional<NonLoc> dstStrLengthNL = dstStrLength.getAs<NonLoc>()) {
Jordy Roseb41f7c52011-06-20 21:55:40 +00001501 maxLastElementIndex = svalBuilder.evalBinOpNN(state, BO_Add,
1502 *lenValNL,
1503 *dstStrLengthNL,
1504 sizeTy);
1505 boundWarning = "Size argument is greater than the free space in the "
1506 "destination buffer";
1507 }
1508
1509 } else {
1510 // For strncpy, this is just checking that lenVal <= sizeof(dst)
1511 // (Yes, strncpy and strncat differ in how they treat termination.
1512 // strncat ALWAYS terminates, but strncpy doesn't.)
Jordy Rose459d5f62012-05-14 17:58:35 +00001513
1514 // We need a special case for when the copy size is zero, in which
1515 // case strncpy will do no work at all. Our bounds check uses n-1
1516 // as the last element accessed, so n == 0 is problematic.
1517 ProgramStateRef StateZeroSize, StateNonZeroSize;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001518 std::tie(StateZeroSize, StateNonZeroSize) =
Jordy Rose459d5f62012-05-14 17:58:35 +00001519 assumeZero(C, state, *lenValNL, sizeTy);
1520
1521 // If the size is known to be zero, we're done.
1522 if (StateZeroSize && !StateNonZeroSize) {
1523 StateZeroSize = StateZeroSize->BindExpr(CE, LCtx, DstVal);
1524 C.addTransition(StateZeroSize);
1525 return;
1526 }
1527
1528 // Otherwise, go ahead and figure out the last element we'll touch.
1529 // We don't record the non-zero assumption here because we can't
1530 // be sure. We won't warn on a possible zero.
David Blaikie2fdacbc2013-02-20 05:52:05 +00001531 NonLoc one = svalBuilder.makeIntVal(1, sizeTy).castAs<NonLoc>();
Jordy Roseb41f7c52011-06-20 21:55:40 +00001532 maxLastElementIndex = svalBuilder.evalBinOpNN(state, BO_Sub, *lenValNL,
1533 one, sizeTy);
1534 boundWarning = "Size argument is greater than the length of the "
1535 "destination buffer";
1536 }
1537 }
Jordy Rose328deee2011-06-20 03:49:16 +00001538
Jordy Rose634c12d2011-06-15 05:52:56 +00001539 // If we couldn't pin down the copy length, at least bound it.
Jordy Roseb41f7c52011-06-20 21:55:40 +00001540 // FIXME: We should actually run this code path for append as well, but
1541 // right now it creates problems with constraints (since we can end up
1542 // trying to pass constraints from symbol to symbol).
1543 if (amountCopied.isUnknown() && !isAppending) {
Jordy Rose634c12d2011-06-15 05:52:56 +00001544 // Try to get a "hypothetical" string length symbol, which we can later
1545 // set as a real value if that turns out to be the case.
1546 amountCopied = getCStringLength(C, state, lenExpr, srcVal, true);
1547 assert(!amountCopied.isUndef());
1548
David Blaikie05785d12013-02-20 22:23:23 +00001549 if (Optional<NonLoc> amountCopiedNL = amountCopied.getAs<NonLoc>()) {
Jordy Rose634c12d2011-06-15 05:52:56 +00001550 if (lenValNL) {
1551 // amountCopied <= lenVal
1552 SVal copiedLessThanBound = svalBuilder.evalBinOpNN(state, BO_LE,
1553 *amountCopiedNL,
1554 *lenValNL,
1555 cmpTy);
David Blaikie2fdacbc2013-02-20 05:52:05 +00001556 state = state->assume(
1557 copiedLessThanBound.castAs<DefinedOrUnknownSVal>(), true);
Jordy Rose634c12d2011-06-15 05:52:56 +00001558 if (!state)
1559 return;
1560 }
1561
1562 if (strLengthNL) {
1563 // amountCopied <= strlen(source)
1564 SVal copiedLessThanSrc = svalBuilder.evalBinOpNN(state, BO_LE,
1565 *amountCopiedNL,
1566 *strLengthNL,
1567 cmpTy);
David Blaikie2fdacbc2013-02-20 05:52:05 +00001568 state = state->assume(
1569 copiedLessThanSrc.castAs<DefinedOrUnknownSVal>(), true);
Jordy Rose634c12d2011-06-15 05:52:56 +00001570 if (!state)
1571 return;
1572 }
1573 }
1574 }
1575
1576 } else {
1577 // The function isn't bounded. The amount copied should match the length
1578 // of the source buffer.
1579 amountCopied = strLength;
Ted Kremenekfb1a79a2011-02-22 04:58:34 +00001580 }
1581
Jordy Rose634c12d2011-06-15 05:52:56 +00001582 assert(state);
1583
1584 // This represents the number of characters copied into the destination
1585 // buffer. (It may not actually be the strlen if the destination buffer
1586 // is not terminated.)
1587 SVal finalStrLength = UnknownVal();
1588
Lenny Maiorani467dbd52011-04-09 15:12:58 +00001589 // If this is an appending function (strcat, strncat...) then set the
1590 // string length to strlen(src) + strlen(dst) since the buffer will
1591 // ultimately contain both.
1592 if (isAppending) {
Jordy Rose455bd582011-06-16 05:51:02 +00001593 // Get the string length of the destination. If the destination is memory
1594 // that can't have a string length, we shouldn't be copying into it anyway.
Lenny Maiorani467dbd52011-04-09 15:12:58 +00001595 SVal dstStrLength = getCStringLength(C, state, Dst, DstVal);
1596 if (dstStrLength.isUndef())
1597 return;
1598
David Blaikie05785d12013-02-20 22:23:23 +00001599 Optional<NonLoc> srcStrLengthNL = amountCopied.getAs<NonLoc>();
1600 Optional<NonLoc> dstStrLengthNL = dstStrLength.getAs<NonLoc>();
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001601
Jordy Rose634c12d2011-06-15 05:52:56 +00001602 // If we know both string lengths, we might know the final string length.
1603 if (srcStrLengthNL && dstStrLengthNL) {
1604 // Make sure the two lengths together don't overflow a size_t.
1605 state = checkAdditionOverflow(C, state, *srcStrLengthNL, *dstStrLengthNL);
1606 if (!state)
1607 return;
Lenny Maiorani467dbd52011-04-09 15:12:58 +00001608
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001609 finalStrLength = svalBuilder.evalBinOpNN(state, BO_Add, *srcStrLengthNL,
Jordy Rose634c12d2011-06-15 05:52:56 +00001610 *dstStrLengthNL, sizeTy);
1611 }
Lenny Maiorani467dbd52011-04-09 15:12:58 +00001612
Jordy Rose634c12d2011-06-15 05:52:56 +00001613 // If we couldn't get a single value for the final string length,
1614 // we can at least bound it by the individual lengths.
1615 if (finalStrLength.isUnknown()) {
1616 // Try to get a "hypothetical" string length symbol, which we can later
1617 // set as a real value if that turns out to be the case.
1618 finalStrLength = getCStringLength(C, state, CE, DstVal, true);
1619 assert(!finalStrLength.isUndef());
1620
David Blaikie05785d12013-02-20 22:23:23 +00001621 if (Optional<NonLoc> finalStrLengthNL = finalStrLength.getAs<NonLoc>()) {
Jordy Rose634c12d2011-06-15 05:52:56 +00001622 if (srcStrLengthNL) {
1623 // finalStrLength >= srcStrLength
1624 SVal sourceInResult = svalBuilder.evalBinOpNN(state, BO_GE,
1625 *finalStrLengthNL,
1626 *srcStrLengthNL,
1627 cmpTy);
David Blaikie2fdacbc2013-02-20 05:52:05 +00001628 state = state->assume(sourceInResult.castAs<DefinedOrUnknownSVal>(),
Jordy Rose634c12d2011-06-15 05:52:56 +00001629 true);
1630 if (!state)
1631 return;
1632 }
1633
1634 if (dstStrLengthNL) {
1635 // finalStrLength >= dstStrLength
1636 SVal destInResult = svalBuilder.evalBinOpNN(state, BO_GE,
1637 *finalStrLengthNL,
1638 *dstStrLengthNL,
1639 cmpTy);
David Blaikie2fdacbc2013-02-20 05:52:05 +00001640 state =
1641 state->assume(destInResult.castAs<DefinedOrUnknownSVal>(), true);
Jordy Rose634c12d2011-06-15 05:52:56 +00001642 if (!state)
1643 return;
1644 }
1645 }
1646 }
1647
1648 } else {
1649 // Otherwise, this is a copy-over function (strcpy, strncpy, ...), and
1650 // the final string length will match the input string length.
1651 finalStrLength = amountCopied;
Lenny Maiorani467dbd52011-04-09 15:12:58 +00001652 }
1653
Jordy Rose634c12d2011-06-15 05:52:56 +00001654 // The final result of the function will either be a pointer past the last
1655 // copied element, or a pointer to the start of the destination buffer.
Ted Kremenek90af9092010-12-02 07:49:45 +00001656 SVal Result = (returnEnd ? UnknownVal() : DstVal);
Jordy Rose722f5582010-08-16 07:51:42 +00001657
Jordy Rose634c12d2011-06-15 05:52:56 +00001658 assert(state);
1659
Jordy Rose722f5582010-08-16 07:51:42 +00001660 // If the destination is a MemRegion, try to check for a buffer overflow and
1661 // record the new string length.
David Blaikie05785d12013-02-20 22:23:23 +00001662 if (Optional<loc::MemRegionVal> dstRegVal =
David Blaikie2fdacbc2013-02-20 05:52:05 +00001663 DstVal.getAs<loc::MemRegionVal>()) {
Jordy Roseb41f7c52011-06-20 21:55:40 +00001664 QualType ptrTy = Dst->getType();
1665
1666 // If we have an exact value on a bounded copy, use that to check for
1667 // overflows, rather than our estimate about how much is actually copied.
1668 if (boundWarning) {
David Blaikie05785d12013-02-20 22:23:23 +00001669 if (Optional<NonLoc> maxLastNL = maxLastElementIndex.getAs<NonLoc>()) {
Jordy Roseb41f7c52011-06-20 21:55:40 +00001670 SVal maxLastElement = svalBuilder.evalBinOpLN(state, BO_Add, *dstRegVal,
1671 *maxLastNL, ptrTy);
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001672 state = CheckLocation(C, state, CE->getArg(2), maxLastElement,
Jordy Roseb41f7c52011-06-20 21:55:40 +00001673 boundWarning);
1674 if (!state)
1675 return;
1676 }
1677 }
1678
1679 // Then, if the final length is known...
David Blaikie05785d12013-02-20 22:23:23 +00001680 if (Optional<NonLoc> knownStrLength = finalStrLength.getAs<NonLoc>()) {
Jordy Rose634c12d2011-06-15 05:52:56 +00001681 SVal lastElement = svalBuilder.evalBinOpLN(state, BO_Add, *dstRegVal,
Jordy Roseb41f7c52011-06-20 21:55:40 +00001682 *knownStrLength, ptrTy);
Jordy Rose722f5582010-08-16 07:51:42 +00001683
Jordy Roseb41f7c52011-06-20 21:55:40 +00001684 // ...and we haven't checked the bound, we'll check the actual copy.
1685 if (!boundWarning) {
1686 const char * const warningMsg =
1687 "String copy function overflows destination buffer";
1688 state = CheckLocation(C, state, Dst, lastElement, warningMsg);
1689 if (!state)
1690 return;
1691 }
Jordy Rose722f5582010-08-16 07:51:42 +00001692
1693 // If this is a stpcpy-style copy, the last element is the return value.
Ted Kremenek90af9092010-12-02 07:49:45 +00001694 if (returnEnd)
1695 Result = lastElement;
Jordy Rose722f5582010-08-16 07:51:42 +00001696 }
1697
Anton Yartsev968c60a2013-11-17 09:18:48 +00001698 // Invalidate the destination (regular invalidation without pointer-escaping
1699 // the address of the top-level region). This must happen before we set the
1700 // C string length because invalidation will clear the length.
Jordy Rose722f5582010-08-16 07:51:42 +00001701 // FIXME: Even if we can't perfectly model the copy, we should see if we
1702 // can use LazyCompoundVals to copy the source values into the destination.
1703 // This would probably remove any existing bindings past the end of the
1704 // string, but that's still an improvement over blank invalidation.
Anton Yartsev968c60a2013-11-17 09:18:48 +00001705 state = InvalidateBuffer(C, state, Dst, *dstRegVal,
Devin Coughlin0da2e932015-09-24 16:52:56 +00001706 /*IsSourceBuffer*/false, nullptr);
Anton Yartsev968c60a2013-11-17 09:18:48 +00001707
1708 // Invalidate the source (const-invalidation without const-pointer-escaping
1709 // the address of the top-level region).
Devin Coughlin0da2e932015-09-24 16:52:56 +00001710 state = InvalidateBuffer(C, state, srcExpr, srcVal, /*IsSourceBuffer*/true,
1711 nullptr);
Jordy Rose722f5582010-08-16 07:51:42 +00001712
Jordy Rose328deee2011-06-20 03:49:16 +00001713 // Set the C string length of the destination, if we know it.
Jordy Roseb41f7c52011-06-20 21:55:40 +00001714 if (isBounded && !isAppending) {
1715 // strncpy is annoying in that it doesn't guarantee to null-terminate
1716 // the result string. If the original string didn't fit entirely inside
1717 // the bound (including the null-terminator), we don't know how long the
1718 // result is.
1719 if (amountCopied != strLength)
1720 finalStrLength = UnknownVal();
1721 }
1722 state = setCStringLength(state, dstRegVal->getRegion(), finalStrLength);
Jordy Rose722f5582010-08-16 07:51:42 +00001723 }
1724
Jordy Rose634c12d2011-06-15 05:52:56 +00001725 assert(state);
1726
Jordy Rose722f5582010-08-16 07:51:42 +00001727 // If this is a stpcpy-style copy, but we were unable to check for a buffer
1728 // overflow, we still need a result. Conjure a return value.
Ted Kremenek90af9092010-12-02 07:49:45 +00001729 if (returnEnd && Result.isUnknown()) {
Craig Topper0dbb7832014-05-27 02:45:47 +00001730 Result = svalBuilder.conjureSymbolVal(nullptr, CE, LCtx, C.blockCount());
Jordy Rose722f5582010-08-16 07:51:42 +00001731 }
1732
1733 // Set the return value.
Ted Kremenek632e3b72012-01-06 22:09:28 +00001734 state = state->BindExpr(CE, LCtx, Result);
Anna Zaksda4c8d62011-10-26 21:06:34 +00001735 C.addTransition(state);
Jordy Rose722f5582010-08-16 07:51:42 +00001736}
1737
Lenny Maioranif3539ad2011-04-12 17:08:43 +00001738void CStringChecker::evalStrcmp(CheckerContext &C, const CallExpr *CE) const {
Anna Zaksb508d292012-04-10 23:41:11 +00001739 if (CE->getNumArgs() < 2)
1740 return;
1741
Jordy Rosec0263702011-06-16 07:13:34 +00001742 //int strcmp(const char *s1, const char *s2);
Lenny Maiorani4af23c82011-04-28 15:09:11 +00001743 evalStrcmpCommon(C, CE, /* isBounded = */ false, /* ignoreCase = */ false);
Lenny Maioranie553e402011-04-25 22:21:00 +00001744}
Lenny Maioranif3539ad2011-04-12 17:08:43 +00001745
Lenny Maioranie553e402011-04-25 22:21:00 +00001746void CStringChecker::evalStrncmp(CheckerContext &C, const CallExpr *CE) const {
Anna Zaksb508d292012-04-10 23:41:11 +00001747 if (CE->getNumArgs() < 3)
1748 return;
1749
Jordy Rosec0263702011-06-16 07:13:34 +00001750 //int strncmp(const char *s1, const char *s2, size_t n);
Lenny Maiorani4af23c82011-04-28 15:09:11 +00001751 evalStrcmpCommon(C, CE, /* isBounded = */ true, /* ignoreCase = */ false);
1752}
1753
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001754void CStringChecker::evalStrcasecmp(CheckerContext &C,
Lenny Maiorani4af23c82011-04-28 15:09:11 +00001755 const CallExpr *CE) const {
Anna Zaksb508d292012-04-10 23:41:11 +00001756 if (CE->getNumArgs() < 2)
1757 return;
1758
Jordy Rosec0263702011-06-16 07:13:34 +00001759 //int strcasecmp(const char *s1, const char *s2);
Lenny Maiorani4af23c82011-04-28 15:09:11 +00001760 evalStrcmpCommon(C, CE, /* isBounded = */ false, /* ignoreCase = */ true);
Lenny Maioranie553e402011-04-25 22:21:00 +00001761}
1762
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001763void CStringChecker::evalStrncasecmp(CheckerContext &C,
Lenny Maiorani0b510272011-05-02 19:05:49 +00001764 const CallExpr *CE) const {
Anna Zaksb508d292012-04-10 23:41:11 +00001765 if (CE->getNumArgs() < 3)
1766 return;
1767
Jordy Rosec0263702011-06-16 07:13:34 +00001768 //int strncasecmp(const char *s1, const char *s2, size_t n);
Lenny Maiorani0b510272011-05-02 19:05:49 +00001769 evalStrcmpCommon(C, CE, /* isBounded = */ true, /* ignoreCase = */ true);
1770}
1771
Lenny Maioranie553e402011-04-25 22:21:00 +00001772void CStringChecker::evalStrcmpCommon(CheckerContext &C, const CallExpr *CE,
Lenny Maiorani4af23c82011-04-28 15:09:11 +00001773 bool isBounded, bool ignoreCase) const {
Jordy Rosedceb0cf2011-06-20 02:06:40 +00001774 CurrentFunctionDescription = "string comparison function";
Ted Kremenek49b1e382012-01-26 21:29:00 +00001775 ProgramStateRef state = C.getState();
Ted Kremenek632e3b72012-01-06 22:09:28 +00001776 const LocationContext *LCtx = C.getLocationContext();
Lenny Maioranif3539ad2011-04-12 17:08:43 +00001777
1778 // Check that the first string is non-null
1779 const Expr *s1 = CE->getArg(0);
Ted Kremenek632e3b72012-01-06 22:09:28 +00001780 SVal s1Val = state->getSVal(s1, LCtx);
Lenny Maioranif3539ad2011-04-12 17:08:43 +00001781 state = checkNonNull(C, state, s1, s1Val);
1782 if (!state)
1783 return;
1784
1785 // Check that the second string is non-null.
1786 const Expr *s2 = CE->getArg(1);
Ted Kremenek632e3b72012-01-06 22:09:28 +00001787 SVal s2Val = state->getSVal(s2, LCtx);
Lenny Maioranif3539ad2011-04-12 17:08:43 +00001788 state = checkNonNull(C, state, s2, s2Val);
1789 if (!state)
1790 return;
1791
1792 // Get the string length of the first string or give up.
1793 SVal s1Length = getCStringLength(C, state, s1, s1Val);
1794 if (s1Length.isUndef())
1795 return;
1796
1797 // Get the string length of the second string or give up.
1798 SVal s2Length = getCStringLength(C, state, s2, s2Val);
1799 if (s2Length.isUndef())
1800 return;
1801
Jordy Rosec0263702011-06-16 07:13:34 +00001802 // If we know the two buffers are the same, we know the result is 0.
1803 // First, get the two buffers' addresses. Another checker will have already
1804 // made sure they're not undefined.
David Blaikie2fdacbc2013-02-20 05:52:05 +00001805 DefinedOrUnknownSVal LV = s1Val.castAs<DefinedOrUnknownSVal>();
1806 DefinedOrUnknownSVal RV = s2Val.castAs<DefinedOrUnknownSVal>();
Lenny Maioranif3539ad2011-04-12 17:08:43 +00001807
Jordy Rosec0263702011-06-16 07:13:34 +00001808 // See if they are the same.
Lenny Maioranif3539ad2011-04-12 17:08:43 +00001809 SValBuilder &svalBuilder = C.getSValBuilder();
Jordy Rosec0263702011-06-16 07:13:34 +00001810 DefinedOrUnknownSVal SameBuf = svalBuilder.evalEQ(state, LV, RV);
Ted Kremenek49b1e382012-01-26 21:29:00 +00001811 ProgramStateRef StSameBuf, StNotSameBuf;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001812 std::tie(StSameBuf, StNotSameBuf) = state->assume(SameBuf);
Lenny Maioranif3539ad2011-04-12 17:08:43 +00001813
Jordy Rosec0263702011-06-16 07:13:34 +00001814 // If the two arguments might be the same buffer, we know the result is 0,
1815 // and we only need to check one size.
1816 if (StSameBuf) {
Ted Kremenek632e3b72012-01-06 22:09:28 +00001817 StSameBuf = StSameBuf->BindExpr(CE, LCtx,
1818 svalBuilder.makeZeroVal(CE->getType()));
Anna Zaksda4c8d62011-10-26 21:06:34 +00001819 C.addTransition(StSameBuf);
Jordy Rosec0263702011-06-16 07:13:34 +00001820
1821 // If the two arguments are GUARANTEED to be the same, we're done!
1822 if (!StNotSameBuf)
1823 return;
1824 }
1825
1826 assert(StNotSameBuf);
1827 state = StNotSameBuf;
1828
1829 // At this point we can go about comparing the two buffers.
1830 // For now, we only do this if they're both known string literals.
1831
1832 // Attempt to extract string literals from both expressions.
1833 const StringLiteral *s1StrLiteral = getCStringLiteral(C, state, s1, s1Val);
1834 const StringLiteral *s2StrLiteral = getCStringLiteral(C, state, s2, s2Val);
1835 bool canComputeResult = false;
1836
1837 if (s1StrLiteral && s2StrLiteral) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001838 StringRef s1StrRef = s1StrLiteral->getString();
1839 StringRef s2StrRef = s2StrLiteral->getString();
Jordy Rosec0263702011-06-16 07:13:34 +00001840
1841 if (isBounded) {
1842 // Get the max number of characters to compare.
1843 const Expr *lenExpr = CE->getArg(2);
Ted Kremenek632e3b72012-01-06 22:09:28 +00001844 SVal lenVal = state->getSVal(lenExpr, LCtx);
Jordy Rosec0263702011-06-16 07:13:34 +00001845
1846 // If the length is known, we can get the right substrings.
1847 if (const llvm::APSInt *len = svalBuilder.getKnownValue(state, lenVal)) {
1848 // Create substrings of each to compare the prefix.
1849 s1StrRef = s1StrRef.substr(0, (size_t)len->getZExtValue());
1850 s2StrRef = s2StrRef.substr(0, (size_t)len->getZExtValue());
1851 canComputeResult = true;
1852 }
1853 } else {
1854 // This is a normal, unbounded strcmp.
1855 canComputeResult = true;
1856 }
1857
1858 if (canComputeResult) {
1859 // Real strcmp stops at null characters.
1860 size_t s1Term = s1StrRef.find('\0');
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001861 if (s1Term != StringRef::npos)
Jordy Rosec0263702011-06-16 07:13:34 +00001862 s1StrRef = s1StrRef.substr(0, s1Term);
1863
1864 size_t s2Term = s2StrRef.find('\0');
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001865 if (s2Term != StringRef::npos)
Jordy Rosec0263702011-06-16 07:13:34 +00001866 s2StrRef = s2StrRef.substr(0, s2Term);
1867
1868 // Use StringRef's comparison methods to compute the actual result.
1869 int result;
1870
1871 if (ignoreCase) {
1872 // Compare string 1 to string 2 the same way strcasecmp() does.
1873 result = s1StrRef.compare_lower(s2StrRef);
1874 } else {
1875 // Compare string 1 to string 2 the same way strcmp() does.
1876 result = s1StrRef.compare(s2StrRef);
1877 }
1878
1879 // Build the SVal of the comparison and bind the return value.
1880 SVal resultVal = svalBuilder.makeIntVal(result, CE->getType());
Ted Kremenek632e3b72012-01-06 22:09:28 +00001881 state = state->BindExpr(CE, LCtx, resultVal);
Jordy Rosec0263702011-06-16 07:13:34 +00001882 }
1883 }
1884
1885 if (!canComputeResult) {
1886 // Conjure a symbolic value. It's the best we can do.
Craig Topper0dbb7832014-05-27 02:45:47 +00001887 SVal resultVal = svalBuilder.conjureSymbolVal(nullptr, CE, LCtx,
1888 C.blockCount());
Ted Kremenek632e3b72012-01-06 22:09:28 +00001889 state = state->BindExpr(CE, LCtx, resultVal);
Jordy Rosec0263702011-06-16 07:13:34 +00001890 }
1891
1892 // Record this as a possible path.
Anna Zaksda4c8d62011-10-26 21:06:34 +00001893 C.addTransition(state);
Lenny Maioranif3539ad2011-04-12 17:08:43 +00001894}
1895
Jordan Rose6e3cf2b2013-04-22 23:18:42 +00001896void CStringChecker::evalStrsep(CheckerContext &C, const CallExpr *CE) const {
1897 //char *strsep(char **stringp, const char *delim);
1898 if (CE->getNumArgs() < 2)
1899 return;
1900
1901 // Sanity: does the search string parameter match the return type?
1902 const Expr *SearchStrPtr = CE->getArg(0);
1903 QualType CharPtrTy = SearchStrPtr->getType()->getPointeeType();
1904 if (CharPtrTy.isNull() ||
1905 CE->getType().getUnqualifiedType() != CharPtrTy.getUnqualifiedType())
1906 return;
1907
1908 CurrentFunctionDescription = "strsep()";
1909 ProgramStateRef State = C.getState();
1910 const LocationContext *LCtx = C.getLocationContext();
1911
1912 // Check that the search string pointer is non-null (though it may point to
1913 // a null string).
1914 SVal SearchStrVal = State->getSVal(SearchStrPtr, LCtx);
1915 State = checkNonNull(C, State, SearchStrPtr, SearchStrVal);
1916 if (!State)
1917 return;
1918
1919 // Check that the delimiter string is non-null.
1920 const Expr *DelimStr = CE->getArg(1);
1921 SVal DelimStrVal = State->getSVal(DelimStr, LCtx);
1922 State = checkNonNull(C, State, DelimStr, DelimStrVal);
1923 if (!State)
1924 return;
1925
1926 SValBuilder &SVB = C.getSValBuilder();
1927 SVal Result;
1928 if (Optional<Loc> SearchStrLoc = SearchStrVal.getAs<Loc>()) {
1929 // Get the current value of the search string pointer, as a char*.
1930 Result = State->getSVal(*SearchStrLoc, CharPtrTy);
1931
1932 // Invalidate the search string, representing the change of one delimiter
1933 // character to NUL.
Anton Yartsev968c60a2013-11-17 09:18:48 +00001934 State = InvalidateBuffer(C, State, SearchStrPtr, Result,
Devin Coughlin0da2e932015-09-24 16:52:56 +00001935 /*IsSourceBuffer*/false, nullptr);
Jordan Rose6e3cf2b2013-04-22 23:18:42 +00001936
1937 // Overwrite the search string pointer. The new value is either an address
1938 // further along in the same string, or NULL if there are no more tokens.
1939 State = State->bindLoc(*SearchStrLoc,
1940 SVB.conjureSymbolVal(getTag(), CE, LCtx, CharPtrTy,
1941 C.blockCount()));
1942 } else {
1943 assert(SearchStrVal.isUnknown());
1944 // Conjure a symbolic value. It's the best we can do.
Craig Topper0dbb7832014-05-27 02:45:47 +00001945 Result = SVB.conjureSymbolVal(nullptr, CE, LCtx, C.blockCount());
Jordan Rose6e3cf2b2013-04-22 23:18:42 +00001946 }
1947
1948 // Set the return value, and finish.
1949 State = State->BindExpr(CE, LCtx, Result);
1950 C.addTransition(State);
1951}
1952
1953
Jordy Rosed5d2e502010-07-08 23:57:29 +00001954//===----------------------------------------------------------------------===//
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001955// The driver method, and other Checker callbacks.
Jordy Rosed5d2e502010-07-08 23:57:29 +00001956//===----------------------------------------------------------------------===//
Jordy Rose134a2362010-07-06 23:11:01 +00001957
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00001958bool CStringChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
Anna Zaks6348a812012-02-17 22:35:26 +00001959 const FunctionDecl *FDecl = C.getCalleeDecl(CE);
1960
1961 if (!FDecl)
Jordy Rose134a2362010-07-06 23:11:01 +00001962 return false;
Jordy Rose134a2362010-07-06 23:11:01 +00001963
Jordan Rose6e3cf2b2013-04-22 23:18:42 +00001964 // FIXME: Poorly-factored string switches are slow.
Craig Topper0dbb7832014-05-27 02:45:47 +00001965 FnCheck evalFunction = nullptr;
Anna Zaks6348a812012-02-17 22:35:26 +00001966 if (C.isCLibraryFunction(FDecl, "memcpy"))
1967 evalFunction = &CStringChecker::evalMemcpy;
1968 else if (C.isCLibraryFunction(FDecl, "mempcpy"))
1969 evalFunction = &CStringChecker::evalMempcpy;
1970 else if (C.isCLibraryFunction(FDecl, "memcmp"))
1971 evalFunction = &CStringChecker::evalMemcmp;
1972 else if (C.isCLibraryFunction(FDecl, "memmove"))
1973 evalFunction = &CStringChecker::evalMemmove;
1974 else if (C.isCLibraryFunction(FDecl, "strcpy"))
1975 evalFunction = &CStringChecker::evalStrcpy;
1976 else if (C.isCLibraryFunction(FDecl, "strncpy"))
1977 evalFunction = &CStringChecker::evalStrncpy;
1978 else if (C.isCLibraryFunction(FDecl, "stpcpy"))
1979 evalFunction = &CStringChecker::evalStpcpy;
1980 else if (C.isCLibraryFunction(FDecl, "strcat"))
1981 evalFunction = &CStringChecker::evalStrcat;
1982 else if (C.isCLibraryFunction(FDecl, "strncat"))
1983 evalFunction = &CStringChecker::evalStrncat;
1984 else if (C.isCLibraryFunction(FDecl, "strlen"))
1985 evalFunction = &CStringChecker::evalstrLength;
1986 else if (C.isCLibraryFunction(FDecl, "strnlen"))
1987 evalFunction = &CStringChecker::evalstrnLength;
1988 else if (C.isCLibraryFunction(FDecl, "strcmp"))
1989 evalFunction = &CStringChecker::evalStrcmp;
1990 else if (C.isCLibraryFunction(FDecl, "strncmp"))
1991 evalFunction = &CStringChecker::evalStrncmp;
1992 else if (C.isCLibraryFunction(FDecl, "strcasecmp"))
1993 evalFunction = &CStringChecker::evalStrcasecmp;
1994 else if (C.isCLibraryFunction(FDecl, "strncasecmp"))
1995 evalFunction = &CStringChecker::evalStrncasecmp;
Jordan Rose6e3cf2b2013-04-22 23:18:42 +00001996 else if (C.isCLibraryFunction(FDecl, "strsep"))
1997 evalFunction = &CStringChecker::evalStrsep;
Anna Zaks6348a812012-02-17 22:35:26 +00001998 else if (C.isCLibraryFunction(FDecl, "bcopy"))
1999 evalFunction = &CStringChecker::evalBcopy;
2000 else if (C.isCLibraryFunction(FDecl, "bcmp"))
2001 evalFunction = &CStringChecker::evalMemcmp;
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002002
Jordy Rosed5d2e502010-07-08 23:57:29 +00002003 // If the callee isn't a string function, let another checker handle it.
Ted Kremenekdc891422010-12-01 21:57:22 +00002004 if (!evalFunction)
Jordy Rose134a2362010-07-06 23:11:01 +00002005 return false;
2006
Jordy Rosed5d2e502010-07-08 23:57:29 +00002007 // Check and evaluate the call.
Ted Kremenekdc891422010-12-01 21:57:22 +00002008 (this->*evalFunction)(C, CE);
Anna Zakse0c7c272012-02-07 00:56:14 +00002009
2010 // If the evaluate call resulted in no change, chain to the next eval call
2011 // handler.
2012 // Note, the custom CString evaluation calls assume that basic safety
2013 // properties are held. However, if the user chooses to turn off some of these
2014 // checks, we ignore the issues and leave the call evaluation to a generic
2015 // handler.
Alexander Kornienko9c104902015-12-28 13:06:58 +00002016 return C.isDifferent();
Jordy Rose134a2362010-07-06 23:11:01 +00002017}
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002018
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00002019void CStringChecker::checkPreStmt(const DeclStmt *DS, CheckerContext &C) const {
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002020 // Record string length for char a[] = "abc";
Ted Kremenek49b1e382012-01-26 21:29:00 +00002021 ProgramStateRef state = C.getState();
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002022
Aaron Ballman535bbcc2014-03-14 17:01:24 +00002023 for (const auto *I : DS->decls()) {
2024 const VarDecl *D = dyn_cast<VarDecl>(I);
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002025 if (!D)
2026 continue;
2027
2028 // FIXME: Handle array fields of structs.
2029 if (!D->getType()->isArrayType())
2030 continue;
2031
2032 const Expr *Init = D->getInit();
2033 if (!Init)
2034 continue;
2035 if (!isa<StringLiteral>(Init))
2036 continue;
2037
Anna Zaksc9abbe22011-10-26 21:06:44 +00002038 Loc VarLoc = state->getLValue(D, C.getLocationContext());
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002039 const MemRegion *MR = VarLoc.getAsRegion();
2040 if (!MR)
2041 continue;
2042
Ted Kremenek632e3b72012-01-06 22:09:28 +00002043 SVal StrVal = state->getSVal(Init, C.getLocationContext());
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002044 assert(StrVal.isValid() && "Initializer string is unknown or undefined");
David Blaikie2fdacbc2013-02-20 05:52:05 +00002045 DefinedOrUnknownSVal strLength =
2046 getCStringLength(C, state, Init, StrVal).castAs<DefinedOrUnknownSVal>();
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002047
Ted Kremenek90af9092010-12-02 07:49:45 +00002048 state = state->set<CStringLength>(MR, strLength);
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002049 }
2050
Anna Zaksda4c8d62011-10-26 21:06:34 +00002051 C.addTransition(state);
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002052}
2053
Ted Kremenek49b1e382012-01-26 21:29:00 +00002054bool CStringChecker::wantsRegionChangeUpdate(ProgramStateRef state) const {
Jordan Rose0c153cb2012-11-02 01:54:06 +00002055 CStringLengthTy Entries = state->get<CStringLength>();
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002056 return !Entries.isEmpty();
2057}
2058
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002059ProgramStateRef
Ted Kremenek49b1e382012-01-26 21:29:00 +00002060CStringChecker::checkRegionChanges(ProgramStateRef state,
Anna Zaksdc154152012-12-20 00:38:25 +00002061 const InvalidatedSymbols *,
Jordy Rose1fad6632011-08-27 22:51:26 +00002062 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks3d348342012-02-14 21:55:24 +00002063 ArrayRef<const MemRegion *> Regions,
Jordan Rose742920c2012-07-02 19:27:35 +00002064 const CallEvent *Call) const {
Jordan Rose0c153cb2012-11-02 01:54:06 +00002065 CStringLengthTy Entries = state->get<CStringLength>();
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002066 if (Entries.isEmpty())
2067 return state;
2068
2069 llvm::SmallPtrSet<const MemRegion *, 8> Invalidated;
2070 llvm::SmallPtrSet<const MemRegion *, 32> SuperRegions;
2071
2072 // First build sets for the changed regions and their super-regions.
Jordy Rose1fad6632011-08-27 22:51:26 +00002073 for (ArrayRef<const MemRegion *>::iterator
2074 I = Regions.begin(), E = Regions.end(); I != E; ++I) {
2075 const MemRegion *MR = *I;
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002076 Invalidated.insert(MR);
2077
2078 SuperRegions.insert(MR);
2079 while (const SubRegion *SR = dyn_cast<SubRegion>(MR)) {
2080 MR = SR->getSuperRegion();
2081 SuperRegions.insert(MR);
2082 }
2083 }
2084
Jordan Rose0c153cb2012-11-02 01:54:06 +00002085 CStringLengthTy::Factory &F = state->get_context<CStringLength>();
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002086
2087 // Then loop over the entries in the current state.
Jordan Rose0c153cb2012-11-02 01:54:06 +00002088 for (CStringLengthTy::iterator I = Entries.begin(),
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002089 E = Entries.end(); I != E; ++I) {
2090 const MemRegion *MR = I.getKey();
2091
2092 // Is this entry for a super-region of a changed region?
2093 if (SuperRegions.count(MR)) {
Ted Kremenekb3b56c62010-11-24 00:54:37 +00002094 Entries = F.remove(Entries, MR);
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002095 continue;
2096 }
2097
2098 // Is this entry for a sub-region of a changed region?
2099 const MemRegion *Super = MR;
2100 while (const SubRegion *SR = dyn_cast<SubRegion>(Super)) {
2101 Super = SR->getSuperRegion();
2102 if (Invalidated.count(Super)) {
Ted Kremenekb3b56c62010-11-24 00:54:37 +00002103 Entries = F.remove(Entries, MR);
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002104 break;
2105 }
2106 }
2107 }
2108
2109 return state->set<CStringLength>(Entries);
2110}
2111
Ted Kremenek49b1e382012-01-26 21:29:00 +00002112void CStringChecker::checkLiveSymbols(ProgramStateRef state,
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00002113 SymbolReaper &SR) const {
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002114 // Mark all symbols in our string length map as valid.
Jordan Rose0c153cb2012-11-02 01:54:06 +00002115 CStringLengthTy Entries = state->get<CStringLength>();
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002116
Jordan Rose0c153cb2012-11-02 01:54:06 +00002117 for (CStringLengthTy::iterator I = Entries.begin(), E = Entries.end();
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002118 I != E; ++I) {
2119 SVal Len = I.getData();
Jordy Rose634c12d2011-06-15 05:52:56 +00002120
Anna Zaksee1a4352011-12-06 23:12:33 +00002121 for (SymExpr::symbol_iterator si = Len.symbol_begin(),
2122 se = Len.symbol_end(); si != se; ++si)
Jordy Rose634c12d2011-06-15 05:52:56 +00002123 SR.markInUse(*si);
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002124 }
2125}
2126
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00002127void CStringChecker::checkDeadSymbols(SymbolReaper &SR,
2128 CheckerContext &C) const {
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002129 if (!SR.hasDeadSymbols())
2130 return;
2131
Ted Kremenek49b1e382012-01-26 21:29:00 +00002132 ProgramStateRef state = C.getState();
Jordan Rose0c153cb2012-11-02 01:54:06 +00002133 CStringLengthTy Entries = state->get<CStringLength>();
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002134 if (Entries.isEmpty())
2135 return;
2136
Jordan Rose0c153cb2012-11-02 01:54:06 +00002137 CStringLengthTy::Factory &F = state->get_context<CStringLength>();
2138 for (CStringLengthTy::iterator I = Entries.begin(), E = Entries.end();
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002139 I != E; ++I) {
2140 SVal Len = I.getData();
2141 if (SymbolRef Sym = Len.getAsSymbol()) {
2142 if (SR.isDead(Sym))
Ted Kremenekb3b56c62010-11-24 00:54:37 +00002143 Entries = F.remove(Entries, I.getKey());
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002144 }
2145 }
2146
2147 state = state->set<CStringLength>(Entries);
Anna Zaksda4c8d62011-10-26 21:06:34 +00002148 C.addTransition(state);
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002149}
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00002150
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002151#define REGISTER_CHECKER(name) \
2152 void ento::register##name(CheckerManager &mgr) { \
2153 CStringChecker *checker = mgr.registerChecker<CStringChecker>(); \
2154 checker->Filter.Check##name = true; \
2155 checker->Filter.CheckName##name = mgr.getCurrentCheckName(); \
2156 }
Anna Zakse0c7c272012-02-07 00:56:14 +00002157
2158REGISTER_CHECKER(CStringNullArg)
2159REGISTER_CHECKER(CStringOutOfBounds)
2160REGISTER_CHECKER(CStringBufferOverlap)
2161REGISTER_CHECKER(CStringNotNullTerm)
Anna Zakse56167e2012-02-17 22:35:31 +00002162
2163void ento::registerCStringCheckerBasic(CheckerManager &Mgr) {
2164 registerCStringNullArg(Mgr);
2165}