blob: e91a7e16802e7277662383291b58ca8ab2f2200a [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 Kremenek49b1e382012-01-26 21:29:00 +000068 ProgramStateRef
69 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,
95 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
Lenny Maioranif3539ad2011-04-12 17:08:43 +0000140 const StringLiteral *getCStringLiteral(CheckerContext &C,
Ted Kremenek49b1e382012-01-26 21:29:00 +0000141 ProgramStateRef &state,
Lenny Maioranif3539ad2011-04-12 17:08:43 +0000142 const Expr *expr,
143 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,
148 bool IsSourceBuffer);
Jordy Rose722f5582010-08-16 07:51:42 +0000149
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000150 static bool SummarizeRegion(raw_ostream &os, ASTContext &Ctx,
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000151 const MemRegion *MR);
Jordy Roseb052e8f2010-07-27 01:37:31 +0000152
153 // Re-usable checks
Ted Kremenek49b1e382012-01-26 21:29:00 +0000154 ProgramStateRef checkNonNull(CheckerContext &C,
155 ProgramStateRef state,
Ted Kremenek001fd5b2011-08-15 22:09:50 +0000156 const Expr *S,
157 SVal l) const;
Ted Kremenek49b1e382012-01-26 21:29:00 +0000158 ProgramStateRef CheckLocation(CheckerContext &C,
159 ProgramStateRef state,
Ted Kremenek001fd5b2011-08-15 22:09:50 +0000160 const Expr *S,
161 SVal l,
Craig Topper0dbb7832014-05-27 02:45:47 +0000162 const char *message = nullptr) const;
Ted Kremenek49b1e382012-01-26 21:29:00 +0000163 ProgramStateRef CheckBufferAccess(CheckerContext &C,
164 ProgramStateRef state,
Ted Kremenek001fd5b2011-08-15 22:09:50 +0000165 const Expr *Size,
166 const Expr *FirstBuf,
167 const Expr *SecondBuf,
Craig Topper0dbb7832014-05-27 02:45:47 +0000168 const char *firstMessage = nullptr,
169 const char *secondMessage = nullptr,
Ted Kremenek001fd5b2011-08-15 22:09:50 +0000170 bool WarnAboutSize = false) const;
171
Ted Kremenek49b1e382012-01-26 21:29:00 +0000172 ProgramStateRef CheckBufferAccess(CheckerContext &C,
173 ProgramStateRef state,
Ted Kremenek001fd5b2011-08-15 22:09:50 +0000174 const Expr *Size,
175 const Expr *Buf,
Craig Topper0dbb7832014-05-27 02:45:47 +0000176 const char *message = nullptr,
Ted Kremenek001fd5b2011-08-15 22:09:50 +0000177 bool WarnAboutSize = false) const {
Jordy Rosedceb0cf2011-06-20 02:06:40 +0000178 // This is a convenience override.
Craig Topper0dbb7832014-05-27 02:45:47 +0000179 return CheckBufferAccess(C, state, Size, Buf, nullptr, message, nullptr,
Jordy Rose328deee2011-06-20 03:49:16 +0000180 WarnAboutSize);
Jordy Rosedceb0cf2011-06-20 02:06:40 +0000181 }
Ted Kremenek49b1e382012-01-26 21:29:00 +0000182 ProgramStateRef CheckOverlap(CheckerContext &C,
183 ProgramStateRef state,
Ted Kremenek001fd5b2011-08-15 22:09:50 +0000184 const Expr *Size,
185 const Expr *First,
186 const Expr *Second) const;
187 void emitOverlapBug(CheckerContext &C,
Ted Kremenek49b1e382012-01-26 21:29:00 +0000188 ProgramStateRef state,
Ted Kremenek001fd5b2011-08-15 22:09:50 +0000189 const Stmt *First,
190 const Stmt *Second) const;
191
Ted Kremenek49b1e382012-01-26 21:29:00 +0000192 ProgramStateRef checkAdditionOverflow(CheckerContext &C,
193 ProgramStateRef state,
Ted Kremenek001fd5b2011-08-15 22:09:50 +0000194 NonLoc left,
195 NonLoc right) const;
Jordy Rose134a2362010-07-06 23:11:01 +0000196};
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000197
Jordy Rose134a2362010-07-06 23:11:01 +0000198} //end anonymous namespace
199
Jordan Rose0c153cb2012-11-02 01:54:06 +0000200REGISTER_MAP_WITH_PROGRAMSTATE(CStringLength, const MemRegion *, SVal)
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000201
Jordy Rosed5d2e502010-07-08 23:57:29 +0000202//===----------------------------------------------------------------------===//
203// Individual checks and utility methods.
204//===----------------------------------------------------------------------===//
205
Ted Kremenek49b1e382012-01-26 21:29:00 +0000206std::pair<ProgramStateRef , ProgramStateRef >
207CStringChecker::assumeZero(CheckerContext &C, ProgramStateRef state, SVal V,
Jordy Rosed5d2e502010-07-08 23:57:29 +0000208 QualType Ty) {
David Blaikie05785d12013-02-20 22:23:23 +0000209 Optional<DefinedSVal> val = V.getAs<DefinedSVal>();
Ted Kremenek90af9092010-12-02 07:49:45 +0000210 if (!val)
Ted Kremenek49b1e382012-01-26 21:29:00 +0000211 return std::pair<ProgramStateRef , ProgramStateRef >(state, state);
Jordy Rose33c829a2010-07-07 07:48:06 +0000212
Ted Kremenek90af9092010-12-02 07:49:45 +0000213 SValBuilder &svalBuilder = C.getSValBuilder();
214 DefinedOrUnknownSVal zero = svalBuilder.makeZeroVal(Ty);
215 return state->assume(svalBuilder.evalEQ(state, *val, zero));
Jordy Rosed5d2e502010-07-08 23:57:29 +0000216}
Jordy Rose33c829a2010-07-07 07:48:06 +0000217
Ted Kremenek49b1e382012-01-26 21:29:00 +0000218ProgramStateRef CStringChecker::checkNonNull(CheckerContext &C,
219 ProgramStateRef state,
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000220 const Expr *S, SVal l) const {
Jordy Rosed5d2e502010-07-08 23:57:29 +0000221 // If a previous check has failed, propagate the failure.
222 if (!state)
Craig Topper0dbb7832014-05-27 02:45:47 +0000223 return nullptr;
Jordy Rosed5d2e502010-07-08 23:57:29 +0000224
Ted Kremenek49b1e382012-01-26 21:29:00 +0000225 ProgramStateRef stateNull, stateNonNull;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000226 std::tie(stateNull, stateNonNull) = assumeZero(C, state, l, S->getType());
Jordy Rosed5d2e502010-07-08 23:57:29 +0000227
228 if (stateNull && !stateNonNull) {
Anna Zakse0c7c272012-02-07 00:56:14 +0000229 if (!Filter.CheckCStringNullArg)
Craig Topper0dbb7832014-05-27 02:45:47 +0000230 return nullptr;
Anna Zakse0c7c272012-02-07 00:56:14 +0000231
Ted Kremenek750b7ac2010-12-20 21:19:09 +0000232 ExplodedNode *N = C.generateSink(stateNull);
Jordy Rose33c829a2010-07-07 07:48:06 +0000233 if (!N)
Craig Topper0dbb7832014-05-27 02:45:47 +0000234 return nullptr;
Jordy Rose33c829a2010-07-07 07:48:06 +0000235
Jordy Rosed5d2e502010-07-08 23:57:29 +0000236 if (!BT_Null)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000237 BT_Null.reset(new BuiltinBug(
238 Filter.CheckNameCStringNullArg, categories::UnixAPI,
239 "Null pointer argument in call to byte string function"));
Jordy Rose33c829a2010-07-07 07:48:06 +0000240
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000241 SmallString<80> buf;
Jordy Rosedceb0cf2011-06-20 02:06:40 +0000242 llvm::raw_svector_ostream os(buf);
243 assert(CurrentFunctionDescription);
244 os << "Null pointer argument in call to " << CurrentFunctionDescription;
245
Jordy Rose33c829a2010-07-07 07:48:06 +0000246 // Generate a report for this bug.
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000247 BuiltinBug *BT = static_cast<BuiltinBug*>(BT_Null.get());
Anna Zaks3a6bdf82011-08-17 23:00:25 +0000248 BugReport *report = new BugReport(*BT, os.str(), N);
Jordy Rose33c829a2010-07-07 07:48:06 +0000249
250 report->addRange(S->getSourceRange());
Jordan Rosea0f7d352012-08-28 00:50:51 +0000251 bugreporter::trackNullOrUndefValue(N, S, *report);
Jordan Rosee10d5a72012-11-02 01:53:40 +0000252 C.emitReport(report);
Craig Topper0dbb7832014-05-27 02:45:47 +0000253 return nullptr;
Jordy Rose33c829a2010-07-07 07:48:06 +0000254 }
255
256 // From here on, assume that the value is non-null.
Jordy Rosed5d2e502010-07-08 23:57:29 +0000257 assert(stateNonNull);
258 return stateNonNull;
Jordy Rose33c829a2010-07-07 07:48:06 +0000259}
260
Jordy Rose134a2362010-07-06 23:11:01 +0000261// FIXME: This was originally copied from ArrayBoundChecker.cpp. Refactor?
Ted Kremenek49b1e382012-01-26 21:29:00 +0000262ProgramStateRef CStringChecker::CheckLocation(CheckerContext &C,
263 ProgramStateRef state,
Jordy Rose722f5582010-08-16 07:51:42 +0000264 const Expr *S, SVal l,
Jordy Rosedceb0cf2011-06-20 02:06:40 +0000265 const char *warningMsg) const {
Jordy Rosed5d2e502010-07-08 23:57:29 +0000266 // If a previous check has failed, propagate the failure.
267 if (!state)
Craig Topper0dbb7832014-05-27 02:45:47 +0000268 return nullptr;
Jordy Rosed5d2e502010-07-08 23:57:29 +0000269
Jordy Rose134a2362010-07-06 23:11:01 +0000270 // Check for out of bound array element access.
271 const MemRegion *R = l.getAsRegion();
272 if (!R)
273 return state;
274
Jordy Rose134a2362010-07-06 23:11:01 +0000275 const ElementRegion *ER = dyn_cast<ElementRegion>(R);
276 if (!ER)
277 return state;
278
Zhongxing Xu8de0a3d2010-08-11 06:10:55 +0000279 assert(ER->getValueType() == C.getASTContext().CharTy &&
Jordy Rose134a2362010-07-06 23:11:01 +0000280 "CheckLocation should only be called with char* ElementRegions");
281
282 // Get the size of the array.
Ted Kremenek90af9092010-12-02 07:49:45 +0000283 const SubRegion *superReg = cast<SubRegion>(ER->getSuperRegion());
284 SValBuilder &svalBuilder = C.getSValBuilder();
Jordy Rose455bd582011-06-16 05:51:02 +0000285 SVal Extent =
286 svalBuilder.convertToArrayIndex(superReg->getExtent(svalBuilder));
David Blaikie2fdacbc2013-02-20 05:52:05 +0000287 DefinedOrUnknownSVal Size = Extent.castAs<DefinedOrUnknownSVal>();
Jordy Rose134a2362010-07-06 23:11:01 +0000288
289 // Get the index of the accessed element.
David Blaikie87396b92013-02-21 22:23:56 +0000290 DefinedOrUnknownSVal Idx = ER->getIndex().castAs<DefinedOrUnknownSVal>();
Jordy Rose134a2362010-07-06 23:11:01 +0000291
Ted Kremenek49b1e382012-01-26 21:29:00 +0000292 ProgramStateRef StInBound = state->assumeInBound(Idx, Size, true);
293 ProgramStateRef StOutBound = state->assumeInBound(Idx, Size, false);
Jordy Rose134a2362010-07-06 23:11:01 +0000294 if (StOutBound && !StInBound) {
Ted Kremenek750b7ac2010-12-20 21:19:09 +0000295 ExplodedNode *N = C.generateSink(StOutBound);
Jordy Rose134a2362010-07-06 23:11:01 +0000296 if (!N)
Craig Topper0dbb7832014-05-27 02:45:47 +0000297 return nullptr;
Jordy Rose134a2362010-07-06 23:11:01 +0000298
Jordy Rosedceb0cf2011-06-20 02:06:40 +0000299 if (!BT_Bounds) {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000300 BT_Bounds.reset(new BuiltinBug(
301 Filter.CheckNameCStringOutOfBounds, "Out-of-bound array access",
302 "Byte string function accesses out-of-bound array element"));
Jordy Rosedceb0cf2011-06-20 02:06:40 +0000303 }
304 BuiltinBug *BT = static_cast<BuiltinBug*>(BT_Bounds.get());
305
306 // Generate a report for this bug.
Anna Zaks3a6bdf82011-08-17 23:00:25 +0000307 BugReport *report;
Jordy Rosedceb0cf2011-06-20 02:06:40 +0000308 if (warningMsg) {
Anna Zaks3a6bdf82011-08-17 23:00:25 +0000309 report = new BugReport(*BT, warningMsg, N);
Jordy Rose722f5582010-08-16 07:51:42 +0000310 } else {
Jordy Rosedceb0cf2011-06-20 02:06:40 +0000311 assert(CurrentFunctionDescription);
312 assert(CurrentFunctionDescription[0] != '\0');
313
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000314 SmallString<80> buf;
Jordy Rosedceb0cf2011-06-20 02:06:40 +0000315 llvm::raw_svector_ostream os(buf);
Jordan Rose4938f272013-02-09 10:09:43 +0000316 os << toUppercase(CurrentFunctionDescription[0])
Jordy Rosedceb0cf2011-06-20 02:06:40 +0000317 << &CurrentFunctionDescription[1]
318 << " accesses out-of-bound array element";
Anna Zaks3a6bdf82011-08-17 23:00:25 +0000319 report = new BugReport(*BT, os.str(), N);
Jordy Rose722f5582010-08-16 07:51:42 +0000320 }
Jordy Rose134a2362010-07-06 23:11:01 +0000321
322 // FIXME: It would be nice to eventually make this diagnostic more clear,
323 // e.g., by referencing the original declaration or by saying *why* this
324 // reference is outside the range.
325
Jordy Rose134a2362010-07-06 23:11:01 +0000326 report->addRange(S->getSourceRange());
Jordan Rosee10d5a72012-11-02 01:53:40 +0000327 C.emitReport(report);
Craig Topper0dbb7832014-05-27 02:45:47 +0000328 return nullptr;
Jordy Rose134a2362010-07-06 23:11:01 +0000329 }
330
331 // Array bound check succeeded. From this point forward the array bound
332 // should always succeed.
333 return StInBound;
334}
335
Ted Kremenek49b1e382012-01-26 21:29:00 +0000336ProgramStateRef CStringChecker::CheckBufferAccess(CheckerContext &C,
337 ProgramStateRef state,
Jordy Rose134a2362010-07-06 23:11:01 +0000338 const Expr *Size,
339 const Expr *FirstBuf,
Jordy Rose722f5582010-08-16 07:51:42 +0000340 const Expr *SecondBuf,
Jordy Rosedceb0cf2011-06-20 02:06:40 +0000341 const char *firstMessage,
Jordy Rose328deee2011-06-20 03:49:16 +0000342 const char *secondMessage,
343 bool WarnAboutSize) const {
Jordy Rosed5d2e502010-07-08 23:57:29 +0000344 // If a previous check has failed, propagate the failure.
345 if (!state)
Craig Topper0dbb7832014-05-27 02:45:47 +0000346 return nullptr;
Jordy Rosed5d2e502010-07-08 23:57:29 +0000347
Ted Kremenek90af9092010-12-02 07:49:45 +0000348 SValBuilder &svalBuilder = C.getSValBuilder();
Jordy Rose455bd582011-06-16 05:51:02 +0000349 ASTContext &Ctx = svalBuilder.getContext();
Ted Kremenek632e3b72012-01-06 22:09:28 +0000350 const LocationContext *LCtx = C.getLocationContext();
Jordy Rose134a2362010-07-06 23:11:01 +0000351
Ted Kremenek90af9092010-12-02 07:49:45 +0000352 QualType sizeTy = Size->getType();
Jordy Rose134a2362010-07-06 23:11:01 +0000353 QualType PtrTy = Ctx.getPointerType(Ctx.CharTy);
354
Jordy Rose33c829a2010-07-07 07:48:06 +0000355 // Check that the first buffer is non-null.
Ted Kremenek632e3b72012-01-06 22:09:28 +0000356 SVal BufVal = state->getSVal(FirstBuf, LCtx);
Ted Kremenek90af9092010-12-02 07:49:45 +0000357 state = checkNonNull(C, state, FirstBuf, BufVal);
Jordy Rose33c829a2010-07-07 07:48:06 +0000358 if (!state)
Craig Topper0dbb7832014-05-27 02:45:47 +0000359 return nullptr;
Jordy Rose33c829a2010-07-07 07:48:06 +0000360
Anna Zakse0c7c272012-02-07 00:56:14 +0000361 // If out-of-bounds checking is turned off, skip the rest.
362 if (!Filter.CheckCStringOutOfBounds)
363 return state;
364
Jordy Rosed5d2e502010-07-08 23:57:29 +0000365 // Get the access length and make sure it is known.
Jordy Rosedceb0cf2011-06-20 02:06:40 +0000366 // FIXME: This assumes the caller has already checked that the access length
367 // is positive. And that it's unsigned.
Ted Kremenek632e3b72012-01-06 22:09:28 +0000368 SVal LengthVal = state->getSVal(Size, LCtx);
David Blaikie05785d12013-02-20 22:23:23 +0000369 Optional<NonLoc> Length = LengthVal.getAs<NonLoc>();
Jordy Rosed5d2e502010-07-08 23:57:29 +0000370 if (!Length)
371 return state;
372
Jordy Rose134a2362010-07-06 23:11:01 +0000373 // Compute the offset of the last element to be accessed: size-1.
David Blaikie2fdacbc2013-02-20 05:52:05 +0000374 NonLoc One = svalBuilder.makeIntVal(1, sizeTy).castAs<NonLoc>();
375 NonLoc LastOffset = svalBuilder
376 .evalBinOpNN(state, BO_Sub, *Length, One, sizeTy).castAs<NonLoc>();
Jordy Rose134a2362010-07-06 23:11:01 +0000377
Chris Lattner57540c52011-04-15 05:22:18 +0000378 // Check that the first buffer is sufficiently long.
Ted Kremenek90af9092010-12-02 07:49:45 +0000379 SVal BufStart = svalBuilder.evalCast(BufVal, PtrTy, FirstBuf->getType());
David Blaikie05785d12013-02-20 22:23:23 +0000380 if (Optional<Loc> BufLoc = BufStart.getAs<Loc>()) {
Jordy Rose328deee2011-06-20 03:49:16 +0000381 const Expr *warningExpr = (WarnAboutSize ? Size : FirstBuf);
382
Ted Kremenek90af9092010-12-02 07:49:45 +0000383 SVal BufEnd = svalBuilder.evalBinOpLN(state, BO_Add, *BufLoc,
384 LastOffset, PtrTy);
Jordy Rose328deee2011-06-20 03:49:16 +0000385 state = CheckLocation(C, state, warningExpr, BufEnd, firstMessage);
Jordy Rose134a2362010-07-06 23:11:01 +0000386
Jordy Roseafdb0532010-08-05 23:11:30 +0000387 // If the buffer isn't large enough, abort.
388 if (!state)
Craig Topper0dbb7832014-05-27 02:45:47 +0000389 return nullptr;
Jordy Roseafdb0532010-08-05 23:11:30 +0000390 }
Jordy Rose134a2362010-07-06 23:11:01 +0000391
392 // If there's a second buffer, check it as well.
393 if (SecondBuf) {
Ted Kremenek632e3b72012-01-06 22:09:28 +0000394 BufVal = state->getSVal(SecondBuf, LCtx);
Ted Kremenek90af9092010-12-02 07:49:45 +0000395 state = checkNonNull(C, state, SecondBuf, BufVal);
Jordy Rose33c829a2010-07-07 07:48:06 +0000396 if (!state)
Craig Topper0dbb7832014-05-27 02:45:47 +0000397 return nullptr;
Jordy Rose33c829a2010-07-07 07:48:06 +0000398
Ted Kremenek90af9092010-12-02 07:49:45 +0000399 BufStart = svalBuilder.evalCast(BufVal, PtrTy, SecondBuf->getType());
David Blaikie05785d12013-02-20 22:23:23 +0000400 if (Optional<Loc> BufLoc = BufStart.getAs<Loc>()) {
Jordy Rose328deee2011-06-20 03:49:16 +0000401 const Expr *warningExpr = (WarnAboutSize ? Size : SecondBuf);
402
Ted Kremenek90af9092010-12-02 07:49:45 +0000403 SVal BufEnd = svalBuilder.evalBinOpLN(state, BO_Add, *BufLoc,
404 LastOffset, PtrTy);
Jordy Rose328deee2011-06-20 03:49:16 +0000405 state = CheckLocation(C, state, warningExpr, BufEnd, secondMessage);
Jordy Roseafdb0532010-08-05 23:11:30 +0000406 }
Jordy Rose134a2362010-07-06 23:11:01 +0000407 }
408
409 // Large enough or not, return this state!
410 return state;
411}
412
Ted Kremenek49b1e382012-01-26 21:29:00 +0000413ProgramStateRef CStringChecker::CheckOverlap(CheckerContext &C,
414 ProgramStateRef state,
Jordy Rosed5d2e502010-07-08 23:57:29 +0000415 const Expr *Size,
Jordy Rose134a2362010-07-06 23:11:01 +0000416 const Expr *First,
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000417 const Expr *Second) const {
Anna Zakse0c7c272012-02-07 00:56:14 +0000418 if (!Filter.CheckCStringBufferOverlap)
419 return state;
420
Jordy Rose134a2362010-07-06 23:11:01 +0000421 // Do a simple check for overlap: if the two arguments are from the same
422 // buffer, see if the end of the first is greater than the start of the second
423 // or vice versa.
424
Jordy Rosed5d2e502010-07-08 23:57:29 +0000425 // If a previous check has failed, propagate the failure.
426 if (!state)
Craig Topper0dbb7832014-05-27 02:45:47 +0000427 return nullptr;
Jordy Rosed5d2e502010-07-08 23:57:29 +0000428
Ted Kremenek49b1e382012-01-26 21:29:00 +0000429 ProgramStateRef stateTrue, stateFalse;
Jordy Rose134a2362010-07-06 23:11:01 +0000430
431 // Get the buffer values and make sure they're known locations.
Ted Kremenek632e3b72012-01-06 22:09:28 +0000432 const LocationContext *LCtx = C.getLocationContext();
433 SVal firstVal = state->getSVal(First, LCtx);
434 SVal secondVal = state->getSVal(Second, LCtx);
Jordy Rose134a2362010-07-06 23:11:01 +0000435
David Blaikie05785d12013-02-20 22:23:23 +0000436 Optional<Loc> firstLoc = firstVal.getAs<Loc>();
Ted Kremenek90af9092010-12-02 07:49:45 +0000437 if (!firstLoc)
Jordy Rose134a2362010-07-06 23:11:01 +0000438 return state;
439
David Blaikie05785d12013-02-20 22:23:23 +0000440 Optional<Loc> secondLoc = secondVal.getAs<Loc>();
Ted Kremenek90af9092010-12-02 07:49:45 +0000441 if (!secondLoc)
Jordy Rose134a2362010-07-06 23:11:01 +0000442 return state;
443
444 // Are the two values the same?
Ted Kremenek90af9092010-12-02 07:49:45 +0000445 SValBuilder &svalBuilder = C.getSValBuilder();
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000446 std::tie(stateTrue, stateFalse) =
Ted Kremenek90af9092010-12-02 07:49:45 +0000447 state->assume(svalBuilder.evalEQ(state, *firstLoc, *secondLoc));
Jordy Rose134a2362010-07-06 23:11:01 +0000448
449 if (stateTrue && !stateFalse) {
450 // If the values are known to be equal, that's automatically an overlap.
Ted Kremenek90af9092010-12-02 07:49:45 +0000451 emitOverlapBug(C, stateTrue, First, Second);
Craig Topper0dbb7832014-05-27 02:45:47 +0000452 return nullptr;
Jordy Rose134a2362010-07-06 23:11:01 +0000453 }
454
Ted Kremenekc5bea1e2010-12-01 22:16:56 +0000455 // assume the two expressions are not equal.
Jordy Rose134a2362010-07-06 23:11:01 +0000456 assert(stateFalse);
457 state = stateFalse;
458
459 // Which value comes first?
Jordy Rose0585a612011-06-16 05:56:50 +0000460 QualType cmpTy = svalBuilder.getConditionType();
Ted Kremenek90af9092010-12-02 07:49:45 +0000461 SVal reverse = svalBuilder.evalBinOpLL(state, BO_GT,
462 *firstLoc, *secondLoc, cmpTy);
David Blaikie05785d12013-02-20 22:23:23 +0000463 Optional<DefinedOrUnknownSVal> reverseTest =
David Blaikie2fdacbc2013-02-20 05:52:05 +0000464 reverse.getAs<DefinedOrUnknownSVal>();
Ted Kremenek90af9092010-12-02 07:49:45 +0000465 if (!reverseTest)
Jordy Rose134a2362010-07-06 23:11:01 +0000466 return state;
467
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000468 std::tie(stateTrue, stateFalse) = state->assume(*reverseTest);
Jordy Rose134a2362010-07-06 23:11:01 +0000469 if (stateTrue) {
470 if (stateFalse) {
471 // If we don't know which one comes first, we can't perform this test.
472 return state;
473 } else {
Ted Kremenek90af9092010-12-02 07:49:45 +0000474 // Switch the values so that firstVal is before secondVal.
David Blaikie2fdacbc2013-02-20 05:52:05 +0000475 std::swap(firstLoc, secondLoc);
Jordy Rose134a2362010-07-06 23:11:01 +0000476
477 // Switch the Exprs as well, so that they still correspond.
David Blaikie2fdacbc2013-02-20 05:52:05 +0000478 std::swap(First, Second);
Jordy Rose134a2362010-07-06 23:11:01 +0000479 }
480 }
481
482 // Get the length, and make sure it too is known.
Ted Kremenek632e3b72012-01-06 22:09:28 +0000483 SVal LengthVal = state->getSVal(Size, LCtx);
David Blaikie05785d12013-02-20 22:23:23 +0000484 Optional<NonLoc> Length = LengthVal.getAs<NonLoc>();
Jordy Rose134a2362010-07-06 23:11:01 +0000485 if (!Length)
486 return state;
487
488 // Convert the first buffer's start address to char*.
489 // Bail out if the cast fails.
Jordy Rose0585a612011-06-16 05:56:50 +0000490 ASTContext &Ctx = svalBuilder.getContext();
Jordy Rose134a2362010-07-06 23:11:01 +0000491 QualType CharPtrTy = Ctx.getPointerType(Ctx.CharTy);
Jordy Rose455bd582011-06-16 05:51:02 +0000492 SVal FirstStart = svalBuilder.evalCast(*firstLoc, CharPtrTy,
493 First->getType());
David Blaikie05785d12013-02-20 22:23:23 +0000494 Optional<Loc> FirstStartLoc = FirstStart.getAs<Loc>();
Jordy Rose134a2362010-07-06 23:11:01 +0000495 if (!FirstStartLoc)
496 return state;
497
498 // Compute the end of the first buffer. Bail out if THAT fails.
Ted Kremenek90af9092010-12-02 07:49:45 +0000499 SVal FirstEnd = svalBuilder.evalBinOpLN(state, BO_Add,
Jordy Rose134a2362010-07-06 23:11:01 +0000500 *FirstStartLoc, *Length, CharPtrTy);
David Blaikie05785d12013-02-20 22:23:23 +0000501 Optional<Loc> FirstEndLoc = FirstEnd.getAs<Loc>();
Jordy Rose134a2362010-07-06 23:11:01 +0000502 if (!FirstEndLoc)
503 return state;
504
505 // Is the end of the first buffer past the start of the second buffer?
Ted Kremenek90af9092010-12-02 07:49:45 +0000506 SVal Overlap = svalBuilder.evalBinOpLL(state, BO_GT,
507 *FirstEndLoc, *secondLoc, cmpTy);
David Blaikie05785d12013-02-20 22:23:23 +0000508 Optional<DefinedOrUnknownSVal> OverlapTest =
David Blaikie2fdacbc2013-02-20 05:52:05 +0000509 Overlap.getAs<DefinedOrUnknownSVal>();
Jordy Rose134a2362010-07-06 23:11:01 +0000510 if (!OverlapTest)
511 return state;
512
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000513 std::tie(stateTrue, stateFalse) = state->assume(*OverlapTest);
Jordy Rose134a2362010-07-06 23:11:01 +0000514
515 if (stateTrue && !stateFalse) {
516 // Overlap!
Ted Kremenek90af9092010-12-02 07:49:45 +0000517 emitOverlapBug(C, stateTrue, First, Second);
Craig Topper0dbb7832014-05-27 02:45:47 +0000518 return nullptr;
Jordy Rose134a2362010-07-06 23:11:01 +0000519 }
520
Ted Kremenekc5bea1e2010-12-01 22:16:56 +0000521 // assume the two expressions don't overlap.
Jordy Rose134a2362010-07-06 23:11:01 +0000522 assert(stateFalse);
523 return stateFalse;
524}
525
Ted Kremenek49b1e382012-01-26 21:29:00 +0000526void CStringChecker::emitOverlapBug(CheckerContext &C, ProgramStateRef state,
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000527 const Stmt *First, const Stmt *Second) const {
Ted Kremenek750b7ac2010-12-20 21:19:09 +0000528 ExplodedNode *N = C.generateSink(state);
Jordy Rose134a2362010-07-06 23:11:01 +0000529 if (!N)
530 return;
531
532 if (!BT_Overlap)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000533 BT_Overlap.reset(new BugType(Filter.CheckNameCStringBufferOverlap,
534 categories::UnixAPI, "Improper arguments"));
Jordy Rose134a2362010-07-06 23:11:01 +0000535
536 // Generate a report for this bug.
Anna Zaks3a6bdf82011-08-17 23:00:25 +0000537 BugReport *report =
538 new BugReport(*BT_Overlap,
Jordy Rose134a2362010-07-06 23:11:01 +0000539 "Arguments must not be overlapping buffers", N);
540 report->addRange(First->getSourceRange());
541 report->addRange(Second->getSourceRange());
542
Jordan Rosee10d5a72012-11-02 01:53:40 +0000543 C.emitReport(report);
Jordy Rose134a2362010-07-06 23:11:01 +0000544}
545
Ted Kremenek49b1e382012-01-26 21:29:00 +0000546ProgramStateRef CStringChecker::checkAdditionOverflow(CheckerContext &C,
547 ProgramStateRef state,
Jordy Rose634c12d2011-06-15 05:52:56 +0000548 NonLoc left,
549 NonLoc right) const {
Anna Zakse0c7c272012-02-07 00:56:14 +0000550 // If out-of-bounds checking is turned off, skip the rest.
551 if (!Filter.CheckCStringOutOfBounds)
552 return state;
553
Jordy Rose634c12d2011-06-15 05:52:56 +0000554 // If a previous check has failed, propagate the failure.
555 if (!state)
Craig Topper0dbb7832014-05-27 02:45:47 +0000556 return nullptr;
Jordy Rose634c12d2011-06-15 05:52:56 +0000557
558 SValBuilder &svalBuilder = C.getSValBuilder();
559 BasicValueFactory &BVF = svalBuilder.getBasicValueFactory();
560
561 QualType sizeTy = svalBuilder.getContext().getSizeType();
562 const llvm::APSInt &maxValInt = BVF.getMaxValue(sizeTy);
563 NonLoc maxVal = svalBuilder.makeIntVal(maxValInt);
564
Anna Zaks7c96b7d2011-12-11 18:43:40 +0000565 SVal maxMinusRight;
David Blaikie2fdacbc2013-02-20 05:52:05 +0000566 if (right.getAs<nonloc::ConcreteInt>()) {
Anna Zaks7c96b7d2011-12-11 18:43:40 +0000567 maxMinusRight = svalBuilder.evalBinOpNN(state, BO_Sub, maxVal, right,
568 sizeTy);
569 } else {
Jordy Rose634c12d2011-06-15 05:52:56 +0000570 // Try switching the operands. (The order of these two assignments is
571 // important!)
572 maxMinusRight = svalBuilder.evalBinOpNN(state, BO_Sub, maxVal, left,
573 sizeTy);
574 left = right;
575 }
576
David Blaikie05785d12013-02-20 22:23:23 +0000577 if (Optional<NonLoc> maxMinusRightNL = maxMinusRight.getAs<NonLoc>()) {
Jordy Rose634c12d2011-06-15 05:52:56 +0000578 QualType cmpTy = svalBuilder.getConditionType();
579 // If left > max - right, we have an overflow.
580 SVal willOverflow = svalBuilder.evalBinOpNN(state, BO_GT, left,
581 *maxMinusRightNL, cmpTy);
582
Ted Kremenek49b1e382012-01-26 21:29:00 +0000583 ProgramStateRef stateOverflow, stateOkay;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000584 std::tie(stateOverflow, stateOkay) =
David Blaikie2fdacbc2013-02-20 05:52:05 +0000585 state->assume(willOverflow.castAs<DefinedOrUnknownSVal>());
Jordy Rose634c12d2011-06-15 05:52:56 +0000586
587 if (stateOverflow && !stateOkay) {
588 // We have an overflow. Emit a bug report.
589 ExplodedNode *N = C.generateSink(stateOverflow);
590 if (!N)
Craig Topper0dbb7832014-05-27 02:45:47 +0000591 return nullptr;
Jordy Rose634c12d2011-06-15 05:52:56 +0000592
593 if (!BT_AdditionOverflow)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000594 BT_AdditionOverflow.reset(
595 new BuiltinBug(Filter.CheckNameCStringOutOfBounds, "API",
596 "Sum of expressions causes overflow"));
Jordy Rose634c12d2011-06-15 05:52:56 +0000597
Jordy Rose634c12d2011-06-15 05:52:56 +0000598 // This isn't a great error message, but this should never occur in real
599 // code anyway -- you'd have to create a buffer longer than a size_t can
600 // represent, which is sort of a contradiction.
Jordy Rose789adbb2011-06-20 03:51:53 +0000601 const char *warning =
602 "This expression will create a string whose length is too big to "
603 "be represented as a size_t";
Jordy Rose634c12d2011-06-15 05:52:56 +0000604
605 // Generate a report for this bug.
Jordy Rose789adbb2011-06-20 03:51:53 +0000606 BugReport *report = new BugReport(*BT_AdditionOverflow, warning, N);
Jordan Rosee10d5a72012-11-02 01:53:40 +0000607 C.emitReport(report);
Jordy Rose634c12d2011-06-15 05:52:56 +0000608
Craig Topper0dbb7832014-05-27 02:45:47 +0000609 return nullptr;
Jordy Rose634c12d2011-06-15 05:52:56 +0000610 }
611
612 // From now on, assume an overflow didn't occur.
613 assert(stateOkay);
614 state = stateOkay;
615 }
616
617 return state;
618}
619
Ted Kremenek49b1e382012-01-26 21:29:00 +0000620ProgramStateRef CStringChecker::setCStringLength(ProgramStateRef state,
Jordy Rose722f5582010-08-16 07:51:42 +0000621 const MemRegion *MR,
Ted Kremenek90af9092010-12-02 07:49:45 +0000622 SVal strLength) {
623 assert(!strLength.isUndef() && "Attempt to set an undefined string length");
Jordy Rose722f5582010-08-16 07:51:42 +0000624
625 MR = MR->StripCasts();
626
627 switch (MR->getKind()) {
628 case MemRegion::StringRegionKind:
629 // FIXME: This can happen if we strcpy() into a string region. This is
630 // undefined [C99 6.4.5p6], but we should still warn about it.
631 return state;
632
633 case MemRegion::SymbolicRegionKind:
634 case MemRegion::AllocaRegionKind:
635 case MemRegion::VarRegionKind:
636 case MemRegion::FieldRegionKind:
637 case MemRegion::ObjCIvarRegionKind:
Jordy Rose0e9fb282011-06-15 05:14:03 +0000638 // These are the types we can currently track string lengths for.
639 break;
Jordy Rose722f5582010-08-16 07:51:42 +0000640
641 case MemRegion::ElementRegionKind:
642 // FIXME: Handle element regions by upper-bounding the parent region's
643 // string length.
644 return state;
645
646 default:
647 // Other regions (mostly non-data) can't have a reliable C string length.
648 // For now, just ignore the change.
649 // FIXME: These are rare but not impossible. We should output some kind of
650 // warning for things like strcpy((char[]){'a', 0}, "b");
651 return state;
652 }
Jordy Rose0e9fb282011-06-15 05:14:03 +0000653
654 if (strLength.isUnknown())
655 return state->remove<CStringLength>(MR);
656
657 return state->set<CStringLength>(MR, strLength);
Jordy Rose722f5582010-08-16 07:51:42 +0000658}
659
Ted Kremenek90af9092010-12-02 07:49:45 +0000660SVal CStringChecker::getCStringLengthForRegion(CheckerContext &C,
Ted Kremenek49b1e382012-01-26 21:29:00 +0000661 ProgramStateRef &state,
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000662 const Expr *Ex,
Jordy Rose634c12d2011-06-15 05:52:56 +0000663 const MemRegion *MR,
664 bool hypothetical) {
665 if (!hypothetical) {
666 // If there's a recorded length, go ahead and return it.
667 const SVal *Recorded = state->get<CStringLength>(MR);
668 if (Recorded)
669 return *Recorded;
670 }
Jordan Rose60619a62013-08-19 16:27:34 +0000671
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000672 // Otherwise, get a new symbol and update the state.
Ted Kremenek90af9092010-12-02 07:49:45 +0000673 SValBuilder &svalBuilder = C.getSValBuilder();
674 QualType sizeTy = svalBuilder.getContext().getSizeType();
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000675 SVal strLength = svalBuilder.getMetadataSymbolVal(CStringChecker::getTag(),
Ted Kremenekd94854a2012-08-22 06:26:15 +0000676 MR, Ex, sizeTy,
677 C.blockCount());
Jordy Rose634c12d2011-06-15 05:52:56 +0000678
Jordan Rose60619a62013-08-19 16:27:34 +0000679 if (!hypothetical) {
680 if (Optional<NonLoc> strLn = strLength.getAs<NonLoc>()) {
681 // In case of unbounded calls strlen etc bound the range to SIZE_MAX/4
682 BasicValueFactory &BVF = svalBuilder.getBasicValueFactory();
683 const llvm::APSInt &maxValInt = BVF.getMaxValue(sizeTy);
684 llvm::APSInt fourInt = APSIntType(maxValInt).getValue(4);
685 const llvm::APSInt *maxLengthInt = BVF.evalAPSInt(BO_Div, maxValInt,
686 fourInt);
687 NonLoc maxLength = svalBuilder.makeIntVal(*maxLengthInt);
688 SVal evalLength = svalBuilder.evalBinOpNN(state, BO_LE, *strLn,
689 maxLength, sizeTy);
690 state = state->assume(evalLength.castAs<DefinedOrUnknownSVal>(), true);
691 }
Jordy Rose634c12d2011-06-15 05:52:56 +0000692 state = state->set<CStringLength>(MR, strLength);
Jordan Rose60619a62013-08-19 16:27:34 +0000693 }
Jordy Rose634c12d2011-06-15 05:52:56 +0000694
Ted Kremenek90af9092010-12-02 07:49:45 +0000695 return strLength;
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000696}
697
Ted Kremenek49b1e382012-01-26 21:29:00 +0000698SVal CStringChecker::getCStringLength(CheckerContext &C, ProgramStateRef &state,
Jordy Rose634c12d2011-06-15 05:52:56 +0000699 const Expr *Ex, SVal Buf,
700 bool hypothetical) const {
Jordy Roseb052e8f2010-07-27 01:37:31 +0000701 const MemRegion *MR = Buf.getAsRegion();
702 if (!MR) {
703 // If we can't get a region, see if it's something we /know/ isn't a
704 // C string. In the context of locations, the only time we can issue such
705 // a warning is for labels.
David Blaikie05785d12013-02-20 22:23:23 +0000706 if (Optional<loc::GotoLabel> Label = Buf.getAs<loc::GotoLabel>()) {
Anna Zakse0c7c272012-02-07 00:56:14 +0000707 if (!Filter.CheckCStringNotNullTerm)
708 return UndefinedVal();
709
Anna Zaksda4c8d62011-10-26 21:06:34 +0000710 if (ExplodedNode *N = C.addTransition(state)) {
Jordy Roseb052e8f2010-07-27 01:37:31 +0000711 if (!BT_NotCString)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000712 BT_NotCString.reset(new BuiltinBug(
713 Filter.CheckNameCStringNotNullTerm, categories::UnixAPI,
714 "Argument is not a null-terminated string."));
Jordy Roseb052e8f2010-07-27 01:37:31 +0000715
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000716 SmallString<120> buf;
Jordy Roseb052e8f2010-07-27 01:37:31 +0000717 llvm::raw_svector_ostream os(buf);
Jordy Rosedceb0cf2011-06-20 02:06:40 +0000718 assert(CurrentFunctionDescription);
719 os << "Argument to " << CurrentFunctionDescription
720 << " is the address of the label '" << Label->getLabel()->getName()
Jordy Roseb052e8f2010-07-27 01:37:31 +0000721 << "', which is not a null-terminated string";
722
723 // Generate a report for this bug.
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000724 BugReport *report = new BugReport(*BT_NotCString, os.str(), N);
Jordy Roseb052e8f2010-07-27 01:37:31 +0000725
726 report->addRange(Ex->getSourceRange());
Jordan Rosee10d5a72012-11-02 01:53:40 +0000727 C.emitReport(report);
Jordy Roseb052e8f2010-07-27 01:37:31 +0000728 }
Jordy Roseb052e8f2010-07-27 01:37:31 +0000729 return UndefinedVal();
Anna Zakse0c7c272012-02-07 00:56:14 +0000730
Jordy Roseb052e8f2010-07-27 01:37:31 +0000731 }
732
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000733 // If it's not a region and not a label, give up.
734 return UnknownVal();
Jordy Roseb052e8f2010-07-27 01:37:31 +0000735 }
736
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000737 // If we have a region, strip casts from it and see if we can figure out
738 // its length. For anything we can't figure out, just return UnknownVal.
739 MR = MR->StripCasts();
740
741 switch (MR->getKind()) {
742 case MemRegion::StringRegionKind: {
743 // Modifying the contents of string regions is undefined [C99 6.4.5p6],
744 // so we can assume that the byte length is the correct C string length.
Ted Kremenek90af9092010-12-02 07:49:45 +0000745 SValBuilder &svalBuilder = C.getSValBuilder();
746 QualType sizeTy = svalBuilder.getContext().getSizeType();
747 const StringLiteral *strLit = cast<StringRegion>(MR)->getStringLiteral();
748 return svalBuilder.makeIntVal(strLit->getByteLength(), sizeTy);
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000749 }
750 case MemRegion::SymbolicRegionKind:
751 case MemRegion::AllocaRegionKind:
752 case MemRegion::VarRegionKind:
753 case MemRegion::FieldRegionKind:
754 case MemRegion::ObjCIvarRegionKind:
Jordy Rose634c12d2011-06-15 05:52:56 +0000755 return getCStringLengthForRegion(C, state, Ex, MR, hypothetical);
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000756 case MemRegion::CompoundLiteralRegionKind:
757 // FIXME: Can we track this? Is it necessary?
758 return UnknownVal();
759 case MemRegion::ElementRegionKind:
760 // FIXME: How can we handle this? It's not good enough to subtract the
761 // offset from the base string length; consider "123\x00567" and &a[5].
762 return UnknownVal();
763 default:
764 // Other regions (mostly non-data) can't have a reliable C string length.
765 // In this case, an error is emitted and UndefinedVal is returned.
766 // The caller should always be prepared to handle this case.
Anna Zakse0c7c272012-02-07 00:56:14 +0000767 if (!Filter.CheckCStringNotNullTerm)
768 return UndefinedVal();
769
Anna Zaksda4c8d62011-10-26 21:06:34 +0000770 if (ExplodedNode *N = C.addTransition(state)) {
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000771 if (!BT_NotCString)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000772 BT_NotCString.reset(new BuiltinBug(
773 Filter.CheckNameCStringNotNullTerm, categories::UnixAPI,
774 "Argument is not a null-terminated string."));
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000775
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000776 SmallString<120> buf;
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000777 llvm::raw_svector_ostream os(buf);
778
Jordy Rosedceb0cf2011-06-20 02:06:40 +0000779 assert(CurrentFunctionDescription);
780 os << "Argument to " << CurrentFunctionDescription << " is ";
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000781
782 if (SummarizeRegion(os, C.getASTContext(), MR))
783 os << ", which is not a null-terminated string";
784 else
785 os << "not a null-terminated string";
786
787 // Generate a report for this bug.
Anna Zaks3a6bdf82011-08-17 23:00:25 +0000788 BugReport *report = new BugReport(*BT_NotCString,
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000789 os.str(), N);
790
791 report->addRange(Ex->getSourceRange());
Jordan Rosee10d5a72012-11-02 01:53:40 +0000792 C.emitReport(report);
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000793 }
794
795 return UndefinedVal();
796 }
Jordy Roseb052e8f2010-07-27 01:37:31 +0000797}
798
Lenny Maioranif3539ad2011-04-12 17:08:43 +0000799const StringLiteral *CStringChecker::getCStringLiteral(CheckerContext &C,
Ted Kremenek49b1e382012-01-26 21:29:00 +0000800 ProgramStateRef &state, const Expr *expr, SVal val) const {
Lenny Maioranif3539ad2011-04-12 17:08:43 +0000801
802 // Get the memory region pointed to by the val.
803 const MemRegion *bufRegion = val.getAsRegion();
804 if (!bufRegion)
Craig Topper0dbb7832014-05-27 02:45:47 +0000805 return nullptr;
Lenny Maioranif3539ad2011-04-12 17:08:43 +0000806
807 // Strip casts off the memory region.
808 bufRegion = bufRegion->StripCasts();
809
810 // Cast the memory region to a string region.
811 const StringRegion *strRegion= dyn_cast<StringRegion>(bufRegion);
812 if (!strRegion)
Craig Topper0dbb7832014-05-27 02:45:47 +0000813 return nullptr;
Lenny Maioranif3539ad2011-04-12 17:08:43 +0000814
815 // Return the actual string in the string region.
816 return strRegion->getStringLiteral();
817}
818
Ted Kremenek49b1e382012-01-26 21:29:00 +0000819ProgramStateRef CStringChecker::InvalidateBuffer(CheckerContext &C,
Anton Yartsev968c60a2013-11-17 09:18:48 +0000820 ProgramStateRef state,
821 const Expr *E, SVal V,
822 bool IsSourceBuffer) {
David Blaikie05785d12013-02-20 22:23:23 +0000823 Optional<Loc> L = V.getAs<Loc>();
Jordy Rose722f5582010-08-16 07:51:42 +0000824 if (!L)
825 return state;
826
827 // FIXME: This is a simplified version of what's in CFRefCount.cpp -- it makes
828 // some assumptions about the value that CFRefCount can't. Even so, it should
829 // probably be refactored.
David Blaikie05785d12013-02-20 22:23:23 +0000830 if (Optional<loc::MemRegionVal> MR = L->getAs<loc::MemRegionVal>()) {
Jordy Rose722f5582010-08-16 07:51:42 +0000831 const MemRegion *R = MR->getRegion()->StripCasts();
832
833 // Are we dealing with an ElementRegion? If so, we should be invalidating
834 // the super-region.
835 if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
836 R = ER->getSuperRegion();
837 // FIXME: What about layers of ElementRegions?
838 }
839
840 // Invalidate this region.
Ted Kremenekd519cae2012-02-17 23:13:45 +0000841 const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
Anton Yartsev968c60a2013-11-17 09:18:48 +0000842
843 bool CausesPointerEscape = false;
844 RegionAndSymbolInvalidationTraits ITraits;
845 // Invalidate and escape only indirect regions accessible through the source
846 // buffer.
847 if (IsSourceBuffer) {
848 ITraits.setTrait(R,
849 RegionAndSymbolInvalidationTraits::TK_PreserveContents);
850 ITraits.setTrait(R, RegionAndSymbolInvalidationTraits::TK_SuppressEscape);
851 CausesPointerEscape = true;
852 }
853
854 return state->invalidateRegions(R, E, C.blockCount(), LCtx,
Craig Topper0dbb7832014-05-27 02:45:47 +0000855 CausesPointerEscape, nullptr, nullptr,
856 &ITraits);
Jordy Rose722f5582010-08-16 07:51:42 +0000857 }
858
859 // If we have a non-region value by chance, just remove the binding.
860 // FIXME: is this necessary or correct? This handles the non-Region
861 // cases. Is it ever valid to store to these?
Ted Kremenek62698882012-08-22 06:37:46 +0000862 return state->killBinding(*L);
Jordy Rose722f5582010-08-16 07:51:42 +0000863}
864
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000865bool CStringChecker::SummarizeRegion(raw_ostream &os, ASTContext &Ctx,
Jordy Roseb052e8f2010-07-27 01:37:31 +0000866 const MemRegion *MR) {
Ted Kremenek8df44b262011-08-12 20:02:48 +0000867 const TypedValueRegion *TVR = dyn_cast<TypedValueRegion>(MR);
Jordy Roseb052e8f2010-07-27 01:37:31 +0000868
Jordy Roseadd45b72011-08-12 21:41:07 +0000869 switch (MR->getKind()) {
Jordy Roseb052e8f2010-07-27 01:37:31 +0000870 case MemRegion::FunctionTextRegionKind: {
Anna Zaks42782342012-09-17 19:13:56 +0000871 const NamedDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
Jordy Roseb052e8f2010-07-27 01:37:31 +0000872 if (FD)
Benjamin Kramerb89514a2011-10-14 18:45:37 +0000873 os << "the address of the function '" << *FD << '\'';
Jordy Roseb052e8f2010-07-27 01:37:31 +0000874 else
875 os << "the address of a function";
876 return true;
877 }
878 case MemRegion::BlockTextRegionKind:
879 os << "block text";
880 return true;
881 case MemRegion::BlockDataRegionKind:
882 os << "a block";
883 return true;
884 case MemRegion::CXXThisRegionKind:
Zhongxing Xu03207162010-11-26 08:52:48 +0000885 case MemRegion::CXXTempObjectRegionKind:
Ted Kremenek8df44b262011-08-12 20:02:48 +0000886 os << "a C++ temp object of type " << TVR->getValueType().getAsString();
Jordy Roseb052e8f2010-07-27 01:37:31 +0000887 return true;
888 case MemRegion::VarRegionKind:
Ted Kremenek8df44b262011-08-12 20:02:48 +0000889 os << "a variable of type" << TVR->getValueType().getAsString();
Jordy Roseb052e8f2010-07-27 01:37:31 +0000890 return true;
891 case MemRegion::FieldRegionKind:
Ted Kremenek8df44b262011-08-12 20:02:48 +0000892 os << "a field of type " << TVR->getValueType().getAsString();
Jordy Roseb052e8f2010-07-27 01:37:31 +0000893 return true;
894 case MemRegion::ObjCIvarRegionKind:
Ted Kremenek8df44b262011-08-12 20:02:48 +0000895 os << "an instance variable of type " << TVR->getValueType().getAsString();
Jordy Roseb052e8f2010-07-27 01:37:31 +0000896 return true;
897 default:
898 return false;
899 }
900}
901
Jordy Rosed5d2e502010-07-08 23:57:29 +0000902//===----------------------------------------------------------------------===//
Ted Kremenekdc891422010-12-01 21:57:22 +0000903// evaluation of individual function calls.
Jordy Rosed5d2e502010-07-08 23:57:29 +0000904//===----------------------------------------------------------------------===//
905
Lenny Maiorani79d74142011-03-31 21:36:53 +0000906void CStringChecker::evalCopyCommon(CheckerContext &C,
907 const CallExpr *CE,
Ted Kremenek49b1e382012-01-26 21:29:00 +0000908 ProgramStateRef state,
Jordy Rosed5d2e502010-07-08 23:57:29 +0000909 const Expr *Size, const Expr *Dest,
Lenny Maiorani79d74142011-03-31 21:36:53 +0000910 const Expr *Source, bool Restricted,
911 bool IsMempcpy) const {
Jordy Rosedceb0cf2011-06-20 02:06:40 +0000912 CurrentFunctionDescription = "memory copy function";
913
Jordy Rosed5d2e502010-07-08 23:57:29 +0000914 // See if the size argument is zero.
Ted Kremenek632e3b72012-01-06 22:09:28 +0000915 const LocationContext *LCtx = C.getLocationContext();
916 SVal sizeVal = state->getSVal(Size, LCtx);
Ted Kremenek90af9092010-12-02 07:49:45 +0000917 QualType sizeTy = Size->getType();
Jordy Rosed5d2e502010-07-08 23:57:29 +0000918
Ted Kremenek49b1e382012-01-26 21:29:00 +0000919 ProgramStateRef stateZeroSize, stateNonZeroSize;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000920 std::tie(stateZeroSize, stateNonZeroSize) =
Jordy Rose455bd582011-06-16 05:51:02 +0000921 assumeZero(C, state, sizeVal, sizeTy);
Jordy Rosed5d2e502010-07-08 23:57:29 +0000922
Lenny Maiorani79d74142011-03-31 21:36:53 +0000923 // Get the value of the Dest.
Ted Kremenek632e3b72012-01-06 22:09:28 +0000924 SVal destVal = state->getSVal(Dest, LCtx);
Lenny Maiorani79d74142011-03-31 21:36:53 +0000925
926 // If the size is zero, there won't be any actual memory access, so
927 // just bind the return value to the destination buffer and return.
Anna Zaksb3b56bb2012-05-03 18:21:28 +0000928 if (stateZeroSize && !stateNonZeroSize) {
Ted Kremenek632e3b72012-01-06 22:09:28 +0000929 stateZeroSize = stateZeroSize->BindExpr(CE, LCtx, destVal);
Anna Zaksda4c8d62011-10-26 21:06:34 +0000930 C.addTransition(stateZeroSize);
Anna Zaksb3b56bb2012-05-03 18:21:28 +0000931 return;
Lenny Maiorani79d74142011-03-31 21:36:53 +0000932 }
Jordy Rosed5d2e502010-07-08 23:57:29 +0000933
934 // If the size can be nonzero, we have to check the other arguments.
Ted Kremenek90af9092010-12-02 07:49:45 +0000935 if (stateNonZeroSize) {
Jordy Rose63b84be2011-06-04 00:04:22 +0000936 state = stateNonZeroSize;
Lenny Maiorani79d74142011-03-31 21:36:53 +0000937
938 // Ensure the destination is not null. If it is NULL there will be a
939 // NULL pointer dereference.
940 state = checkNonNull(C, state, Dest, destVal);
941 if (!state)
942 return;
943
944 // Get the value of the Src.
Ted Kremenek632e3b72012-01-06 22:09:28 +0000945 SVal srcVal = state->getSVal(Source, LCtx);
Lenny Maiorani79d74142011-03-31 21:36:53 +0000946
947 // Ensure the source is not null. If it is NULL there will be a
948 // NULL pointer dereference.
949 state = checkNonNull(C, state, Source, srcVal);
950 if (!state)
951 return;
952
Jordy Rosefb5e8c22011-06-04 01:50:25 +0000953 // Ensure the accesses are valid and that the buffers do not overlap.
Jordy Rosedceb0cf2011-06-20 02:06:40 +0000954 const char * const writeWarning =
955 "Memory copy function overflows destination buffer";
Jordy Rose722f5582010-08-16 07:51:42 +0000956 state = CheckBufferAccess(C, state, Size, Dest, Source,
Craig Topper0dbb7832014-05-27 02:45:47 +0000957 writeWarning, /* sourceWarning = */ nullptr);
Jordy Rosed5d2e502010-07-08 23:57:29 +0000958 if (Restricted)
959 state = CheckOverlap(C, state, Size, Dest, Source);
Jordy Rose722f5582010-08-16 07:51:42 +0000960
Jordy Rosefb5e8c22011-06-04 01:50:25 +0000961 if (!state)
962 return;
Lenny Maiorani79d74142011-03-31 21:36:53 +0000963
Jordy Rosefb5e8c22011-06-04 01:50:25 +0000964 // If this is mempcpy, get the byte after the last byte copied and
965 // bind the expr.
966 if (IsMempcpy) {
David Blaikie2fdacbc2013-02-20 05:52:05 +0000967 loc::MemRegionVal destRegVal = destVal.castAs<loc::MemRegionVal>();
Jordy Rosefb5e8c22011-06-04 01:50:25 +0000968
969 // Get the length to copy.
David Blaikie05785d12013-02-20 22:23:23 +0000970 if (Optional<NonLoc> lenValNonLoc = sizeVal.getAs<NonLoc>()) {
Jordy Rosefb5e8c22011-06-04 01:50:25 +0000971 // Get the byte after the last byte copied.
Anna Zaks2d2f1372014-10-03 21:48:54 +0000972 SValBuilder &SvalBuilder = C.getSValBuilder();
973 ASTContext &Ctx = SvalBuilder.getContext();
974 QualType CharPtrTy = Ctx.getPointerType(Ctx.CharTy);
975 loc::MemRegionVal DestRegCharVal = SvalBuilder.evalCast(destRegVal,
976 CharPtrTy, Dest->getType()).castAs<loc::MemRegionVal>();
Jordy Rosefb5e8c22011-06-04 01:50:25 +0000977 SVal lastElement = C.getSValBuilder().evalBinOpLN(state, BO_Add,
Anna Zaks2d2f1372014-10-03 21:48:54 +0000978 DestRegCharVal,
Jordy Rosefb5e8c22011-06-04 01:50:25 +0000979 *lenValNonLoc,
980 Dest->getType());
981
982 // The byte after the last byte copied is the return value.
Ted Kremenek632e3b72012-01-06 22:09:28 +0000983 state = state->BindExpr(CE, LCtx, lastElement);
Jordy Rose097c5392011-06-04 01:47:27 +0000984 } else {
Jordy Rosefb5e8c22011-06-04 01:50:25 +0000985 // If we don't know how much we copied, we can at least
986 // conjure a return value for later.
Craig Topper0dbb7832014-05-27 02:45:47 +0000987 SVal result = C.getSValBuilder().conjureSymbolVal(nullptr, CE, LCtx,
Ted Kremenekd94854a2012-08-22 06:26:15 +0000988 C.blockCount());
Ted Kremenek632e3b72012-01-06 22:09:28 +0000989 state = state->BindExpr(CE, LCtx, result);
Lenny Maiorani79d74142011-03-31 21:36:53 +0000990 }
991
Jordy Rosefb5e8c22011-06-04 01:50:25 +0000992 } else {
993 // All other copies return the destination buffer.
994 // (Well, bcopy() has a void return type, but this won't hurt.)
Ted Kremenek632e3b72012-01-06 22:09:28 +0000995 state = state->BindExpr(CE, LCtx, destVal);
Jordy Rose722f5582010-08-16 07:51:42 +0000996 }
Jordy Rosefb5e8c22011-06-04 01:50:25 +0000997
Anton Yartsev968c60a2013-11-17 09:18:48 +0000998 // Invalidate the destination (regular invalidation without pointer-escaping
999 // the address of the top-level region).
Jordy Rosefb5e8c22011-06-04 01:50:25 +00001000 // FIXME: Even if we can't perfectly model the copy, we should see if we
1001 // can use LazyCompoundVals to copy the source values into the destination.
1002 // This would probably remove any existing bindings past the end of the
1003 // copied region, but that's still an improvement over blank invalidation.
Anton Yartsev968c60a2013-11-17 09:18:48 +00001004 state = InvalidateBuffer(C, state, Dest, C.getSVal(Dest),
1005 /*IsSourceBuffer*/false);
1006
1007 // Invalidate the source (const-invalidation without const-pointer-escaping
1008 // the address of the top-level region).
1009 state = InvalidateBuffer(C, state, Source, C.getSVal(Source),
1010 /*IsSourceBuffer*/true);
1011
Anna Zaksda4c8d62011-10-26 21:06:34 +00001012 C.addTransition(state);
Jordy Rosed5d2e502010-07-08 23:57:29 +00001013 }
1014}
1015
1016
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00001017void CStringChecker::evalMemcpy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaksb508d292012-04-10 23:41:11 +00001018 if (CE->getNumArgs() < 3)
1019 return;
1020
Jordy Rose134a2362010-07-06 23:11:01 +00001021 // void *memcpy(void *restrict dst, const void *restrict src, size_t n);
Jordy Rose134a2362010-07-06 23:11:01 +00001022 // The return value is the address of the destination buffer.
Jordy Rosed5d2e502010-07-08 23:57:29 +00001023 const Expr *Dest = CE->getArg(0);
Ted Kremenek49b1e382012-01-26 21:29:00 +00001024 ProgramStateRef state = C.getState();
Jordy Rose097c5392011-06-04 01:47:27 +00001025
Lenny Maiorani79d74142011-03-31 21:36:53 +00001026 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1), true);
1027}
1028
1029void CStringChecker::evalMempcpy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaksb508d292012-04-10 23:41:11 +00001030 if (CE->getNumArgs() < 3)
1031 return;
1032
Lenny Maiorani79d74142011-03-31 21:36:53 +00001033 // void *mempcpy(void *restrict dst, const void *restrict src, size_t n);
1034 // The return value is a pointer to the byte following the last written byte.
1035 const Expr *Dest = CE->getArg(0);
Ted Kremenek49b1e382012-01-26 21:29:00 +00001036 ProgramStateRef state = C.getState();
Lenny Maiorani79d74142011-03-31 21:36:53 +00001037
1038 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1), true, true);
Jordy Rose134a2362010-07-06 23:11:01 +00001039}
1040
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00001041void CStringChecker::evalMemmove(CheckerContext &C, const CallExpr *CE) const {
Anna Zaksb508d292012-04-10 23:41:11 +00001042 if (CE->getNumArgs() < 3)
1043 return;
1044
Jordy Rosed5d2e502010-07-08 23:57:29 +00001045 // void *memmove(void *dst, const void *src, size_t n);
1046 // The return value is the address of the destination buffer.
1047 const Expr *Dest = CE->getArg(0);
Ted Kremenek49b1e382012-01-26 21:29:00 +00001048 ProgramStateRef state = C.getState();
Jordy Rose097c5392011-06-04 01:47:27 +00001049
Lenny Maiorani79d74142011-03-31 21:36:53 +00001050 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1));
Jordy Rosed5d2e502010-07-08 23:57:29 +00001051}
1052
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00001053void CStringChecker::evalBcopy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaksb508d292012-04-10 23:41:11 +00001054 if (CE->getNumArgs() < 3)
1055 return;
1056
Jordy Rosed5d2e502010-07-08 23:57:29 +00001057 // void bcopy(const void *src, void *dst, size_t n);
Lenny Maiorani79d74142011-03-31 21:36:53 +00001058 evalCopyCommon(C, CE, C.getState(),
1059 CE->getArg(2), CE->getArg(1), CE->getArg(0));
Jordy Rosed5d2e502010-07-08 23:57:29 +00001060}
1061
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00001062void CStringChecker::evalMemcmp(CheckerContext &C, const CallExpr *CE) const {
Anna Zaksb508d292012-04-10 23:41:11 +00001063 if (CE->getNumArgs() < 3)
1064 return;
1065
Jordy Rose65136fb2010-07-07 08:15:01 +00001066 // int memcmp(const void *s1, const void *s2, size_t n);
Jordy Rosedceb0cf2011-06-20 02:06:40 +00001067 CurrentFunctionDescription = "memory comparison function";
1068
Jordy Rose65136fb2010-07-07 08:15:01 +00001069 const Expr *Left = CE->getArg(0);
1070 const Expr *Right = CE->getArg(1);
1071 const Expr *Size = CE->getArg(2);
1072
Ted Kremenek49b1e382012-01-26 21:29:00 +00001073 ProgramStateRef state = C.getState();
Ted Kremenek90af9092010-12-02 07:49:45 +00001074 SValBuilder &svalBuilder = C.getSValBuilder();
Jordy Rose65136fb2010-07-07 08:15:01 +00001075
Jordy Rosed5d2e502010-07-08 23:57:29 +00001076 // See if the size argument is zero.
Ted Kremenek632e3b72012-01-06 22:09:28 +00001077 const LocationContext *LCtx = C.getLocationContext();
1078 SVal sizeVal = state->getSVal(Size, LCtx);
Ted Kremenek90af9092010-12-02 07:49:45 +00001079 QualType sizeTy = Size->getType();
Jordy Rose65136fb2010-07-07 08:15:01 +00001080
Ted Kremenek49b1e382012-01-26 21:29:00 +00001081 ProgramStateRef stateZeroSize, stateNonZeroSize;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001082 std::tie(stateZeroSize, stateNonZeroSize) =
Ted Kremenek90af9092010-12-02 07:49:45 +00001083 assumeZero(C, state, sizeVal, sizeTy);
Jordy Rose65136fb2010-07-07 08:15:01 +00001084
Jordy Rosed5d2e502010-07-08 23:57:29 +00001085 // If the size can be zero, the result will be 0 in that case, and we don't
1086 // have to check either of the buffers.
Ted Kremenek90af9092010-12-02 07:49:45 +00001087 if (stateZeroSize) {
1088 state = stateZeroSize;
Ted Kremenek632e3b72012-01-06 22:09:28 +00001089 state = state->BindExpr(CE, LCtx,
1090 svalBuilder.makeZeroVal(CE->getType()));
Anna Zaksda4c8d62011-10-26 21:06:34 +00001091 C.addTransition(state);
Jordy Rose65136fb2010-07-07 08:15:01 +00001092 }
1093
Jordy Rosed5d2e502010-07-08 23:57:29 +00001094 // If the size can be nonzero, we have to check the other arguments.
Ted Kremenek90af9092010-12-02 07:49:45 +00001095 if (stateNonZeroSize) {
1096 state = stateNonZeroSize;
Jordy Rosed5d2e502010-07-08 23:57:29 +00001097 // If we know the two buffers are the same, we know the result is 0.
1098 // First, get the two buffers' addresses. Another checker will have already
1099 // made sure they're not undefined.
Ted Kremenek632e3b72012-01-06 22:09:28 +00001100 DefinedOrUnknownSVal LV =
David Blaikie2fdacbc2013-02-20 05:52:05 +00001101 state->getSVal(Left, LCtx).castAs<DefinedOrUnknownSVal>();
Ted Kremenek632e3b72012-01-06 22:09:28 +00001102 DefinedOrUnknownSVal RV =
David Blaikie2fdacbc2013-02-20 05:52:05 +00001103 state->getSVal(Right, LCtx).castAs<DefinedOrUnknownSVal>();
Jordy Rose65136fb2010-07-07 08:15:01 +00001104
Jordy Rosed5d2e502010-07-08 23:57:29 +00001105 // See if they are the same.
Ted Kremenek90af9092010-12-02 07:49:45 +00001106 DefinedOrUnknownSVal SameBuf = svalBuilder.evalEQ(state, LV, RV);
Ted Kremenek49b1e382012-01-26 21:29:00 +00001107 ProgramStateRef StSameBuf, StNotSameBuf;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001108 std::tie(StSameBuf, StNotSameBuf) = state->assume(SameBuf);
Jordy Rosed5d2e502010-07-08 23:57:29 +00001109
Jordy Rose455bd582011-06-16 05:51:02 +00001110 // If the two arguments might be the same buffer, we know the result is 0,
Jordy Rosed5d2e502010-07-08 23:57:29 +00001111 // and we only need to check one size.
1112 if (StSameBuf) {
1113 state = StSameBuf;
1114 state = CheckBufferAccess(C, state, Size, Left);
1115 if (state) {
Ted Kremenek632e3b72012-01-06 22:09:28 +00001116 state = StSameBuf->BindExpr(CE, LCtx,
1117 svalBuilder.makeZeroVal(CE->getType()));
Anna Zaksda4c8d62011-10-26 21:06:34 +00001118 C.addTransition(state);
Jordy Rosed5d2e502010-07-08 23:57:29 +00001119 }
1120 }
1121
1122 // If the two arguments might be different buffers, we have to check the
1123 // size of both of them.
1124 if (StNotSameBuf) {
1125 state = StNotSameBuf;
1126 state = CheckBufferAccess(C, state, Size, Left, Right);
1127 if (state) {
1128 // The return value is the comparison result, which we don't know.
Craig Topper0dbb7832014-05-27 02:45:47 +00001129 SVal CmpV = svalBuilder.conjureSymbolVal(nullptr, CE, LCtx,
1130 C.blockCount());
Ted Kremenek632e3b72012-01-06 22:09:28 +00001131 state = state->BindExpr(CE, LCtx, CmpV);
Anna Zaksda4c8d62011-10-26 21:06:34 +00001132 C.addTransition(state);
Jordy Rosed5d2e502010-07-08 23:57:29 +00001133 }
1134 }
1135 }
Jordy Rose65136fb2010-07-07 08:15:01 +00001136}
1137
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00001138void CStringChecker::evalstrLength(CheckerContext &C,
1139 const CallExpr *CE) const {
Anna Zaksb508d292012-04-10 23:41:11 +00001140 if (CE->getNumArgs() < 1)
1141 return;
1142
Jordy Roseb052e8f2010-07-27 01:37:31 +00001143 // size_t strlen(const char *s);
Ted Kremenek280a01f2011-02-22 04:55:05 +00001144 evalstrLengthCommon(C, CE, /* IsStrnlen = */ false);
1145}
1146
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00001147void CStringChecker::evalstrnLength(CheckerContext &C,
1148 const CallExpr *CE) const {
Anna Zaksb508d292012-04-10 23:41:11 +00001149 if (CE->getNumArgs() < 2)
1150 return;
1151
Ted Kremenek280a01f2011-02-22 04:55:05 +00001152 // size_t strnlen(const char *s, size_t maxlen);
1153 evalstrLengthCommon(C, CE, /* IsStrnlen = */ true);
1154}
1155
1156void CStringChecker::evalstrLengthCommon(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00001157 bool IsStrnlen) const {
Jordy Rosedceb0cf2011-06-20 02:06:40 +00001158 CurrentFunctionDescription = "string length function";
Ted Kremenek49b1e382012-01-26 21:29:00 +00001159 ProgramStateRef state = C.getState();
Ted Kremenek632e3b72012-01-06 22:09:28 +00001160 const LocationContext *LCtx = C.getLocationContext();
Jordy Rosed3592892011-06-14 01:15:31 +00001161
1162 if (IsStrnlen) {
1163 const Expr *maxlenExpr = CE->getArg(1);
Ted Kremenek632e3b72012-01-06 22:09:28 +00001164 SVal maxlenVal = state->getSVal(maxlenExpr, LCtx);
Jordy Rosed3592892011-06-14 01:15:31 +00001165
Ted Kremenek49b1e382012-01-26 21:29:00 +00001166 ProgramStateRef stateZeroSize, stateNonZeroSize;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001167 std::tie(stateZeroSize, stateNonZeroSize) =
Jordy Rosed3592892011-06-14 01:15:31 +00001168 assumeZero(C, state, maxlenVal, maxlenExpr->getType());
1169
1170 // If the size can be zero, the result will be 0 in that case, and we don't
1171 // have to check the string itself.
1172 if (stateZeroSize) {
1173 SVal zero = C.getSValBuilder().makeZeroVal(CE->getType());
Ted Kremenek632e3b72012-01-06 22:09:28 +00001174 stateZeroSize = stateZeroSize->BindExpr(CE, LCtx, zero);
Anna Zaksda4c8d62011-10-26 21:06:34 +00001175 C.addTransition(stateZeroSize);
Jordy Rosed3592892011-06-14 01:15:31 +00001176 }
1177
1178 // If the size is GUARANTEED to be zero, we're done!
1179 if (!stateNonZeroSize)
1180 return;
1181
1182 // Otherwise, record the assumption that the size is nonzero.
1183 state = stateNonZeroSize;
1184 }
1185
1186 // Check that the string argument is non-null.
Jordy Roseb052e8f2010-07-27 01:37:31 +00001187 const Expr *Arg = CE->getArg(0);
Ted Kremenek632e3b72012-01-06 22:09:28 +00001188 SVal ArgVal = state->getSVal(Arg, LCtx);
Jordy Roseb052e8f2010-07-27 01:37:31 +00001189
Ted Kremenek90af9092010-12-02 07:49:45 +00001190 state = checkNonNull(C, state, Arg, ArgVal);
Jordy Roseb052e8f2010-07-27 01:37:31 +00001191
Jordy Rose45d8c122011-06-14 01:26:48 +00001192 if (!state)
1193 return;
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001194
Jordy Rose45d8c122011-06-14 01:26:48 +00001195 SVal strLength = getCStringLength(C, state, Arg, ArgVal);
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001196
Jordy Rose45d8c122011-06-14 01:26:48 +00001197 // If the argument isn't a valid C string, there's no valid state to
1198 // transition to.
1199 if (strLength.isUndef())
1200 return;
Jordy Rosed3592892011-06-14 01:15:31 +00001201
Jordy Rose45d8c122011-06-14 01:26:48 +00001202 DefinedOrUnknownSVal result = UnknownVal();
Jordy Rosed3592892011-06-14 01:15:31 +00001203
Jordy Rose45d8c122011-06-14 01:26:48 +00001204 // If the check is for strnlen() then bind the return value to no more than
1205 // the maxlen value.
1206 if (IsStrnlen) {
Jordy Rose0585a612011-06-16 05:56:50 +00001207 QualType cmpTy = C.getSValBuilder().getConditionType();
Jordy Rosed3592892011-06-14 01:15:31 +00001208
Jordy Rose45d8c122011-06-14 01:26:48 +00001209 // It's a little unfortunate to be getting this again,
1210 // but it's not that expensive...
1211 const Expr *maxlenExpr = CE->getArg(1);
Ted Kremenek632e3b72012-01-06 22:09:28 +00001212 SVal maxlenVal = state->getSVal(maxlenExpr, LCtx);
Ted Kremenek280a01f2011-02-22 04:55:05 +00001213
David Blaikie05785d12013-02-20 22:23:23 +00001214 Optional<NonLoc> strLengthNL = strLength.getAs<NonLoc>();
1215 Optional<NonLoc> maxlenValNL = maxlenVal.getAs<NonLoc>();
Ted Kremenek280a01f2011-02-22 04:55:05 +00001216
Jordy Rose45d8c122011-06-14 01:26:48 +00001217 if (strLengthNL && maxlenValNL) {
Ted Kremenek49b1e382012-01-26 21:29:00 +00001218 ProgramStateRef stateStringTooLong, stateStringNotTooLong;
Jordy Rosed3592892011-06-14 01:15:31 +00001219
Jordy Rose45d8c122011-06-14 01:26:48 +00001220 // Check if the strLength is greater than the maxlen.
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001221 std::tie(stateStringTooLong, stateStringNotTooLong) = state->assume(
1222 C.getSValBuilder()
1223 .evalBinOpNN(state, BO_GT, *strLengthNL, *maxlenValNL, cmpTy)
1224 .castAs<DefinedOrUnknownSVal>());
Jordy Rosed3592892011-06-14 01:15:31 +00001225
Jordy Rose45d8c122011-06-14 01:26:48 +00001226 if (stateStringTooLong && !stateStringNotTooLong) {
1227 // If the string is longer than maxlen, return maxlen.
1228 result = *maxlenValNL;
1229 } else if (stateStringNotTooLong && !stateStringTooLong) {
1230 // If the string is shorter than maxlen, return its length.
1231 result = *strLengthNL;
Ted Kremenek280a01f2011-02-22 04:55:05 +00001232 }
1233 }
1234
Jordy Rose45d8c122011-06-14 01:26:48 +00001235 if (result.isUnknown()) {
1236 // If we don't have enough information for a comparison, there's
1237 // no guarantee the full string length will actually be returned.
1238 // All we know is the return value is the min of the string length
1239 // and the limit. This is better than nothing.
Craig Topper0dbb7832014-05-27 02:45:47 +00001240 result = C.getSValBuilder().conjureSymbolVal(nullptr, CE, LCtx,
1241 C.blockCount());
David Blaikie2fdacbc2013-02-20 05:52:05 +00001242 NonLoc resultNL = result.castAs<NonLoc>();
Jordy Rose45d8c122011-06-14 01:26:48 +00001243
1244 if (strLengthNL) {
David Blaikie2fdacbc2013-02-20 05:52:05 +00001245 state = state->assume(C.getSValBuilder().evalBinOpNN(
1246 state, BO_LE, resultNL, *strLengthNL, cmpTy)
1247 .castAs<DefinedOrUnknownSVal>(), true);
Jordy Rose45d8c122011-06-14 01:26:48 +00001248 }
1249
1250 if (maxlenValNL) {
David Blaikie2fdacbc2013-02-20 05:52:05 +00001251 state = state->assume(C.getSValBuilder().evalBinOpNN(
1252 state, BO_LE, resultNL, *maxlenValNL, cmpTy)
1253 .castAs<DefinedOrUnknownSVal>(), true);
Jordy Rose45d8c122011-06-14 01:26:48 +00001254 }
1255 }
1256
1257 } else {
1258 // This is a plain strlen(), not strnlen().
David Blaikie2fdacbc2013-02-20 05:52:05 +00001259 result = strLength.castAs<DefinedOrUnknownSVal>();
Jordy Rose45d8c122011-06-14 01:26:48 +00001260
1261 // If we don't know the length of the string, conjure a return
1262 // value, so it can be used in constraints, at least.
1263 if (result.isUnknown()) {
Craig Topper0dbb7832014-05-27 02:45:47 +00001264 result = C.getSValBuilder().conjureSymbolVal(nullptr, CE, LCtx,
1265 C.blockCount());
Jordy Rose45d8c122011-06-14 01:26:48 +00001266 }
Jordy Roseb052e8f2010-07-27 01:37:31 +00001267 }
Jordy Rose45d8c122011-06-14 01:26:48 +00001268
1269 // Bind the return value.
1270 assert(!result.isUnknown() && "Should have conjured a value by now");
Ted Kremenek632e3b72012-01-06 22:09:28 +00001271 state = state->BindExpr(CE, LCtx, result);
Anna Zaksda4c8d62011-10-26 21:06:34 +00001272 C.addTransition(state);
Jordy Roseb052e8f2010-07-27 01:37:31 +00001273}
1274
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00001275void CStringChecker::evalStrcpy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaksb508d292012-04-10 23:41:11 +00001276 if (CE->getNumArgs() < 2)
1277 return;
1278
Jordy Rose722f5582010-08-16 07:51:42 +00001279 // char *strcpy(char *restrict dst, const char *restrict src);
Lenny Maiorani467dbd52011-04-09 15:12:58 +00001280 evalStrcpyCommon(C, CE,
1281 /* returnEnd = */ false,
1282 /* isBounded = */ false,
1283 /* isAppending = */ false);
Ted Kremenekfb1a79a2011-02-22 04:58:34 +00001284}
1285
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00001286void CStringChecker::evalStrncpy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaksb508d292012-04-10 23:41:11 +00001287 if (CE->getNumArgs() < 3)
1288 return;
1289
Jordy Rose4451cd42011-06-04 00:05:23 +00001290 // char *strncpy(char *restrict dst, const char *restrict src, size_t n);
Lenny Maiorani467dbd52011-04-09 15:12:58 +00001291 evalStrcpyCommon(C, CE,
1292 /* returnEnd = */ false,
1293 /* isBounded = */ true,
1294 /* isAppending = */ false);
Jordy Rose722f5582010-08-16 07:51:42 +00001295}
1296
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00001297void CStringChecker::evalStpcpy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaksb508d292012-04-10 23:41:11 +00001298 if (CE->getNumArgs() < 2)
1299 return;
1300
Jordy Rose722f5582010-08-16 07:51:42 +00001301 // char *stpcpy(char *restrict dst, const char *restrict src);
Lenny Maiorani467dbd52011-04-09 15:12:58 +00001302 evalStrcpyCommon(C, CE,
1303 /* returnEnd = */ true,
1304 /* isBounded = */ false,
1305 /* isAppending = */ false);
1306}
1307
1308void CStringChecker::evalStrcat(CheckerContext &C, const CallExpr *CE) const {
Anna Zaksb508d292012-04-10 23:41:11 +00001309 if (CE->getNumArgs() < 2)
1310 return;
1311
Lenny Maiorani467dbd52011-04-09 15:12:58 +00001312 //char *strcat(char *restrict s1, const char *restrict s2);
1313 evalStrcpyCommon(C, CE,
1314 /* returnEnd = */ false,
1315 /* isBounded = */ false,
1316 /* isAppending = */ true);
1317}
1318
1319void CStringChecker::evalStrncat(CheckerContext &C, const CallExpr *CE) const {
Anna Zaksb508d292012-04-10 23:41:11 +00001320 if (CE->getNumArgs() < 3)
1321 return;
1322
Lenny Maiorani467dbd52011-04-09 15:12:58 +00001323 //char *strncat(char *restrict s1, const char *restrict s2, size_t n);
1324 evalStrcpyCommon(C, CE,
1325 /* returnEnd = */ false,
1326 /* isBounded = */ true,
1327 /* isAppending = */ true);
Jordy Rose722f5582010-08-16 07:51:42 +00001328}
1329
Ted Kremenekdc891422010-12-01 21:57:22 +00001330void CStringChecker::evalStrcpyCommon(CheckerContext &C, const CallExpr *CE,
Lenny Maiorani467dbd52011-04-09 15:12:58 +00001331 bool returnEnd, bool isBounded,
1332 bool isAppending) const {
Jordy Rosedceb0cf2011-06-20 02:06:40 +00001333 CurrentFunctionDescription = "string copy function";
Ted Kremenek49b1e382012-01-26 21:29:00 +00001334 ProgramStateRef state = C.getState();
Ted Kremenek632e3b72012-01-06 22:09:28 +00001335 const LocationContext *LCtx = C.getLocationContext();
Jordy Rose722f5582010-08-16 07:51:42 +00001336
Lenny Maiorani467dbd52011-04-09 15:12:58 +00001337 // Check that the destination is non-null.
Jordy Rose722f5582010-08-16 07:51:42 +00001338 const Expr *Dst = CE->getArg(0);
Ted Kremenek632e3b72012-01-06 22:09:28 +00001339 SVal DstVal = state->getSVal(Dst, LCtx);
Jordy Rose722f5582010-08-16 07:51:42 +00001340
Ted Kremenek90af9092010-12-02 07:49:45 +00001341 state = checkNonNull(C, state, Dst, DstVal);
Jordy Rose722f5582010-08-16 07:51:42 +00001342 if (!state)
1343 return;
1344
1345 // Check that the source is non-null.
Ted Kremenek90af9092010-12-02 07:49:45 +00001346 const Expr *srcExpr = CE->getArg(1);
Ted Kremenek632e3b72012-01-06 22:09:28 +00001347 SVal srcVal = state->getSVal(srcExpr, LCtx);
Ted Kremenek90af9092010-12-02 07:49:45 +00001348 state = checkNonNull(C, state, srcExpr, srcVal);
Jordy Rose722f5582010-08-16 07:51:42 +00001349 if (!state)
1350 return;
1351
1352 // Get the string length of the source.
Ted Kremenek90af9092010-12-02 07:49:45 +00001353 SVal strLength = getCStringLength(C, state, srcExpr, srcVal);
Jordy Rose722f5582010-08-16 07:51:42 +00001354
1355 // If the source isn't a valid C string, give up.
Ted Kremenek90af9092010-12-02 07:49:45 +00001356 if (strLength.isUndef())
Jordy Rose722f5582010-08-16 07:51:42 +00001357 return;
1358
Jordy Rose634c12d2011-06-15 05:52:56 +00001359 SValBuilder &svalBuilder = C.getSValBuilder();
1360 QualType cmpTy = svalBuilder.getConditionType();
Jordy Roseb41f7c52011-06-20 21:55:40 +00001361 QualType sizeTy = svalBuilder.getContext().getSizeType();
Jordy Rose634c12d2011-06-15 05:52:56 +00001362
Jordy Roseb41f7c52011-06-20 21:55:40 +00001363 // These two values allow checking two kinds of errors:
1364 // - actual overflows caused by a source that doesn't fit in the destination
1365 // - potential overflows caused by a bound that could exceed the destination
Jordy Rose634c12d2011-06-15 05:52:56 +00001366 SVal amountCopied = UnknownVal();
Jordy Roseb41f7c52011-06-20 21:55:40 +00001367 SVal maxLastElementIndex = UnknownVal();
Craig Topper0dbb7832014-05-27 02:45:47 +00001368 const char *boundWarning = nullptr;
Jordy Rose634c12d2011-06-15 05:52:56 +00001369
Lenny Maiorani467dbd52011-04-09 15:12:58 +00001370 // If the function is strncpy, strncat, etc... it is bounded.
1371 if (isBounded) {
1372 // Get the max number of characters to copy.
Ted Kremenekfb1a79a2011-02-22 04:58:34 +00001373 const Expr *lenExpr = CE->getArg(2);
Ted Kremenek632e3b72012-01-06 22:09:28 +00001374 SVal lenVal = state->getSVal(lenExpr, LCtx);
Ted Kremenekfb1a79a2011-02-22 04:58:34 +00001375
Jordy Rose634c12d2011-06-15 05:52:56 +00001376 // Protect against misdeclared strncpy().
Jordy Roseb41f7c52011-06-20 21:55:40 +00001377 lenVal = svalBuilder.evalCast(lenVal, sizeTy, lenExpr->getType());
Jordy Rose634c12d2011-06-15 05:52:56 +00001378
David Blaikie05785d12013-02-20 22:23:23 +00001379 Optional<NonLoc> strLengthNL = strLength.getAs<NonLoc>();
1380 Optional<NonLoc> lenValNL = lenVal.getAs<NonLoc>();
Ted Kremenekfb1a79a2011-02-22 04:58:34 +00001381
Jordy Rose634c12d2011-06-15 05:52:56 +00001382 // If we know both values, we might be able to figure out how much
1383 // we're copying.
1384 if (strLengthNL && lenValNL) {
Ted Kremenek49b1e382012-01-26 21:29:00 +00001385 ProgramStateRef stateSourceTooLong, stateSourceNotTooLong;
Ted Kremenekfb1a79a2011-02-22 04:58:34 +00001386
Jordy Rose634c12d2011-06-15 05:52:56 +00001387 // Check if the max number to copy is less than the length of the src.
Jordy Roseb41f7c52011-06-20 21:55:40 +00001388 // If the bound is equal to the source length, strncpy won't null-
1389 // terminate the result!
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001390 std::tie(stateSourceTooLong, stateSourceNotTooLong) = state->assume(
David Blaikie2fdacbc2013-02-20 05:52:05 +00001391 svalBuilder.evalBinOpNN(state, BO_GE, *strLengthNL, *lenValNL, cmpTy)
1392 .castAs<DefinedOrUnknownSVal>());
Jordy Rose634c12d2011-06-15 05:52:56 +00001393
1394 if (stateSourceTooLong && !stateSourceNotTooLong) {
1395 // Max number to copy is less than the length of the src, so the actual
1396 // strLength copied is the max number arg.
1397 state = stateSourceTooLong;
1398 amountCopied = lenVal;
1399
1400 } else if (!stateSourceTooLong && stateSourceNotTooLong) {
1401 // The source buffer entirely fits in the bound.
1402 state = stateSourceNotTooLong;
1403 amountCopied = strLength;
1404 }
1405 }
1406
Jordy Rose328deee2011-06-20 03:49:16 +00001407 // We still want to know if the bound is known to be too large.
Jordy Roseb41f7c52011-06-20 21:55:40 +00001408 if (lenValNL) {
1409 if (isAppending) {
1410 // For strncat, the check is strlen(dst) + lenVal < sizeof(dst)
1411
1412 // Get the string length of the destination. If the destination is
1413 // memory that can't have a string length, we shouldn't be copying
1414 // into it anyway.
1415 SVal dstStrLength = getCStringLength(C, state, Dst, DstVal);
1416 if (dstStrLength.isUndef())
1417 return;
1418
David Blaikie05785d12013-02-20 22:23:23 +00001419 if (Optional<NonLoc> dstStrLengthNL = dstStrLength.getAs<NonLoc>()) {
Jordy Roseb41f7c52011-06-20 21:55:40 +00001420 maxLastElementIndex = svalBuilder.evalBinOpNN(state, BO_Add,
1421 *lenValNL,
1422 *dstStrLengthNL,
1423 sizeTy);
1424 boundWarning = "Size argument is greater than the free space in the "
1425 "destination buffer";
1426 }
1427
1428 } else {
1429 // For strncpy, this is just checking that lenVal <= sizeof(dst)
1430 // (Yes, strncpy and strncat differ in how they treat termination.
1431 // strncat ALWAYS terminates, but strncpy doesn't.)
Jordy Rose459d5f62012-05-14 17:58:35 +00001432
1433 // We need a special case for when the copy size is zero, in which
1434 // case strncpy will do no work at all. Our bounds check uses n-1
1435 // as the last element accessed, so n == 0 is problematic.
1436 ProgramStateRef StateZeroSize, StateNonZeroSize;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001437 std::tie(StateZeroSize, StateNonZeroSize) =
Jordy Rose459d5f62012-05-14 17:58:35 +00001438 assumeZero(C, state, *lenValNL, sizeTy);
1439
1440 // If the size is known to be zero, we're done.
1441 if (StateZeroSize && !StateNonZeroSize) {
1442 StateZeroSize = StateZeroSize->BindExpr(CE, LCtx, DstVal);
1443 C.addTransition(StateZeroSize);
1444 return;
1445 }
1446
1447 // Otherwise, go ahead and figure out the last element we'll touch.
1448 // We don't record the non-zero assumption here because we can't
1449 // be sure. We won't warn on a possible zero.
David Blaikie2fdacbc2013-02-20 05:52:05 +00001450 NonLoc one = svalBuilder.makeIntVal(1, sizeTy).castAs<NonLoc>();
Jordy Roseb41f7c52011-06-20 21:55:40 +00001451 maxLastElementIndex = svalBuilder.evalBinOpNN(state, BO_Sub, *lenValNL,
1452 one, sizeTy);
1453 boundWarning = "Size argument is greater than the length of the "
1454 "destination buffer";
1455 }
1456 }
Jordy Rose328deee2011-06-20 03:49:16 +00001457
Jordy Rose634c12d2011-06-15 05:52:56 +00001458 // If we couldn't pin down the copy length, at least bound it.
Jordy Roseb41f7c52011-06-20 21:55:40 +00001459 // FIXME: We should actually run this code path for append as well, but
1460 // right now it creates problems with constraints (since we can end up
1461 // trying to pass constraints from symbol to symbol).
1462 if (amountCopied.isUnknown() && !isAppending) {
Jordy Rose634c12d2011-06-15 05:52:56 +00001463 // Try to get a "hypothetical" string length symbol, which we can later
1464 // set as a real value if that turns out to be the case.
1465 amountCopied = getCStringLength(C, state, lenExpr, srcVal, true);
1466 assert(!amountCopied.isUndef());
1467
David Blaikie05785d12013-02-20 22:23:23 +00001468 if (Optional<NonLoc> amountCopiedNL = amountCopied.getAs<NonLoc>()) {
Jordy Rose634c12d2011-06-15 05:52:56 +00001469 if (lenValNL) {
1470 // amountCopied <= lenVal
1471 SVal copiedLessThanBound = svalBuilder.evalBinOpNN(state, BO_LE,
1472 *amountCopiedNL,
1473 *lenValNL,
1474 cmpTy);
David Blaikie2fdacbc2013-02-20 05:52:05 +00001475 state = state->assume(
1476 copiedLessThanBound.castAs<DefinedOrUnknownSVal>(), true);
Jordy Rose634c12d2011-06-15 05:52:56 +00001477 if (!state)
1478 return;
1479 }
1480
1481 if (strLengthNL) {
1482 // amountCopied <= strlen(source)
1483 SVal copiedLessThanSrc = svalBuilder.evalBinOpNN(state, BO_LE,
1484 *amountCopiedNL,
1485 *strLengthNL,
1486 cmpTy);
David Blaikie2fdacbc2013-02-20 05:52:05 +00001487 state = state->assume(
1488 copiedLessThanSrc.castAs<DefinedOrUnknownSVal>(), true);
Jordy Rose634c12d2011-06-15 05:52:56 +00001489 if (!state)
1490 return;
1491 }
1492 }
1493 }
1494
1495 } else {
1496 // The function isn't bounded. The amount copied should match the length
1497 // of the source buffer.
1498 amountCopied = strLength;
Ted Kremenekfb1a79a2011-02-22 04:58:34 +00001499 }
1500
Jordy Rose634c12d2011-06-15 05:52:56 +00001501 assert(state);
1502
1503 // This represents the number of characters copied into the destination
1504 // buffer. (It may not actually be the strlen if the destination buffer
1505 // is not terminated.)
1506 SVal finalStrLength = UnknownVal();
1507
Lenny Maiorani467dbd52011-04-09 15:12:58 +00001508 // If this is an appending function (strcat, strncat...) then set the
1509 // string length to strlen(src) + strlen(dst) since the buffer will
1510 // ultimately contain both.
1511 if (isAppending) {
Jordy Rose455bd582011-06-16 05:51:02 +00001512 // Get the string length of the destination. If the destination is memory
1513 // that can't have a string length, we shouldn't be copying into it anyway.
Lenny Maiorani467dbd52011-04-09 15:12:58 +00001514 SVal dstStrLength = getCStringLength(C, state, Dst, DstVal);
1515 if (dstStrLength.isUndef())
1516 return;
1517
David Blaikie05785d12013-02-20 22:23:23 +00001518 Optional<NonLoc> srcStrLengthNL = amountCopied.getAs<NonLoc>();
1519 Optional<NonLoc> dstStrLengthNL = dstStrLength.getAs<NonLoc>();
Lenny Maiorani467dbd52011-04-09 15:12:58 +00001520
Jordy Rose634c12d2011-06-15 05:52:56 +00001521 // If we know both string lengths, we might know the final string length.
1522 if (srcStrLengthNL && dstStrLengthNL) {
1523 // Make sure the two lengths together don't overflow a size_t.
1524 state = checkAdditionOverflow(C, state, *srcStrLengthNL, *dstStrLengthNL);
1525 if (!state)
1526 return;
Lenny Maiorani467dbd52011-04-09 15:12:58 +00001527
Jordy Rose634c12d2011-06-15 05:52:56 +00001528 finalStrLength = svalBuilder.evalBinOpNN(state, BO_Add, *srcStrLengthNL,
1529 *dstStrLengthNL, sizeTy);
1530 }
Lenny Maiorani467dbd52011-04-09 15:12:58 +00001531
Jordy Rose634c12d2011-06-15 05:52:56 +00001532 // If we couldn't get a single value for the final string length,
1533 // we can at least bound it by the individual lengths.
1534 if (finalStrLength.isUnknown()) {
1535 // Try to get a "hypothetical" string length symbol, which we can later
1536 // set as a real value if that turns out to be the case.
1537 finalStrLength = getCStringLength(C, state, CE, DstVal, true);
1538 assert(!finalStrLength.isUndef());
1539
David Blaikie05785d12013-02-20 22:23:23 +00001540 if (Optional<NonLoc> finalStrLengthNL = finalStrLength.getAs<NonLoc>()) {
Jordy Rose634c12d2011-06-15 05:52:56 +00001541 if (srcStrLengthNL) {
1542 // finalStrLength >= srcStrLength
1543 SVal sourceInResult = svalBuilder.evalBinOpNN(state, BO_GE,
1544 *finalStrLengthNL,
1545 *srcStrLengthNL,
1546 cmpTy);
David Blaikie2fdacbc2013-02-20 05:52:05 +00001547 state = state->assume(sourceInResult.castAs<DefinedOrUnknownSVal>(),
Jordy Rose634c12d2011-06-15 05:52:56 +00001548 true);
1549 if (!state)
1550 return;
1551 }
1552
1553 if (dstStrLengthNL) {
1554 // finalStrLength >= dstStrLength
1555 SVal destInResult = svalBuilder.evalBinOpNN(state, BO_GE,
1556 *finalStrLengthNL,
1557 *dstStrLengthNL,
1558 cmpTy);
David Blaikie2fdacbc2013-02-20 05:52:05 +00001559 state =
1560 state->assume(destInResult.castAs<DefinedOrUnknownSVal>(), true);
Jordy Rose634c12d2011-06-15 05:52:56 +00001561 if (!state)
1562 return;
1563 }
1564 }
1565 }
1566
1567 } else {
1568 // Otherwise, this is a copy-over function (strcpy, strncpy, ...), and
1569 // the final string length will match the input string length.
1570 finalStrLength = amountCopied;
Lenny Maiorani467dbd52011-04-09 15:12:58 +00001571 }
1572
Jordy Rose634c12d2011-06-15 05:52:56 +00001573 // The final result of the function will either be a pointer past the last
1574 // copied element, or a pointer to the start of the destination buffer.
Ted Kremenek90af9092010-12-02 07:49:45 +00001575 SVal Result = (returnEnd ? UnknownVal() : DstVal);
Jordy Rose722f5582010-08-16 07:51:42 +00001576
Jordy Rose634c12d2011-06-15 05:52:56 +00001577 assert(state);
1578
Jordy Rose722f5582010-08-16 07:51:42 +00001579 // If the destination is a MemRegion, try to check for a buffer overflow and
1580 // record the new string length.
David Blaikie05785d12013-02-20 22:23:23 +00001581 if (Optional<loc::MemRegionVal> dstRegVal =
David Blaikie2fdacbc2013-02-20 05:52:05 +00001582 DstVal.getAs<loc::MemRegionVal>()) {
Jordy Roseb41f7c52011-06-20 21:55:40 +00001583 QualType ptrTy = Dst->getType();
1584
1585 // If we have an exact value on a bounded copy, use that to check for
1586 // overflows, rather than our estimate about how much is actually copied.
1587 if (boundWarning) {
David Blaikie05785d12013-02-20 22:23:23 +00001588 if (Optional<NonLoc> maxLastNL = maxLastElementIndex.getAs<NonLoc>()) {
Jordy Roseb41f7c52011-06-20 21:55:40 +00001589 SVal maxLastElement = svalBuilder.evalBinOpLN(state, BO_Add, *dstRegVal,
1590 *maxLastNL, ptrTy);
1591 state = CheckLocation(C, state, CE->getArg(2), maxLastElement,
1592 boundWarning);
1593 if (!state)
1594 return;
1595 }
1596 }
1597
1598 // Then, if the final length is known...
David Blaikie05785d12013-02-20 22:23:23 +00001599 if (Optional<NonLoc> knownStrLength = finalStrLength.getAs<NonLoc>()) {
Jordy Rose634c12d2011-06-15 05:52:56 +00001600 SVal lastElement = svalBuilder.evalBinOpLN(state, BO_Add, *dstRegVal,
Jordy Roseb41f7c52011-06-20 21:55:40 +00001601 *knownStrLength, ptrTy);
Jordy Rose722f5582010-08-16 07:51:42 +00001602
Jordy Roseb41f7c52011-06-20 21:55:40 +00001603 // ...and we haven't checked the bound, we'll check the actual copy.
1604 if (!boundWarning) {
1605 const char * const warningMsg =
1606 "String copy function overflows destination buffer";
1607 state = CheckLocation(C, state, Dst, lastElement, warningMsg);
1608 if (!state)
1609 return;
1610 }
Jordy Rose722f5582010-08-16 07:51:42 +00001611
1612 // If this is a stpcpy-style copy, the last element is the return value.
Ted Kremenek90af9092010-12-02 07:49:45 +00001613 if (returnEnd)
1614 Result = lastElement;
Jordy Rose722f5582010-08-16 07:51:42 +00001615 }
1616
Anton Yartsev968c60a2013-11-17 09:18:48 +00001617 // Invalidate the destination (regular invalidation without pointer-escaping
1618 // the address of the top-level region). This must happen before we set the
1619 // C string length because invalidation will clear the length.
Jordy Rose722f5582010-08-16 07:51:42 +00001620 // FIXME: Even if we can't perfectly model the copy, we should see if we
1621 // can use LazyCompoundVals to copy the source values into the destination.
1622 // This would probably remove any existing bindings past the end of the
1623 // string, but that's still an improvement over blank invalidation.
Anton Yartsev968c60a2013-11-17 09:18:48 +00001624 state = InvalidateBuffer(C, state, Dst, *dstRegVal,
1625 /*IsSourceBuffer*/false);
1626
1627 // Invalidate the source (const-invalidation without const-pointer-escaping
1628 // the address of the top-level region).
1629 state = InvalidateBuffer(C, state, srcExpr, srcVal, /*IsSourceBuffer*/true);
Jordy Rose722f5582010-08-16 07:51:42 +00001630
Jordy Rose328deee2011-06-20 03:49:16 +00001631 // Set the C string length of the destination, if we know it.
Jordy Roseb41f7c52011-06-20 21:55:40 +00001632 if (isBounded && !isAppending) {
1633 // strncpy is annoying in that it doesn't guarantee to null-terminate
1634 // the result string. If the original string didn't fit entirely inside
1635 // the bound (including the null-terminator), we don't know how long the
1636 // result is.
1637 if (amountCopied != strLength)
1638 finalStrLength = UnknownVal();
1639 }
1640 state = setCStringLength(state, dstRegVal->getRegion(), finalStrLength);
Jordy Rose722f5582010-08-16 07:51:42 +00001641 }
1642
Jordy Rose634c12d2011-06-15 05:52:56 +00001643 assert(state);
1644
Jordy Rose722f5582010-08-16 07:51:42 +00001645 // If this is a stpcpy-style copy, but we were unable to check for a buffer
1646 // overflow, we still need a result. Conjure a return value.
Ted Kremenek90af9092010-12-02 07:49:45 +00001647 if (returnEnd && Result.isUnknown()) {
Craig Topper0dbb7832014-05-27 02:45:47 +00001648 Result = svalBuilder.conjureSymbolVal(nullptr, CE, LCtx, C.blockCount());
Jordy Rose722f5582010-08-16 07:51:42 +00001649 }
1650
1651 // Set the return value.
Ted Kremenek632e3b72012-01-06 22:09:28 +00001652 state = state->BindExpr(CE, LCtx, Result);
Anna Zaksda4c8d62011-10-26 21:06:34 +00001653 C.addTransition(state);
Jordy Rose722f5582010-08-16 07:51:42 +00001654}
1655
Lenny Maioranif3539ad2011-04-12 17:08:43 +00001656void CStringChecker::evalStrcmp(CheckerContext &C, const CallExpr *CE) const {
Anna Zaksb508d292012-04-10 23:41:11 +00001657 if (CE->getNumArgs() < 2)
1658 return;
1659
Jordy Rosec0263702011-06-16 07:13:34 +00001660 //int strcmp(const char *s1, const char *s2);
Lenny Maiorani4af23c82011-04-28 15:09:11 +00001661 evalStrcmpCommon(C, CE, /* isBounded = */ false, /* ignoreCase = */ false);
Lenny Maioranie553e402011-04-25 22:21:00 +00001662}
Lenny Maioranif3539ad2011-04-12 17:08:43 +00001663
Lenny Maioranie553e402011-04-25 22:21:00 +00001664void CStringChecker::evalStrncmp(CheckerContext &C, const CallExpr *CE) const {
Anna Zaksb508d292012-04-10 23:41:11 +00001665 if (CE->getNumArgs() < 3)
1666 return;
1667
Jordy Rosec0263702011-06-16 07:13:34 +00001668 //int strncmp(const char *s1, const char *s2, size_t n);
Lenny Maiorani4af23c82011-04-28 15:09:11 +00001669 evalStrcmpCommon(C, CE, /* isBounded = */ true, /* ignoreCase = */ false);
1670}
1671
1672void CStringChecker::evalStrcasecmp(CheckerContext &C,
1673 const CallExpr *CE) const {
Anna Zaksb508d292012-04-10 23:41:11 +00001674 if (CE->getNumArgs() < 2)
1675 return;
1676
Jordy Rosec0263702011-06-16 07:13:34 +00001677 //int strcasecmp(const char *s1, const char *s2);
Lenny Maiorani4af23c82011-04-28 15:09:11 +00001678 evalStrcmpCommon(C, CE, /* isBounded = */ false, /* ignoreCase = */ true);
Lenny Maioranie553e402011-04-25 22:21:00 +00001679}
1680
Lenny Maiorani0b510272011-05-02 19:05:49 +00001681void CStringChecker::evalStrncasecmp(CheckerContext &C,
1682 const CallExpr *CE) const {
Anna Zaksb508d292012-04-10 23:41:11 +00001683 if (CE->getNumArgs() < 3)
1684 return;
1685
Jordy Rosec0263702011-06-16 07:13:34 +00001686 //int strncasecmp(const char *s1, const char *s2, size_t n);
Lenny Maiorani0b510272011-05-02 19:05:49 +00001687 evalStrcmpCommon(C, CE, /* isBounded = */ true, /* ignoreCase = */ true);
1688}
1689
Lenny Maioranie553e402011-04-25 22:21:00 +00001690void CStringChecker::evalStrcmpCommon(CheckerContext &C, const CallExpr *CE,
Lenny Maiorani4af23c82011-04-28 15:09:11 +00001691 bool isBounded, bool ignoreCase) const {
Jordy Rosedceb0cf2011-06-20 02:06:40 +00001692 CurrentFunctionDescription = "string comparison function";
Ted Kremenek49b1e382012-01-26 21:29:00 +00001693 ProgramStateRef state = C.getState();
Ted Kremenek632e3b72012-01-06 22:09:28 +00001694 const LocationContext *LCtx = C.getLocationContext();
Lenny Maioranif3539ad2011-04-12 17:08:43 +00001695
1696 // Check that the first string is non-null
1697 const Expr *s1 = CE->getArg(0);
Ted Kremenek632e3b72012-01-06 22:09:28 +00001698 SVal s1Val = state->getSVal(s1, LCtx);
Lenny Maioranif3539ad2011-04-12 17:08:43 +00001699 state = checkNonNull(C, state, s1, s1Val);
1700 if (!state)
1701 return;
1702
1703 // Check that the second string is non-null.
1704 const Expr *s2 = CE->getArg(1);
Ted Kremenek632e3b72012-01-06 22:09:28 +00001705 SVal s2Val = state->getSVal(s2, LCtx);
Lenny Maioranif3539ad2011-04-12 17:08:43 +00001706 state = checkNonNull(C, state, s2, s2Val);
1707 if (!state)
1708 return;
1709
1710 // Get the string length of the first string or give up.
1711 SVal s1Length = getCStringLength(C, state, s1, s1Val);
1712 if (s1Length.isUndef())
1713 return;
1714
1715 // Get the string length of the second string or give up.
1716 SVal s2Length = getCStringLength(C, state, s2, s2Val);
1717 if (s2Length.isUndef())
1718 return;
1719
Jordy Rosec0263702011-06-16 07:13:34 +00001720 // If we know the two buffers are the same, we know the result is 0.
1721 // First, get the two buffers' addresses. Another checker will have already
1722 // made sure they're not undefined.
David Blaikie2fdacbc2013-02-20 05:52:05 +00001723 DefinedOrUnknownSVal LV = s1Val.castAs<DefinedOrUnknownSVal>();
1724 DefinedOrUnknownSVal RV = s2Val.castAs<DefinedOrUnknownSVal>();
Lenny Maioranif3539ad2011-04-12 17:08:43 +00001725
Jordy Rosec0263702011-06-16 07:13:34 +00001726 // See if they are the same.
Lenny Maioranif3539ad2011-04-12 17:08:43 +00001727 SValBuilder &svalBuilder = C.getSValBuilder();
Jordy Rosec0263702011-06-16 07:13:34 +00001728 DefinedOrUnknownSVal SameBuf = svalBuilder.evalEQ(state, LV, RV);
Ted Kremenek49b1e382012-01-26 21:29:00 +00001729 ProgramStateRef StSameBuf, StNotSameBuf;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001730 std::tie(StSameBuf, StNotSameBuf) = state->assume(SameBuf);
Lenny Maioranif3539ad2011-04-12 17:08:43 +00001731
Jordy Rosec0263702011-06-16 07:13:34 +00001732 // If the two arguments might be the same buffer, we know the result is 0,
1733 // and we only need to check one size.
1734 if (StSameBuf) {
Ted Kremenek632e3b72012-01-06 22:09:28 +00001735 StSameBuf = StSameBuf->BindExpr(CE, LCtx,
1736 svalBuilder.makeZeroVal(CE->getType()));
Anna Zaksda4c8d62011-10-26 21:06:34 +00001737 C.addTransition(StSameBuf);
Jordy Rosec0263702011-06-16 07:13:34 +00001738
1739 // If the two arguments are GUARANTEED to be the same, we're done!
1740 if (!StNotSameBuf)
1741 return;
1742 }
1743
1744 assert(StNotSameBuf);
1745 state = StNotSameBuf;
1746
1747 // At this point we can go about comparing the two buffers.
1748 // For now, we only do this if they're both known string literals.
1749
1750 // Attempt to extract string literals from both expressions.
1751 const StringLiteral *s1StrLiteral = getCStringLiteral(C, state, s1, s1Val);
1752 const StringLiteral *s2StrLiteral = getCStringLiteral(C, state, s2, s2Val);
1753 bool canComputeResult = false;
1754
1755 if (s1StrLiteral && s2StrLiteral) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001756 StringRef s1StrRef = s1StrLiteral->getString();
1757 StringRef s2StrRef = s2StrLiteral->getString();
Jordy Rosec0263702011-06-16 07:13:34 +00001758
1759 if (isBounded) {
1760 // Get the max number of characters to compare.
1761 const Expr *lenExpr = CE->getArg(2);
Ted Kremenek632e3b72012-01-06 22:09:28 +00001762 SVal lenVal = state->getSVal(lenExpr, LCtx);
Jordy Rosec0263702011-06-16 07:13:34 +00001763
1764 // If the length is known, we can get the right substrings.
1765 if (const llvm::APSInt *len = svalBuilder.getKnownValue(state, lenVal)) {
1766 // Create substrings of each to compare the prefix.
1767 s1StrRef = s1StrRef.substr(0, (size_t)len->getZExtValue());
1768 s2StrRef = s2StrRef.substr(0, (size_t)len->getZExtValue());
1769 canComputeResult = true;
1770 }
1771 } else {
1772 // This is a normal, unbounded strcmp.
1773 canComputeResult = true;
1774 }
1775
1776 if (canComputeResult) {
1777 // Real strcmp stops at null characters.
1778 size_t s1Term = s1StrRef.find('\0');
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001779 if (s1Term != StringRef::npos)
Jordy Rosec0263702011-06-16 07:13:34 +00001780 s1StrRef = s1StrRef.substr(0, s1Term);
1781
1782 size_t s2Term = s2StrRef.find('\0');
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001783 if (s2Term != StringRef::npos)
Jordy Rosec0263702011-06-16 07:13:34 +00001784 s2StrRef = s2StrRef.substr(0, s2Term);
1785
1786 // Use StringRef's comparison methods to compute the actual result.
1787 int result;
1788
1789 if (ignoreCase) {
1790 // Compare string 1 to string 2 the same way strcasecmp() does.
1791 result = s1StrRef.compare_lower(s2StrRef);
1792 } else {
1793 // Compare string 1 to string 2 the same way strcmp() does.
1794 result = s1StrRef.compare(s2StrRef);
1795 }
1796
1797 // Build the SVal of the comparison and bind the return value.
1798 SVal resultVal = svalBuilder.makeIntVal(result, CE->getType());
Ted Kremenek632e3b72012-01-06 22:09:28 +00001799 state = state->BindExpr(CE, LCtx, resultVal);
Jordy Rosec0263702011-06-16 07:13:34 +00001800 }
1801 }
1802
1803 if (!canComputeResult) {
1804 // Conjure a symbolic value. It's the best we can do.
Craig Topper0dbb7832014-05-27 02:45:47 +00001805 SVal resultVal = svalBuilder.conjureSymbolVal(nullptr, CE, LCtx,
1806 C.blockCount());
Ted Kremenek632e3b72012-01-06 22:09:28 +00001807 state = state->BindExpr(CE, LCtx, resultVal);
Jordy Rosec0263702011-06-16 07:13:34 +00001808 }
1809
1810 // Record this as a possible path.
Anna Zaksda4c8d62011-10-26 21:06:34 +00001811 C.addTransition(state);
Lenny Maioranif3539ad2011-04-12 17:08:43 +00001812}
1813
Jordan Rose6e3cf2b2013-04-22 23:18:42 +00001814void CStringChecker::evalStrsep(CheckerContext &C, const CallExpr *CE) const {
1815 //char *strsep(char **stringp, const char *delim);
1816 if (CE->getNumArgs() < 2)
1817 return;
1818
1819 // Sanity: does the search string parameter match the return type?
1820 const Expr *SearchStrPtr = CE->getArg(0);
1821 QualType CharPtrTy = SearchStrPtr->getType()->getPointeeType();
1822 if (CharPtrTy.isNull() ||
1823 CE->getType().getUnqualifiedType() != CharPtrTy.getUnqualifiedType())
1824 return;
1825
1826 CurrentFunctionDescription = "strsep()";
1827 ProgramStateRef State = C.getState();
1828 const LocationContext *LCtx = C.getLocationContext();
1829
1830 // Check that the search string pointer is non-null (though it may point to
1831 // a null string).
1832 SVal SearchStrVal = State->getSVal(SearchStrPtr, LCtx);
1833 State = checkNonNull(C, State, SearchStrPtr, SearchStrVal);
1834 if (!State)
1835 return;
1836
1837 // Check that the delimiter string is non-null.
1838 const Expr *DelimStr = CE->getArg(1);
1839 SVal DelimStrVal = State->getSVal(DelimStr, LCtx);
1840 State = checkNonNull(C, State, DelimStr, DelimStrVal);
1841 if (!State)
1842 return;
1843
1844 SValBuilder &SVB = C.getSValBuilder();
1845 SVal Result;
1846 if (Optional<Loc> SearchStrLoc = SearchStrVal.getAs<Loc>()) {
1847 // Get the current value of the search string pointer, as a char*.
1848 Result = State->getSVal(*SearchStrLoc, CharPtrTy);
1849
1850 // Invalidate the search string, representing the change of one delimiter
1851 // character to NUL.
Anton Yartsev968c60a2013-11-17 09:18:48 +00001852 State = InvalidateBuffer(C, State, SearchStrPtr, Result,
1853 /*IsSourceBuffer*/false);
Jordan Rose6e3cf2b2013-04-22 23:18:42 +00001854
1855 // Overwrite the search string pointer. The new value is either an address
1856 // further along in the same string, or NULL if there are no more tokens.
1857 State = State->bindLoc(*SearchStrLoc,
1858 SVB.conjureSymbolVal(getTag(), CE, LCtx, CharPtrTy,
1859 C.blockCount()));
1860 } else {
1861 assert(SearchStrVal.isUnknown());
1862 // Conjure a symbolic value. It's the best we can do.
Craig Topper0dbb7832014-05-27 02:45:47 +00001863 Result = SVB.conjureSymbolVal(nullptr, CE, LCtx, C.blockCount());
Jordan Rose6e3cf2b2013-04-22 23:18:42 +00001864 }
1865
1866 // Set the return value, and finish.
1867 State = State->BindExpr(CE, LCtx, Result);
1868 C.addTransition(State);
1869}
1870
1871
Jordy Rosed5d2e502010-07-08 23:57:29 +00001872//===----------------------------------------------------------------------===//
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001873// The driver method, and other Checker callbacks.
Jordy Rosed5d2e502010-07-08 23:57:29 +00001874//===----------------------------------------------------------------------===//
Jordy Rose134a2362010-07-06 23:11:01 +00001875
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00001876bool CStringChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
Anna Zaks6348a812012-02-17 22:35:26 +00001877 const FunctionDecl *FDecl = C.getCalleeDecl(CE);
1878
1879 if (!FDecl)
Jordy Rose134a2362010-07-06 23:11:01 +00001880 return false;
Jordy Rose134a2362010-07-06 23:11:01 +00001881
Jordan Rose6e3cf2b2013-04-22 23:18:42 +00001882 // FIXME: Poorly-factored string switches are slow.
Craig Topper0dbb7832014-05-27 02:45:47 +00001883 FnCheck evalFunction = nullptr;
Anna Zaks6348a812012-02-17 22:35:26 +00001884 if (C.isCLibraryFunction(FDecl, "memcpy"))
1885 evalFunction = &CStringChecker::evalMemcpy;
1886 else if (C.isCLibraryFunction(FDecl, "mempcpy"))
1887 evalFunction = &CStringChecker::evalMempcpy;
1888 else if (C.isCLibraryFunction(FDecl, "memcmp"))
1889 evalFunction = &CStringChecker::evalMemcmp;
1890 else if (C.isCLibraryFunction(FDecl, "memmove"))
1891 evalFunction = &CStringChecker::evalMemmove;
1892 else if (C.isCLibraryFunction(FDecl, "strcpy"))
1893 evalFunction = &CStringChecker::evalStrcpy;
1894 else if (C.isCLibraryFunction(FDecl, "strncpy"))
1895 evalFunction = &CStringChecker::evalStrncpy;
1896 else if (C.isCLibraryFunction(FDecl, "stpcpy"))
1897 evalFunction = &CStringChecker::evalStpcpy;
1898 else if (C.isCLibraryFunction(FDecl, "strcat"))
1899 evalFunction = &CStringChecker::evalStrcat;
1900 else if (C.isCLibraryFunction(FDecl, "strncat"))
1901 evalFunction = &CStringChecker::evalStrncat;
1902 else if (C.isCLibraryFunction(FDecl, "strlen"))
1903 evalFunction = &CStringChecker::evalstrLength;
1904 else if (C.isCLibraryFunction(FDecl, "strnlen"))
1905 evalFunction = &CStringChecker::evalstrnLength;
1906 else if (C.isCLibraryFunction(FDecl, "strcmp"))
1907 evalFunction = &CStringChecker::evalStrcmp;
1908 else if (C.isCLibraryFunction(FDecl, "strncmp"))
1909 evalFunction = &CStringChecker::evalStrncmp;
1910 else if (C.isCLibraryFunction(FDecl, "strcasecmp"))
1911 evalFunction = &CStringChecker::evalStrcasecmp;
1912 else if (C.isCLibraryFunction(FDecl, "strncasecmp"))
1913 evalFunction = &CStringChecker::evalStrncasecmp;
Jordan Rose6e3cf2b2013-04-22 23:18:42 +00001914 else if (C.isCLibraryFunction(FDecl, "strsep"))
1915 evalFunction = &CStringChecker::evalStrsep;
Anna Zaks6348a812012-02-17 22:35:26 +00001916 else if (C.isCLibraryFunction(FDecl, "bcopy"))
1917 evalFunction = &CStringChecker::evalBcopy;
1918 else if (C.isCLibraryFunction(FDecl, "bcmp"))
1919 evalFunction = &CStringChecker::evalMemcmp;
1920
Jordy Rosed5d2e502010-07-08 23:57:29 +00001921 // If the callee isn't a string function, let another checker handle it.
Ted Kremenekdc891422010-12-01 21:57:22 +00001922 if (!evalFunction)
Jordy Rose134a2362010-07-06 23:11:01 +00001923 return false;
1924
Jordy Rosedceb0cf2011-06-20 02:06:40 +00001925 // Make sure each function sets its own description.
1926 // (But don't bother in a release build.)
Craig Topper0dbb7832014-05-27 02:45:47 +00001927 assert(!(CurrentFunctionDescription = nullptr));
Jordy Rosedceb0cf2011-06-20 02:06:40 +00001928
Jordy Rosed5d2e502010-07-08 23:57:29 +00001929 // Check and evaluate the call.
Ted Kremenekdc891422010-12-01 21:57:22 +00001930 (this->*evalFunction)(C, CE);
Anna Zakse0c7c272012-02-07 00:56:14 +00001931
1932 // If the evaluate call resulted in no change, chain to the next eval call
1933 // handler.
1934 // Note, the custom CString evaluation calls assume that basic safety
1935 // properties are held. However, if the user chooses to turn off some of these
1936 // checks, we ignore the issues and leave the call evaluation to a generic
1937 // handler.
1938 if (!C.isDifferent())
1939 return false;
1940
Jordy Rose134a2362010-07-06 23:11:01 +00001941 return true;
1942}
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001943
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00001944void CStringChecker::checkPreStmt(const DeclStmt *DS, CheckerContext &C) const {
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001945 // Record string length for char a[] = "abc";
Ted Kremenek49b1e382012-01-26 21:29:00 +00001946 ProgramStateRef state = C.getState();
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001947
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001948 for (const auto *I : DS->decls()) {
1949 const VarDecl *D = dyn_cast<VarDecl>(I);
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001950 if (!D)
1951 continue;
1952
1953 // FIXME: Handle array fields of structs.
1954 if (!D->getType()->isArrayType())
1955 continue;
1956
1957 const Expr *Init = D->getInit();
1958 if (!Init)
1959 continue;
1960 if (!isa<StringLiteral>(Init))
1961 continue;
1962
Anna Zaksc9abbe22011-10-26 21:06:44 +00001963 Loc VarLoc = state->getLValue(D, C.getLocationContext());
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001964 const MemRegion *MR = VarLoc.getAsRegion();
1965 if (!MR)
1966 continue;
1967
Ted Kremenek632e3b72012-01-06 22:09:28 +00001968 SVal StrVal = state->getSVal(Init, C.getLocationContext());
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001969 assert(StrVal.isValid() && "Initializer string is unknown or undefined");
David Blaikie2fdacbc2013-02-20 05:52:05 +00001970 DefinedOrUnknownSVal strLength =
1971 getCStringLength(C, state, Init, StrVal).castAs<DefinedOrUnknownSVal>();
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001972
Ted Kremenek90af9092010-12-02 07:49:45 +00001973 state = state->set<CStringLength>(MR, strLength);
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001974 }
1975
Anna Zaksda4c8d62011-10-26 21:06:34 +00001976 C.addTransition(state);
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001977}
1978
Ted Kremenek49b1e382012-01-26 21:29:00 +00001979bool CStringChecker::wantsRegionChangeUpdate(ProgramStateRef state) const {
Jordan Rose0c153cb2012-11-02 01:54:06 +00001980 CStringLengthTy Entries = state->get<CStringLength>();
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001981 return !Entries.isEmpty();
1982}
1983
Ted Kremenek49b1e382012-01-26 21:29:00 +00001984ProgramStateRef
1985CStringChecker::checkRegionChanges(ProgramStateRef state,
Anna Zaksdc154152012-12-20 00:38:25 +00001986 const InvalidatedSymbols *,
Jordy Rose1fad6632011-08-27 22:51:26 +00001987 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks3d348342012-02-14 21:55:24 +00001988 ArrayRef<const MemRegion *> Regions,
Jordan Rose742920c2012-07-02 19:27:35 +00001989 const CallEvent *Call) const {
Jordan Rose0c153cb2012-11-02 01:54:06 +00001990 CStringLengthTy Entries = state->get<CStringLength>();
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001991 if (Entries.isEmpty())
1992 return state;
1993
1994 llvm::SmallPtrSet<const MemRegion *, 8> Invalidated;
1995 llvm::SmallPtrSet<const MemRegion *, 32> SuperRegions;
1996
1997 // First build sets for the changed regions and their super-regions.
Jordy Rose1fad6632011-08-27 22:51:26 +00001998 for (ArrayRef<const MemRegion *>::iterator
1999 I = Regions.begin(), E = Regions.end(); I != E; ++I) {
2000 const MemRegion *MR = *I;
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002001 Invalidated.insert(MR);
2002
2003 SuperRegions.insert(MR);
2004 while (const SubRegion *SR = dyn_cast<SubRegion>(MR)) {
2005 MR = SR->getSuperRegion();
2006 SuperRegions.insert(MR);
2007 }
2008 }
2009
Jordan Rose0c153cb2012-11-02 01:54:06 +00002010 CStringLengthTy::Factory &F = state->get_context<CStringLength>();
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002011
2012 // Then loop over the entries in the current state.
Jordan Rose0c153cb2012-11-02 01:54:06 +00002013 for (CStringLengthTy::iterator I = Entries.begin(),
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002014 E = Entries.end(); I != E; ++I) {
2015 const MemRegion *MR = I.getKey();
2016
2017 // Is this entry for a super-region of a changed region?
2018 if (SuperRegions.count(MR)) {
Ted Kremenekb3b56c62010-11-24 00:54:37 +00002019 Entries = F.remove(Entries, MR);
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002020 continue;
2021 }
2022
2023 // Is this entry for a sub-region of a changed region?
2024 const MemRegion *Super = MR;
2025 while (const SubRegion *SR = dyn_cast<SubRegion>(Super)) {
2026 Super = SR->getSuperRegion();
2027 if (Invalidated.count(Super)) {
Ted Kremenekb3b56c62010-11-24 00:54:37 +00002028 Entries = F.remove(Entries, MR);
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002029 break;
2030 }
2031 }
2032 }
2033
2034 return state->set<CStringLength>(Entries);
2035}
2036
Ted Kremenek49b1e382012-01-26 21:29:00 +00002037void CStringChecker::checkLiveSymbols(ProgramStateRef state,
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00002038 SymbolReaper &SR) const {
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002039 // Mark all symbols in our string length map as valid.
Jordan Rose0c153cb2012-11-02 01:54:06 +00002040 CStringLengthTy Entries = state->get<CStringLength>();
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002041
Jordan Rose0c153cb2012-11-02 01:54:06 +00002042 for (CStringLengthTy::iterator I = Entries.begin(), E = Entries.end();
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002043 I != E; ++I) {
2044 SVal Len = I.getData();
Jordy Rose634c12d2011-06-15 05:52:56 +00002045
Anna Zaksee1a4352011-12-06 23:12:33 +00002046 for (SymExpr::symbol_iterator si = Len.symbol_begin(),
2047 se = Len.symbol_end(); si != se; ++si)
Jordy Rose634c12d2011-06-15 05:52:56 +00002048 SR.markInUse(*si);
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002049 }
2050}
2051
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00002052void CStringChecker::checkDeadSymbols(SymbolReaper &SR,
2053 CheckerContext &C) const {
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002054 if (!SR.hasDeadSymbols())
2055 return;
2056
Ted Kremenek49b1e382012-01-26 21:29:00 +00002057 ProgramStateRef state = C.getState();
Jordan Rose0c153cb2012-11-02 01:54:06 +00002058 CStringLengthTy Entries = state->get<CStringLength>();
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002059 if (Entries.isEmpty())
2060 return;
2061
Jordan Rose0c153cb2012-11-02 01:54:06 +00002062 CStringLengthTy::Factory &F = state->get_context<CStringLength>();
2063 for (CStringLengthTy::iterator I = Entries.begin(), E = Entries.end();
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002064 I != E; ++I) {
2065 SVal Len = I.getData();
2066 if (SymbolRef Sym = Len.getAsSymbol()) {
2067 if (SR.isDead(Sym))
Ted Kremenekb3b56c62010-11-24 00:54:37 +00002068 Entries = F.remove(Entries, I.getKey());
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002069 }
2070 }
2071
2072 state = state->set<CStringLength>(Entries);
Anna Zaksda4c8d62011-10-26 21:06:34 +00002073 C.addTransition(state);
Jordy Rose2a2e21c2010-08-14 21:02:52 +00002074}
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00002075
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002076#define REGISTER_CHECKER(name) \
2077 void ento::register##name(CheckerManager &mgr) { \
2078 CStringChecker *checker = mgr.registerChecker<CStringChecker>(); \
2079 checker->Filter.Check##name = true; \
2080 checker->Filter.CheckName##name = mgr.getCurrentCheckName(); \
2081 }
Anna Zakse0c7c272012-02-07 00:56:14 +00002082
2083REGISTER_CHECKER(CStringNullArg)
2084REGISTER_CHECKER(CStringOutOfBounds)
2085REGISTER_CHECKER(CStringBufferOverlap)
2086REGISTER_CHECKER(CStringNotNullTerm)
Anna Zakse56167e2012-02-17 22:35:31 +00002087
2088void ento::registerCStringCheckerBasic(CheckerManager &Mgr) {
2089 registerCStringNullArg(Mgr);
2090}