blob: 1c9956727a69804f6fc836c6c4afb84b826deb19 [file] [log] [blame]
Anna Zaksc800f682011-10-11 16:49:54 +00001//= CStringChecker.cpp - Checks calls to C string functions --------*- C++ -*-//
Jordy Roseccbf7ee2010-07-06 23:11:01 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This defines CStringChecker, which is an assortment of checks on calls
11// to functions in <string.h>.
12//
13//===----------------------------------------------------------------------===//
14
Argyrios Kyrtzidisa0decc92011-02-15 21:25:03 +000015#include "ClangSACheckers.h"
Anna Zaksf0dfc9c2012-02-17 22:35:31 +000016#include "InterCheckerAPI.h"
Jordan Rose223f0ff2013-02-09 10:09:43 +000017#include "clang/Basic/CharInfo.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000018#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
Argyrios Kyrtzidisec8605f2011-03-01 01:16:21 +000019#include "clang/StaticAnalyzer/Core/Checker.h"
Argyrios Kyrtzidis695fb502011-02-17 21:39:17 +000020#include "clang/StaticAnalyzer/Core/CheckerManager.h"
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000021#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
Ted Kremenek18c66fd2011-08-15 22:09:50 +000022#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
Benjamin Kramer00bd44d2012-02-04 12:31:12 +000023#include "llvm/ADT/STLExtras.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000024#include "llvm/ADT/SmallString.h"
Jordy Roseccbf7ee2010-07-06 23:11:01 +000025#include "llvm/ADT/StringSwitch.h"
Benjamin Kramera93d0f22012-12-01 17:12:56 +000026#include "llvm/Support/raw_ostream.h"
Jordy Roseccbf7ee2010-07-06 23:11:01 +000027
28using namespace clang;
Ted Kremenek9ef65372010-12-23 07:20:52 +000029using namespace ento;
Jordy Roseccbf7ee2010-07-06 23:11:01 +000030
31namespace {
Argyrios Kyrtzidisec8605f2011-03-01 01:16:21 +000032class CStringChecker : public Checker< eval::Call,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000033 check::PreStmt<DeclStmt>,
34 check::LiveSymbols,
35 check::DeadSymbols,
36 check::RegionChanges
37 > {
Anna Zaks57300762012-02-07 00:56:14 +000038 mutable OwningPtr<BugType> BT_Null,
39 BT_Bounds,
40 BT_Overlap,
41 BT_NotCString,
42 BT_AdditionOverflow;
43
Jordy Rose9e49d9f2011-06-20 02:06:40 +000044 mutable const char *CurrentFunctionDescription;
45
Jordy Roseccbf7ee2010-07-06 23:11:01 +000046public:
Anna Zaks57300762012-02-07 00:56:14 +000047 /// The filter is used to filter out the diagnostics which are not enabled by
48 /// the user.
49 struct CStringChecksFilter {
50 DefaultBool CheckCStringNullArg;
51 DefaultBool CheckCStringOutOfBounds;
52 DefaultBool CheckCStringBufferOverlap;
53 DefaultBool CheckCStringNotNullTerm;
54 };
55
56 CStringChecksFilter Filter;
57
Jordy Roseccbf7ee2010-07-06 23:11:01 +000058 static void *getTag() { static int tag; return &tag; }
59
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000060 bool evalCall(const CallExpr *CE, CheckerContext &C) const;
61 void checkPreStmt(const DeclStmt *DS, CheckerContext &C) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +000062 void checkLiveSymbols(ProgramStateRef state, SymbolReaper &SR) const;
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000063 void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +000064 bool wantsRegionChangeUpdate(ProgramStateRef state) const;
Jordy Rosea5261542010-08-14 21:02:52 +000065
Ted Kremenek8bef8232012-01-26 21:29:00 +000066 ProgramStateRef
67 checkRegionChanges(ProgramStateRef state,
Anna Zaksbf53dfa2012-12-20 00:38:25 +000068 const InvalidatedSymbols *,
Jordy Rose537716a2011-08-27 22:51:26 +000069 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +000070 ArrayRef<const MemRegion *> Regions,
Jordan Rose740d4902012-07-02 19:27:35 +000071 const CallEvent *Call) const;
Jordy Roseccbf7ee2010-07-06 23:11:01 +000072
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000073 typedef void (CStringChecker::*FnCheck)(CheckerContext &,
74 const CallExpr *) const;
Jordy Roseccbf7ee2010-07-06 23:11:01 +000075
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000076 void evalMemcpy(CheckerContext &C, const CallExpr *CE) const;
Lenny Maioranib8b875b2011-03-31 21:36:53 +000077 void evalMempcpy(CheckerContext &C, const CallExpr *CE) const;
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000078 void evalMemmove(CheckerContext &C, const CallExpr *CE) const;
79 void evalBcopy(CheckerContext &C, const CallExpr *CE) const;
Lenny Maioranib8b875b2011-03-31 21:36:53 +000080 void evalCopyCommon(CheckerContext &C, const CallExpr *CE,
Ted Kremenek8bef8232012-01-26 21:29:00 +000081 ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +000082 const Expr *Size,
83 const Expr *Source,
84 const Expr *Dest,
Lenny Maioranib8b875b2011-03-31 21:36:53 +000085 bool Restricted = false,
86 bool IsMempcpy = false) const;
Jordy Rosed325ffb2010-07-08 23:57:29 +000087
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000088 void evalMemcmp(CheckerContext &C, const CallExpr *CE) const;
Jordy Roseccbf7ee2010-07-06 23:11:01 +000089
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000090 void evalstrLength(CheckerContext &C, const CallExpr *CE) const;
91 void evalstrnLength(CheckerContext &C, const CallExpr *CE) const;
Ted Kremenek18c66fd2011-08-15 22:09:50 +000092 void evalstrLengthCommon(CheckerContext &C,
93 const CallExpr *CE,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000094 bool IsStrnlen = false) const;
Jordy Rose19c5dd12010-07-27 01:37:31 +000095
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000096 void evalStrcpy(CheckerContext &C, const CallExpr *CE) const;
97 void evalStrncpy(CheckerContext &C, const CallExpr *CE) const;
98 void evalStpcpy(CheckerContext &C, const CallExpr *CE) const;
Ted Kremenek18c66fd2011-08-15 22:09:50 +000099 void evalStrcpyCommon(CheckerContext &C,
100 const CallExpr *CE,
101 bool returnEnd,
102 bool isBounded,
103 bool isAppending) const;
Lenny Maiorani067bbd02011-04-09 15:12:58 +0000104
105 void evalStrcat(CheckerContext &C, const CallExpr *CE) const;
106 void evalStrncat(CheckerContext &C, const CallExpr *CE) const;
Jordy Rosee64f3112010-08-16 07:51:42 +0000107
Lenny Maiorani318dd922011-04-12 17:08:43 +0000108 void evalStrcmp(CheckerContext &C, const CallExpr *CE) const;
Lenny Maiorani357f6ee2011-04-25 22:21:00 +0000109 void evalStrncmp(CheckerContext &C, const CallExpr *CE) const;
Lenny Maioranibd1d16a2011-04-28 15:09:11 +0000110 void evalStrcasecmp(CheckerContext &C, const CallExpr *CE) const;
Lenny Maiorani454fd2d2011-05-02 19:05:49 +0000111 void evalStrncasecmp(CheckerContext &C, const CallExpr *CE) const;
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000112 void evalStrcmpCommon(CheckerContext &C,
113 const CallExpr *CE,
114 bool isBounded = false,
115 bool ignoreCase = false) const;
Lenny Maiorani318dd922011-04-12 17:08:43 +0000116
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000117 // Utility methods
Ted Kremenek8bef8232012-01-26 21:29:00 +0000118 std::pair<ProgramStateRef , ProgramStateRef >
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000119 static assumeZero(CheckerContext &C,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000120 ProgramStateRef state, SVal V, QualType Ty);
Jordy Rosed325ffb2010-07-08 23:57:29 +0000121
Ted Kremenek8bef8232012-01-26 21:29:00 +0000122 static ProgramStateRef setCStringLength(ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000123 const MemRegion *MR,
124 SVal strLength);
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000125 static SVal getCStringLengthForRegion(CheckerContext &C,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000126 ProgramStateRef &state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000127 const Expr *Ex,
128 const MemRegion *MR,
Jordy Rosed5af0e12011-06-15 05:52:56 +0000129 bool hypothetical);
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000130 SVal getCStringLength(CheckerContext &C,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000131 ProgramStateRef &state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000132 const Expr *Ex,
133 SVal Buf,
Jordy Rosed5af0e12011-06-15 05:52:56 +0000134 bool hypothetical = false) const;
Jordy Rose19c5dd12010-07-27 01:37:31 +0000135
Lenny Maiorani318dd922011-04-12 17:08:43 +0000136 const StringLiteral *getCStringLiteral(CheckerContext &C,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000137 ProgramStateRef &state,
Lenny Maiorani318dd922011-04-12 17:08:43 +0000138 const Expr *expr,
139 SVal val) const;
140
Ted Kremenek8bef8232012-01-26 21:29:00 +0000141 static ProgramStateRef InvalidateBuffer(CheckerContext &C,
142 ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000143 const Expr *Ex, SVal V);
Jordy Rosee64f3112010-08-16 07:51:42 +0000144
Ted Kremenek9c378f72011-08-12 23:37:29 +0000145 static bool SummarizeRegion(raw_ostream &os, ASTContext &Ctx,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000146 const MemRegion *MR);
Jordy Rose19c5dd12010-07-27 01:37:31 +0000147
148 // Re-usable checks
Ted Kremenek8bef8232012-01-26 21:29:00 +0000149 ProgramStateRef checkNonNull(CheckerContext &C,
150 ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000151 const Expr *S,
152 SVal l) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000153 ProgramStateRef CheckLocation(CheckerContext &C,
154 ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000155 const Expr *S,
156 SVal l,
157 const char *message = NULL) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000158 ProgramStateRef CheckBufferAccess(CheckerContext &C,
159 ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000160 const Expr *Size,
161 const Expr *FirstBuf,
162 const Expr *SecondBuf,
163 const char *firstMessage = NULL,
164 const char *secondMessage = NULL,
165 bool WarnAboutSize = false) const;
166
Ted Kremenek8bef8232012-01-26 21:29:00 +0000167 ProgramStateRef CheckBufferAccess(CheckerContext &C,
168 ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000169 const Expr *Size,
170 const Expr *Buf,
171 const char *message = NULL,
172 bool WarnAboutSize = false) const {
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000173 // This is a convenience override.
Jordy Rose5e5f1502011-06-20 03:49:16 +0000174 return CheckBufferAccess(C, state, Size, Buf, NULL, message, NULL,
175 WarnAboutSize);
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000176 }
Ted Kremenek8bef8232012-01-26 21:29:00 +0000177 ProgramStateRef CheckOverlap(CheckerContext &C,
178 ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000179 const Expr *Size,
180 const Expr *First,
181 const Expr *Second) const;
182 void emitOverlapBug(CheckerContext &C,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000183 ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000184 const Stmt *First,
185 const Stmt *Second) const;
186
Ted Kremenek8bef8232012-01-26 21:29:00 +0000187 ProgramStateRef checkAdditionOverflow(CheckerContext &C,
188 ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000189 NonLoc left,
190 NonLoc right) const;
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000191};
Jordy Rosea5261542010-08-14 21:02:52 +0000192
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000193} //end anonymous namespace
194
Jordan Rose166d5022012-11-02 01:54:06 +0000195REGISTER_MAP_WITH_PROGRAMSTATE(CStringLength, const MemRegion *, SVal)
Jordy Rosea5261542010-08-14 21:02:52 +0000196
Jordy Rosed325ffb2010-07-08 23:57:29 +0000197//===----------------------------------------------------------------------===//
198// Individual checks and utility methods.
199//===----------------------------------------------------------------------===//
200
Ted Kremenek8bef8232012-01-26 21:29:00 +0000201std::pair<ProgramStateRef , ProgramStateRef >
202CStringChecker::assumeZero(CheckerContext &C, ProgramStateRef state, SVal V,
Jordy Rosed325ffb2010-07-08 23:57:29 +0000203 QualType Ty) {
David Blaikie5251abe2013-02-20 05:52:05 +0000204 llvm::Optional<DefinedSVal> val = V.getAs<DefinedSVal>();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000205 if (!val)
Ted Kremenek8bef8232012-01-26 21:29:00 +0000206 return std::pair<ProgramStateRef , ProgramStateRef >(state, state);
Jordy Rosea6b808c2010-07-07 07:48:06 +0000207
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000208 SValBuilder &svalBuilder = C.getSValBuilder();
209 DefinedOrUnknownSVal zero = svalBuilder.makeZeroVal(Ty);
210 return state->assume(svalBuilder.evalEQ(state, *val, zero));
Jordy Rosed325ffb2010-07-08 23:57:29 +0000211}
Jordy Rosea6b808c2010-07-07 07:48:06 +0000212
Ted Kremenek8bef8232012-01-26 21:29:00 +0000213ProgramStateRef CStringChecker::checkNonNull(CheckerContext &C,
214 ProgramStateRef state,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000215 const Expr *S, SVal l) const {
Jordy Rosed325ffb2010-07-08 23:57:29 +0000216 // If a previous check has failed, propagate the failure.
217 if (!state)
218 return NULL;
219
Ted Kremenek8bef8232012-01-26 21:29:00 +0000220 ProgramStateRef stateNull, stateNonNull;
Ted Kremenek28f47b92010-12-01 22:16:56 +0000221 llvm::tie(stateNull, stateNonNull) = assumeZero(C, state, l, S->getType());
Jordy Rosed325ffb2010-07-08 23:57:29 +0000222
223 if (stateNull && !stateNonNull) {
Anna Zaks57300762012-02-07 00:56:14 +0000224 if (!Filter.CheckCStringNullArg)
225 return NULL;
226
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000227 ExplodedNode *N = C.generateSink(stateNull);
Jordy Rosea6b808c2010-07-07 07:48:06 +0000228 if (!N)
229 return NULL;
230
Jordy Rosed325ffb2010-07-08 23:57:29 +0000231 if (!BT_Null)
Anna Zaks57300762012-02-07 00:56:14 +0000232 BT_Null.reset(new BuiltinBug("Unix API",
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000233 "Null pointer argument in call to byte string function"));
Jordy Rosea6b808c2010-07-07 07:48:06 +0000234
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000235 SmallString<80> buf;
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000236 llvm::raw_svector_ostream os(buf);
237 assert(CurrentFunctionDescription);
238 os << "Null pointer argument in call to " << CurrentFunctionDescription;
239
Jordy Rosea6b808c2010-07-07 07:48:06 +0000240 // Generate a report for this bug.
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000241 BuiltinBug *BT = static_cast<BuiltinBug*>(BT_Null.get());
Anna Zakse172e8b2011-08-17 23:00:25 +0000242 BugReport *report = new BugReport(*BT, os.str(), N);
Jordy Rosea6b808c2010-07-07 07:48:06 +0000243
244 report->addRange(S->getSourceRange());
Jordan Rosea1f81bb2012-08-28 00:50:51 +0000245 bugreporter::trackNullOrUndefValue(N, S, *report);
Jordan Rose785950e2012-11-02 01:53:40 +0000246 C.emitReport(report);
Jordy Rosea6b808c2010-07-07 07:48:06 +0000247 return NULL;
248 }
249
250 // From here on, assume that the value is non-null.
Jordy Rosed325ffb2010-07-08 23:57:29 +0000251 assert(stateNonNull);
252 return stateNonNull;
Jordy Rosea6b808c2010-07-07 07:48:06 +0000253}
254
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000255// FIXME: This was originally copied from ArrayBoundChecker.cpp. Refactor?
Ted Kremenek8bef8232012-01-26 21:29:00 +0000256ProgramStateRef CStringChecker::CheckLocation(CheckerContext &C,
257 ProgramStateRef state,
Jordy Rosee64f3112010-08-16 07:51:42 +0000258 const Expr *S, SVal l,
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000259 const char *warningMsg) const {
Jordy Rosed325ffb2010-07-08 23:57:29 +0000260 // If a previous check has failed, propagate the failure.
261 if (!state)
262 return NULL;
263
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000264 // Check for out of bound array element access.
265 const MemRegion *R = l.getAsRegion();
266 if (!R)
267 return state;
268
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000269 const ElementRegion *ER = dyn_cast<ElementRegion>(R);
270 if (!ER)
271 return state;
272
Zhongxing Xu018220c2010-08-11 06:10:55 +0000273 assert(ER->getValueType() == C.getASTContext().CharTy &&
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000274 "CheckLocation should only be called with char* ElementRegions");
275
276 // Get the size of the array.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000277 const SubRegion *superReg = cast<SubRegion>(ER->getSuperRegion());
278 SValBuilder &svalBuilder = C.getSValBuilder();
Jordy Rose1e022412011-06-16 05:51:02 +0000279 SVal Extent =
280 svalBuilder.convertToArrayIndex(superReg->getExtent(svalBuilder));
David Blaikie5251abe2013-02-20 05:52:05 +0000281 DefinedOrUnknownSVal Size = Extent.castAs<DefinedOrUnknownSVal>();
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000282
283 // Get the index of the accessed element.
Gabor Greif89b06582010-09-09 10:51:37 +0000284 DefinedOrUnknownSVal Idx = cast<DefinedOrUnknownSVal>(ER->getIndex());
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000285
Ted Kremenek8bef8232012-01-26 21:29:00 +0000286 ProgramStateRef StInBound = state->assumeInBound(Idx, Size, true);
287 ProgramStateRef StOutBound = state->assumeInBound(Idx, Size, false);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000288 if (StOutBound && !StInBound) {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000289 ExplodedNode *N = C.generateSink(StOutBound);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000290 if (!N)
291 return NULL;
292
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000293 if (!BT_Bounds) {
294 BT_Bounds.reset(new BuiltinBug("Out-of-bound array access",
295 "Byte string function accesses out-of-bound array element"));
296 }
297 BuiltinBug *BT = static_cast<BuiltinBug*>(BT_Bounds.get());
298
299 // Generate a report for this bug.
Anna Zakse172e8b2011-08-17 23:00:25 +0000300 BugReport *report;
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000301 if (warningMsg) {
Anna Zakse172e8b2011-08-17 23:00:25 +0000302 report = new BugReport(*BT, warningMsg, N);
Jordy Rosee64f3112010-08-16 07:51:42 +0000303 } else {
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000304 assert(CurrentFunctionDescription);
305 assert(CurrentFunctionDescription[0] != '\0');
306
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000307 SmallString<80> buf;
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000308 llvm::raw_svector_ostream os(buf);
Jordan Rose223f0ff2013-02-09 10:09:43 +0000309 os << toUppercase(CurrentFunctionDescription[0])
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000310 << &CurrentFunctionDescription[1]
311 << " accesses out-of-bound array element";
Anna Zakse172e8b2011-08-17 23:00:25 +0000312 report = new BugReport(*BT, os.str(), N);
Jordy Rosee64f3112010-08-16 07:51:42 +0000313 }
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000314
315 // FIXME: It would be nice to eventually make this diagnostic more clear,
316 // e.g., by referencing the original declaration or by saying *why* this
317 // reference is outside the range.
318
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000319 report->addRange(S->getSourceRange());
Jordan Rose785950e2012-11-02 01:53:40 +0000320 C.emitReport(report);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000321 return NULL;
322 }
323
324 // Array bound check succeeded. From this point forward the array bound
325 // should always succeed.
326 return StInBound;
327}
328
Ted Kremenek8bef8232012-01-26 21:29:00 +0000329ProgramStateRef CStringChecker::CheckBufferAccess(CheckerContext &C,
330 ProgramStateRef state,
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000331 const Expr *Size,
332 const Expr *FirstBuf,
Jordy Rosee64f3112010-08-16 07:51:42 +0000333 const Expr *SecondBuf,
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000334 const char *firstMessage,
Jordy Rose5e5f1502011-06-20 03:49:16 +0000335 const char *secondMessage,
336 bool WarnAboutSize) const {
Jordy Rosed325ffb2010-07-08 23:57:29 +0000337 // If a previous check has failed, propagate the failure.
338 if (!state)
339 return NULL;
340
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000341 SValBuilder &svalBuilder = C.getSValBuilder();
Jordy Rose1e022412011-06-16 05:51:02 +0000342 ASTContext &Ctx = svalBuilder.getContext();
Ted Kremenek5eca4822012-01-06 22:09:28 +0000343 const LocationContext *LCtx = C.getLocationContext();
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000344
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000345 QualType sizeTy = Size->getType();
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000346 QualType PtrTy = Ctx.getPointerType(Ctx.CharTy);
347
Jordy Rosea6b808c2010-07-07 07:48:06 +0000348 // Check that the first buffer is non-null.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000349 SVal BufVal = state->getSVal(FirstBuf, LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000350 state = checkNonNull(C, state, FirstBuf, BufVal);
Jordy Rosea6b808c2010-07-07 07:48:06 +0000351 if (!state)
352 return NULL;
353
Anna Zaks57300762012-02-07 00:56:14 +0000354 // If out-of-bounds checking is turned off, skip the rest.
355 if (!Filter.CheckCStringOutOfBounds)
356 return state;
357
Jordy Rosed325ffb2010-07-08 23:57:29 +0000358 // Get the access length and make sure it is known.
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000359 // FIXME: This assumes the caller has already checked that the access length
360 // is positive. And that it's unsigned.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000361 SVal LengthVal = state->getSVal(Size, LCtx);
David Blaikie5251abe2013-02-20 05:52:05 +0000362 llvm::Optional<NonLoc> Length = LengthVal.getAs<NonLoc>();
Jordy Rosed325ffb2010-07-08 23:57:29 +0000363 if (!Length)
364 return state;
365
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000366 // Compute the offset of the last element to be accessed: size-1.
David Blaikie5251abe2013-02-20 05:52:05 +0000367 NonLoc One = svalBuilder.makeIntVal(1, sizeTy).castAs<NonLoc>();
368 NonLoc LastOffset = svalBuilder
369 .evalBinOpNN(state, BO_Sub, *Length, One, sizeTy).castAs<NonLoc>();
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000370
Chris Lattnerfc8f0e12011-04-15 05:22:18 +0000371 // Check that the first buffer is sufficiently long.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000372 SVal BufStart = svalBuilder.evalCast(BufVal, PtrTy, FirstBuf->getType());
David Blaikie5251abe2013-02-20 05:52:05 +0000373 if (llvm::Optional<Loc> BufLoc = BufStart.getAs<Loc>()) {
Jordy Rose5e5f1502011-06-20 03:49:16 +0000374 const Expr *warningExpr = (WarnAboutSize ? Size : FirstBuf);
375
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000376 SVal BufEnd = svalBuilder.evalBinOpLN(state, BO_Add, *BufLoc,
377 LastOffset, PtrTy);
Jordy Rose5e5f1502011-06-20 03:49:16 +0000378 state = CheckLocation(C, state, warningExpr, BufEnd, firstMessage);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000379
Jordy Roseb6a40262010-08-05 23:11:30 +0000380 // If the buffer isn't large enough, abort.
381 if (!state)
382 return NULL;
383 }
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000384
385 // If there's a second buffer, check it as well.
386 if (SecondBuf) {
Ted Kremenek5eca4822012-01-06 22:09:28 +0000387 BufVal = state->getSVal(SecondBuf, LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000388 state = checkNonNull(C, state, SecondBuf, BufVal);
Jordy Rosea6b808c2010-07-07 07:48:06 +0000389 if (!state)
390 return NULL;
391
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000392 BufStart = svalBuilder.evalCast(BufVal, PtrTy, SecondBuf->getType());
David Blaikie5251abe2013-02-20 05:52:05 +0000393 if (llvm::Optional<Loc> BufLoc = BufStart.getAs<Loc>()) {
Jordy Rose5e5f1502011-06-20 03:49:16 +0000394 const Expr *warningExpr = (WarnAboutSize ? Size : SecondBuf);
395
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000396 SVal BufEnd = svalBuilder.evalBinOpLN(state, BO_Add, *BufLoc,
397 LastOffset, PtrTy);
Jordy Rose5e5f1502011-06-20 03:49:16 +0000398 state = CheckLocation(C, state, warningExpr, BufEnd, secondMessage);
Jordy Roseb6a40262010-08-05 23:11:30 +0000399 }
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000400 }
401
402 // Large enough or not, return this state!
403 return state;
404}
405
Ted Kremenek8bef8232012-01-26 21:29:00 +0000406ProgramStateRef CStringChecker::CheckOverlap(CheckerContext &C,
407 ProgramStateRef state,
Jordy Rosed325ffb2010-07-08 23:57:29 +0000408 const Expr *Size,
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000409 const Expr *First,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000410 const Expr *Second) const {
Anna Zaks57300762012-02-07 00:56:14 +0000411 if (!Filter.CheckCStringBufferOverlap)
412 return state;
413
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000414 // Do a simple check for overlap: if the two arguments are from the same
415 // buffer, see if the end of the first is greater than the start of the second
416 // or vice versa.
417
Jordy Rosed325ffb2010-07-08 23:57:29 +0000418 // If a previous check has failed, propagate the failure.
419 if (!state)
420 return NULL;
421
Ted Kremenek8bef8232012-01-26 21:29:00 +0000422 ProgramStateRef stateTrue, stateFalse;
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000423
424 // Get the buffer values and make sure they're known locations.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000425 const LocationContext *LCtx = C.getLocationContext();
426 SVal firstVal = state->getSVal(First, LCtx);
427 SVal secondVal = state->getSVal(Second, LCtx);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000428
David Blaikie5251abe2013-02-20 05:52:05 +0000429 llvm::Optional<Loc> firstLoc = firstVal.getAs<Loc>();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000430 if (!firstLoc)
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000431 return state;
432
David Blaikie5251abe2013-02-20 05:52:05 +0000433 llvm::Optional<Loc> secondLoc = secondVal.getAs<Loc>();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000434 if (!secondLoc)
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000435 return state;
436
437 // Are the two values the same?
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000438 SValBuilder &svalBuilder = C.getSValBuilder();
439 llvm::tie(stateTrue, stateFalse) =
440 state->assume(svalBuilder.evalEQ(state, *firstLoc, *secondLoc));
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000441
442 if (stateTrue && !stateFalse) {
443 // If the values are known to be equal, that's automatically an overlap.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000444 emitOverlapBug(C, stateTrue, First, Second);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000445 return NULL;
446 }
447
Ted Kremenek28f47b92010-12-01 22:16:56 +0000448 // assume the two expressions are not equal.
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000449 assert(stateFalse);
450 state = stateFalse;
451
452 // Which value comes first?
Jordy Roseee2fde12011-06-16 05:56:50 +0000453 QualType cmpTy = svalBuilder.getConditionType();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000454 SVal reverse = svalBuilder.evalBinOpLL(state, BO_GT,
455 *firstLoc, *secondLoc, cmpTy);
David Blaikie5251abe2013-02-20 05:52:05 +0000456 llvm::Optional<DefinedOrUnknownSVal> reverseTest =
457 reverse.getAs<DefinedOrUnknownSVal>();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000458 if (!reverseTest)
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000459 return state;
460
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000461 llvm::tie(stateTrue, stateFalse) = state->assume(*reverseTest);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000462 if (stateTrue) {
463 if (stateFalse) {
464 // If we don't know which one comes first, we can't perform this test.
465 return state;
466 } else {
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000467 // Switch the values so that firstVal is before secondVal.
David Blaikie5251abe2013-02-20 05:52:05 +0000468 std::swap(firstLoc, secondLoc);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000469
470 // Switch the Exprs as well, so that they still correspond.
David Blaikie5251abe2013-02-20 05:52:05 +0000471 std::swap(First, Second);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000472 }
473 }
474
475 // Get the length, and make sure it too is known.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000476 SVal LengthVal = state->getSVal(Size, LCtx);
David Blaikie5251abe2013-02-20 05:52:05 +0000477 llvm::Optional<NonLoc> Length = LengthVal.getAs<NonLoc>();
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000478 if (!Length)
479 return state;
480
481 // Convert the first buffer's start address to char*.
482 // Bail out if the cast fails.
Jordy Roseee2fde12011-06-16 05:56:50 +0000483 ASTContext &Ctx = svalBuilder.getContext();
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000484 QualType CharPtrTy = Ctx.getPointerType(Ctx.CharTy);
Jordy Rose1e022412011-06-16 05:51:02 +0000485 SVal FirstStart = svalBuilder.evalCast(*firstLoc, CharPtrTy,
486 First->getType());
David Blaikie5251abe2013-02-20 05:52:05 +0000487 llvm::Optional<Loc> FirstStartLoc = FirstStart.getAs<Loc>();
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000488 if (!FirstStartLoc)
489 return state;
490
491 // Compute the end of the first buffer. Bail out if THAT fails.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000492 SVal FirstEnd = svalBuilder.evalBinOpLN(state, BO_Add,
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000493 *FirstStartLoc, *Length, CharPtrTy);
David Blaikie5251abe2013-02-20 05:52:05 +0000494 llvm::Optional<Loc> FirstEndLoc = FirstEnd.getAs<Loc>();
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000495 if (!FirstEndLoc)
496 return state;
497
498 // Is the end of the first buffer past the start of the second buffer?
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000499 SVal Overlap = svalBuilder.evalBinOpLL(state, BO_GT,
500 *FirstEndLoc, *secondLoc, cmpTy);
David Blaikie5251abe2013-02-20 05:52:05 +0000501 llvm::Optional<DefinedOrUnknownSVal> OverlapTest =
502 Overlap.getAs<DefinedOrUnknownSVal>();
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000503 if (!OverlapTest)
504 return state;
505
Ted Kremenek28f47b92010-12-01 22:16:56 +0000506 llvm::tie(stateTrue, stateFalse) = state->assume(*OverlapTest);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000507
508 if (stateTrue && !stateFalse) {
509 // Overlap!
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000510 emitOverlapBug(C, stateTrue, First, Second);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000511 return NULL;
512 }
513
Ted Kremenek28f47b92010-12-01 22:16:56 +0000514 // assume the two expressions don't overlap.
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000515 assert(stateFalse);
516 return stateFalse;
517}
518
Ted Kremenek8bef8232012-01-26 21:29:00 +0000519void CStringChecker::emitOverlapBug(CheckerContext &C, ProgramStateRef state,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000520 const Stmt *First, const Stmt *Second) const {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000521 ExplodedNode *N = C.generateSink(state);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000522 if (!N)
523 return;
524
525 if (!BT_Overlap)
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000526 BT_Overlap.reset(new BugType("Unix API", "Improper arguments"));
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000527
528 // Generate a report for this bug.
Anna Zakse172e8b2011-08-17 23:00:25 +0000529 BugReport *report =
530 new BugReport(*BT_Overlap,
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000531 "Arguments must not be overlapping buffers", N);
532 report->addRange(First->getSourceRange());
533 report->addRange(Second->getSourceRange());
534
Jordan Rose785950e2012-11-02 01:53:40 +0000535 C.emitReport(report);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000536}
537
Ted Kremenek8bef8232012-01-26 21:29:00 +0000538ProgramStateRef CStringChecker::checkAdditionOverflow(CheckerContext &C,
539 ProgramStateRef state,
Jordy Rosed5af0e12011-06-15 05:52:56 +0000540 NonLoc left,
541 NonLoc right) const {
Anna Zaks57300762012-02-07 00:56:14 +0000542 // If out-of-bounds checking is turned off, skip the rest.
543 if (!Filter.CheckCStringOutOfBounds)
544 return state;
545
Jordy Rosed5af0e12011-06-15 05:52:56 +0000546 // If a previous check has failed, propagate the failure.
547 if (!state)
548 return NULL;
549
550 SValBuilder &svalBuilder = C.getSValBuilder();
551 BasicValueFactory &BVF = svalBuilder.getBasicValueFactory();
552
553 QualType sizeTy = svalBuilder.getContext().getSizeType();
554 const llvm::APSInt &maxValInt = BVF.getMaxValue(sizeTy);
555 NonLoc maxVal = svalBuilder.makeIntVal(maxValInt);
556
Anna Zakse3d250e2011-12-11 18:43:40 +0000557 SVal maxMinusRight;
David Blaikie5251abe2013-02-20 05:52:05 +0000558 if (right.getAs<nonloc::ConcreteInt>()) {
Anna Zakse3d250e2011-12-11 18:43:40 +0000559 maxMinusRight = svalBuilder.evalBinOpNN(state, BO_Sub, maxVal, right,
560 sizeTy);
561 } else {
Jordy Rosed5af0e12011-06-15 05:52:56 +0000562 // Try switching the operands. (The order of these two assignments is
563 // important!)
564 maxMinusRight = svalBuilder.evalBinOpNN(state, BO_Sub, maxVal, left,
565 sizeTy);
566 left = right;
567 }
568
David Blaikie5251abe2013-02-20 05:52:05 +0000569 if (llvm::Optional<NonLoc> maxMinusRightNL = maxMinusRight.getAs<NonLoc>()) {
Jordy Rosed5af0e12011-06-15 05:52:56 +0000570 QualType cmpTy = svalBuilder.getConditionType();
571 // If left > max - right, we have an overflow.
572 SVal willOverflow = svalBuilder.evalBinOpNN(state, BO_GT, left,
573 *maxMinusRightNL, cmpTy);
574
Ted Kremenek8bef8232012-01-26 21:29:00 +0000575 ProgramStateRef stateOverflow, stateOkay;
Jordy Rosed5af0e12011-06-15 05:52:56 +0000576 llvm::tie(stateOverflow, stateOkay) =
David Blaikie5251abe2013-02-20 05:52:05 +0000577 state->assume(willOverflow.castAs<DefinedOrUnknownSVal>());
Jordy Rosed5af0e12011-06-15 05:52:56 +0000578
579 if (stateOverflow && !stateOkay) {
580 // We have an overflow. Emit a bug report.
581 ExplodedNode *N = C.generateSink(stateOverflow);
582 if (!N)
583 return NULL;
584
585 if (!BT_AdditionOverflow)
586 BT_AdditionOverflow.reset(new BuiltinBug("API",
587 "Sum of expressions causes overflow"));
588
Jordy Rosed5af0e12011-06-15 05:52:56 +0000589 // This isn't a great error message, but this should never occur in real
590 // code anyway -- you'd have to create a buffer longer than a size_t can
591 // represent, which is sort of a contradiction.
Jordy Rose8cc24912011-06-20 03:51:53 +0000592 const char *warning =
593 "This expression will create a string whose length is too big to "
594 "be represented as a size_t";
Jordy Rosed5af0e12011-06-15 05:52:56 +0000595
596 // Generate a report for this bug.
Jordy Rose8cc24912011-06-20 03:51:53 +0000597 BugReport *report = new BugReport(*BT_AdditionOverflow, warning, N);
Jordan Rose785950e2012-11-02 01:53:40 +0000598 C.emitReport(report);
Jordy Rosed5af0e12011-06-15 05:52:56 +0000599
600 return NULL;
601 }
602
603 // From now on, assume an overflow didn't occur.
604 assert(stateOkay);
605 state = stateOkay;
606 }
607
608 return state;
609}
610
Ted Kremenek8bef8232012-01-26 21:29:00 +0000611ProgramStateRef CStringChecker::setCStringLength(ProgramStateRef state,
Jordy Rosee64f3112010-08-16 07:51:42 +0000612 const MemRegion *MR,
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000613 SVal strLength) {
614 assert(!strLength.isUndef() && "Attempt to set an undefined string length");
Jordy Rosee64f3112010-08-16 07:51:42 +0000615
616 MR = MR->StripCasts();
617
618 switch (MR->getKind()) {
619 case MemRegion::StringRegionKind:
620 // FIXME: This can happen if we strcpy() into a string region. This is
621 // undefined [C99 6.4.5p6], but we should still warn about it.
622 return state;
623
624 case MemRegion::SymbolicRegionKind:
625 case MemRegion::AllocaRegionKind:
626 case MemRegion::VarRegionKind:
627 case MemRegion::FieldRegionKind:
628 case MemRegion::ObjCIvarRegionKind:
Jordy Rose210c05b2011-06-15 05:14:03 +0000629 // These are the types we can currently track string lengths for.
630 break;
Jordy Rosee64f3112010-08-16 07:51:42 +0000631
632 case MemRegion::ElementRegionKind:
633 // FIXME: Handle element regions by upper-bounding the parent region's
634 // string length.
635 return state;
636
637 default:
638 // Other regions (mostly non-data) can't have a reliable C string length.
639 // For now, just ignore the change.
640 // FIXME: These are rare but not impossible. We should output some kind of
641 // warning for things like strcpy((char[]){'a', 0}, "b");
642 return state;
643 }
Jordy Rose210c05b2011-06-15 05:14:03 +0000644
645 if (strLength.isUnknown())
646 return state->remove<CStringLength>(MR);
647
648 return state->set<CStringLength>(MR, strLength);
Jordy Rosee64f3112010-08-16 07:51:42 +0000649}
650
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000651SVal CStringChecker::getCStringLengthForRegion(CheckerContext &C,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000652 ProgramStateRef &state,
Jordy Rosea5261542010-08-14 21:02:52 +0000653 const Expr *Ex,
Jordy Rosed5af0e12011-06-15 05:52:56 +0000654 const MemRegion *MR,
655 bool hypothetical) {
656 if (!hypothetical) {
657 // If there's a recorded length, go ahead and return it.
658 const SVal *Recorded = state->get<CStringLength>(MR);
659 if (Recorded)
660 return *Recorded;
661 }
Jordy Rosea5261542010-08-14 21:02:52 +0000662
663 // Otherwise, get a new symbol and update the state.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000664 SValBuilder &svalBuilder = C.getSValBuilder();
665 QualType sizeTy = svalBuilder.getContext().getSizeType();
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000666 SVal strLength = svalBuilder.getMetadataSymbolVal(CStringChecker::getTag(),
Ted Kremenek66c486f2012-08-22 06:26:15 +0000667 MR, Ex, sizeTy,
668 C.blockCount());
Jordy Rosed5af0e12011-06-15 05:52:56 +0000669
670 if (!hypothetical)
671 state = state->set<CStringLength>(MR, strLength);
672
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000673 return strLength;
Jordy Rosea5261542010-08-14 21:02:52 +0000674}
675
Ted Kremenek8bef8232012-01-26 21:29:00 +0000676SVal CStringChecker::getCStringLength(CheckerContext &C, ProgramStateRef &state,
Jordy Rosed5af0e12011-06-15 05:52:56 +0000677 const Expr *Ex, SVal Buf,
678 bool hypothetical) const {
Jordy Rose19c5dd12010-07-27 01:37:31 +0000679 const MemRegion *MR = Buf.getAsRegion();
680 if (!MR) {
681 // If we can't get a region, see if it's something we /know/ isn't a
682 // C string. In the context of locations, the only time we can issue such
683 // a warning is for labels.
David Blaikie5251abe2013-02-20 05:52:05 +0000684 if (llvm::Optional<loc::GotoLabel> Label = Buf.getAs<loc::GotoLabel>()) {
Anna Zaks57300762012-02-07 00:56:14 +0000685 if (!Filter.CheckCStringNotNullTerm)
686 return UndefinedVal();
687
Anna Zaks0bd6b112011-10-26 21:06:34 +0000688 if (ExplodedNode *N = C.addTransition(state)) {
Jordy Rose19c5dd12010-07-27 01:37:31 +0000689 if (!BT_NotCString)
Anna Zaks57300762012-02-07 00:56:14 +0000690 BT_NotCString.reset(new BuiltinBug("Unix API",
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000691 "Argument is not a null-terminated string."));
Jordy Rose19c5dd12010-07-27 01:37:31 +0000692
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000693 SmallString<120> buf;
Jordy Rose19c5dd12010-07-27 01:37:31 +0000694 llvm::raw_svector_ostream os(buf);
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000695 assert(CurrentFunctionDescription);
696 os << "Argument to " << CurrentFunctionDescription
697 << " is the address of the label '" << Label->getLabel()->getName()
Jordy Rose19c5dd12010-07-27 01:37:31 +0000698 << "', which is not a null-terminated string";
699
700 // Generate a report for this bug.
Anna Zakse172e8b2011-08-17 23:00:25 +0000701 BugReport *report = new BugReport(*BT_NotCString,
Jordy Rose19c5dd12010-07-27 01:37:31 +0000702 os.str(), N);
703
704 report->addRange(Ex->getSourceRange());
Jordan Rose785950e2012-11-02 01:53:40 +0000705 C.emitReport(report);
Jordy Rose19c5dd12010-07-27 01:37:31 +0000706 }
Jordy Rose19c5dd12010-07-27 01:37:31 +0000707 return UndefinedVal();
Anna Zaks57300762012-02-07 00:56:14 +0000708
Jordy Rose19c5dd12010-07-27 01:37:31 +0000709 }
710
Jordy Rosea5261542010-08-14 21:02:52 +0000711 // If it's not a region and not a label, give up.
712 return UnknownVal();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000713 }
714
Jordy Rosea5261542010-08-14 21:02:52 +0000715 // If we have a region, strip casts from it and see if we can figure out
716 // its length. For anything we can't figure out, just return UnknownVal.
717 MR = MR->StripCasts();
718
719 switch (MR->getKind()) {
720 case MemRegion::StringRegionKind: {
721 // Modifying the contents of string regions is undefined [C99 6.4.5p6],
722 // so we can assume that the byte length is the correct C string length.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000723 SValBuilder &svalBuilder = C.getSValBuilder();
724 QualType sizeTy = svalBuilder.getContext().getSizeType();
725 const StringLiteral *strLit = cast<StringRegion>(MR)->getStringLiteral();
726 return svalBuilder.makeIntVal(strLit->getByteLength(), sizeTy);
Jordy Rosea5261542010-08-14 21:02:52 +0000727 }
728 case MemRegion::SymbolicRegionKind:
729 case MemRegion::AllocaRegionKind:
730 case MemRegion::VarRegionKind:
731 case MemRegion::FieldRegionKind:
732 case MemRegion::ObjCIvarRegionKind:
Jordy Rosed5af0e12011-06-15 05:52:56 +0000733 return getCStringLengthForRegion(C, state, Ex, MR, hypothetical);
Jordy Rosea5261542010-08-14 21:02:52 +0000734 case MemRegion::CompoundLiteralRegionKind:
735 // FIXME: Can we track this? Is it necessary?
736 return UnknownVal();
737 case MemRegion::ElementRegionKind:
738 // FIXME: How can we handle this? It's not good enough to subtract the
739 // offset from the base string length; consider "123\x00567" and &a[5].
740 return UnknownVal();
741 default:
742 // Other regions (mostly non-data) can't have a reliable C string length.
743 // In this case, an error is emitted and UndefinedVal is returned.
744 // The caller should always be prepared to handle this case.
Anna Zaks57300762012-02-07 00:56:14 +0000745 if (!Filter.CheckCStringNotNullTerm)
746 return UndefinedVal();
747
Anna Zaks0bd6b112011-10-26 21:06:34 +0000748 if (ExplodedNode *N = C.addTransition(state)) {
Jordy Rosea5261542010-08-14 21:02:52 +0000749 if (!BT_NotCString)
Anna Zaks57300762012-02-07 00:56:14 +0000750 BT_NotCString.reset(new BuiltinBug("Unix API",
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000751 "Argument is not a null-terminated string."));
Jordy Rosea5261542010-08-14 21:02:52 +0000752
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000753 SmallString<120> buf;
Jordy Rosea5261542010-08-14 21:02:52 +0000754 llvm::raw_svector_ostream os(buf);
755
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000756 assert(CurrentFunctionDescription);
757 os << "Argument to " << CurrentFunctionDescription << " is ";
Jordy Rosea5261542010-08-14 21:02:52 +0000758
759 if (SummarizeRegion(os, C.getASTContext(), MR))
760 os << ", which is not a null-terminated string";
761 else
762 os << "not a null-terminated string";
763
764 // Generate a report for this bug.
Anna Zakse172e8b2011-08-17 23:00:25 +0000765 BugReport *report = new BugReport(*BT_NotCString,
Jordy Rosea5261542010-08-14 21:02:52 +0000766 os.str(), N);
767
768 report->addRange(Ex->getSourceRange());
Jordan Rose785950e2012-11-02 01:53:40 +0000769 C.emitReport(report);
Jordy Rosea5261542010-08-14 21:02:52 +0000770 }
771
772 return UndefinedVal();
773 }
Jordy Rose19c5dd12010-07-27 01:37:31 +0000774}
775
Lenny Maiorani318dd922011-04-12 17:08:43 +0000776const StringLiteral *CStringChecker::getCStringLiteral(CheckerContext &C,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000777 ProgramStateRef &state, const Expr *expr, SVal val) const {
Lenny Maiorani318dd922011-04-12 17:08:43 +0000778
779 // Get the memory region pointed to by the val.
780 const MemRegion *bufRegion = val.getAsRegion();
781 if (!bufRegion)
782 return NULL;
783
784 // Strip casts off the memory region.
785 bufRegion = bufRegion->StripCasts();
786
787 // Cast the memory region to a string region.
788 const StringRegion *strRegion= dyn_cast<StringRegion>(bufRegion);
789 if (!strRegion)
790 return NULL;
791
792 // Return the actual string in the string region.
793 return strRegion->getStringLiteral();
794}
795
Ted Kremenek8bef8232012-01-26 21:29:00 +0000796ProgramStateRef CStringChecker::InvalidateBuffer(CheckerContext &C,
797 ProgramStateRef state,
Jordy Rosee64f3112010-08-16 07:51:42 +0000798 const Expr *E, SVal V) {
David Blaikie5251abe2013-02-20 05:52:05 +0000799 llvm::Optional<Loc> L = V.getAs<Loc>();
Jordy Rosee64f3112010-08-16 07:51:42 +0000800 if (!L)
801 return state;
802
803 // FIXME: This is a simplified version of what's in CFRefCount.cpp -- it makes
804 // some assumptions about the value that CFRefCount can't. Even so, it should
805 // probably be refactored.
David Blaikie5251abe2013-02-20 05:52:05 +0000806 if (llvm::Optional<loc::MemRegionVal> MR = L->getAs<loc::MemRegionVal>()) {
Jordy Rosee64f3112010-08-16 07:51:42 +0000807 const MemRegion *R = MR->getRegion()->StripCasts();
808
809 // Are we dealing with an ElementRegion? If so, we should be invalidating
810 // the super-region.
811 if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
812 R = ER->getSuperRegion();
813 // FIXME: What about layers of ElementRegions?
814 }
815
816 // Invalidate this region.
Ted Kremenek3133f792012-02-17 23:13:45 +0000817 const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
Anna Zaksbf53dfa2012-12-20 00:38:25 +0000818 return state->invalidateRegions(R, E, C.blockCount(), LCtx,
Anna Zaks64eb0702013-01-16 01:35:54 +0000819 /*CausesPointerEscape*/ false);
Jordy Rosee64f3112010-08-16 07:51:42 +0000820 }
821
822 // If we have a non-region value by chance, just remove the binding.
823 // FIXME: is this necessary or correct? This handles the non-Region
824 // cases. Is it ever valid to store to these?
Ted Kremenek56a46b52012-08-22 06:37:46 +0000825 return state->killBinding(*L);
Jordy Rosee64f3112010-08-16 07:51:42 +0000826}
827
Ted Kremenek9c378f72011-08-12 23:37:29 +0000828bool CStringChecker::SummarizeRegion(raw_ostream &os, ASTContext &Ctx,
Jordy Rose19c5dd12010-07-27 01:37:31 +0000829 const MemRegion *MR) {
Ted Kremenek96979342011-08-12 20:02:48 +0000830 const TypedValueRegion *TVR = dyn_cast<TypedValueRegion>(MR);
Jordy Rose19c5dd12010-07-27 01:37:31 +0000831
Jordy Rose096aef92011-08-12 21:41:07 +0000832 switch (MR->getKind()) {
Jordy Rose19c5dd12010-07-27 01:37:31 +0000833 case MemRegion::FunctionTextRegionKind: {
Anna Zaks5fc1d0c2012-09-17 19:13:56 +0000834 const NamedDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000835 if (FD)
Benjamin Kramerb8989f22011-10-14 18:45:37 +0000836 os << "the address of the function '" << *FD << '\'';
Jordy Rose19c5dd12010-07-27 01:37:31 +0000837 else
838 os << "the address of a function";
839 return true;
840 }
841 case MemRegion::BlockTextRegionKind:
842 os << "block text";
843 return true;
844 case MemRegion::BlockDataRegionKind:
845 os << "a block";
846 return true;
847 case MemRegion::CXXThisRegionKind:
Zhongxing Xu02fe28c2010-11-26 08:52:48 +0000848 case MemRegion::CXXTempObjectRegionKind:
Ted Kremenek96979342011-08-12 20:02:48 +0000849 os << "a C++ temp object of type " << TVR->getValueType().getAsString();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000850 return true;
851 case MemRegion::VarRegionKind:
Ted Kremenek96979342011-08-12 20:02:48 +0000852 os << "a variable of type" << TVR->getValueType().getAsString();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000853 return true;
854 case MemRegion::FieldRegionKind:
Ted Kremenek96979342011-08-12 20:02:48 +0000855 os << "a field of type " << TVR->getValueType().getAsString();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000856 return true;
857 case MemRegion::ObjCIvarRegionKind:
Ted Kremenek96979342011-08-12 20:02:48 +0000858 os << "an instance variable of type " << TVR->getValueType().getAsString();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000859 return true;
860 default:
861 return false;
862 }
863}
864
Jordy Rosed325ffb2010-07-08 23:57:29 +0000865//===----------------------------------------------------------------------===//
Ted Kremenek9c149532010-12-01 21:57:22 +0000866// evaluation of individual function calls.
Jordy Rosed325ffb2010-07-08 23:57:29 +0000867//===----------------------------------------------------------------------===//
868
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000869void CStringChecker::evalCopyCommon(CheckerContext &C,
870 const CallExpr *CE,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000871 ProgramStateRef state,
Jordy Rosed325ffb2010-07-08 23:57:29 +0000872 const Expr *Size, const Expr *Dest,
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000873 const Expr *Source, bool Restricted,
874 bool IsMempcpy) const {
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000875 CurrentFunctionDescription = "memory copy function";
876
Jordy Rosed325ffb2010-07-08 23:57:29 +0000877 // See if the size argument is zero.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000878 const LocationContext *LCtx = C.getLocationContext();
879 SVal sizeVal = state->getSVal(Size, LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000880 QualType sizeTy = Size->getType();
Jordy Rosed325ffb2010-07-08 23:57:29 +0000881
Ted Kremenek8bef8232012-01-26 21:29:00 +0000882 ProgramStateRef stateZeroSize, stateNonZeroSize;
Jordy Rose1e022412011-06-16 05:51:02 +0000883 llvm::tie(stateZeroSize, stateNonZeroSize) =
884 assumeZero(C, state, sizeVal, sizeTy);
Jordy Rosed325ffb2010-07-08 23:57:29 +0000885
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000886 // Get the value of the Dest.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000887 SVal destVal = state->getSVal(Dest, LCtx);
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000888
889 // If the size is zero, there won't be any actual memory access, so
890 // just bind the return value to the destination buffer and return.
Anna Zaksdd160f32012-05-03 18:21:28 +0000891 if (stateZeroSize && !stateNonZeroSize) {
Ted Kremenek5eca4822012-01-06 22:09:28 +0000892 stateZeroSize = stateZeroSize->BindExpr(CE, LCtx, destVal);
Anna Zaks0bd6b112011-10-26 21:06:34 +0000893 C.addTransition(stateZeroSize);
Anna Zaksdd160f32012-05-03 18:21:28 +0000894 return;
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000895 }
Jordy Rosed325ffb2010-07-08 23:57:29 +0000896
897 // If the size can be nonzero, we have to check the other arguments.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000898 if (stateNonZeroSize) {
Jordy Rose22d27172011-06-04 00:04:22 +0000899 state = stateNonZeroSize;
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000900
901 // Ensure the destination is not null. If it is NULL there will be a
902 // NULL pointer dereference.
903 state = checkNonNull(C, state, Dest, destVal);
904 if (!state)
905 return;
906
907 // Get the value of the Src.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000908 SVal srcVal = state->getSVal(Source, LCtx);
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000909
910 // Ensure the source is not null. If it is NULL there will be a
911 // NULL pointer dereference.
912 state = checkNonNull(C, state, Source, srcVal);
913 if (!state)
914 return;
915
Jordy Rose7182b962011-06-04 01:50:25 +0000916 // Ensure the accesses are valid and that the buffers do not overlap.
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000917 const char * const writeWarning =
918 "Memory copy function overflows destination buffer";
Jordy Rosee64f3112010-08-16 07:51:42 +0000919 state = CheckBufferAccess(C, state, Size, Dest, Source,
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000920 writeWarning, /* sourceWarning = */ NULL);
Jordy Rosed325ffb2010-07-08 23:57:29 +0000921 if (Restricted)
922 state = CheckOverlap(C, state, Size, Dest, Source);
Jordy Rosee64f3112010-08-16 07:51:42 +0000923
Jordy Rose7182b962011-06-04 01:50:25 +0000924 if (!state)
925 return;
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000926
Jordy Rose7182b962011-06-04 01:50:25 +0000927 // If this is mempcpy, get the byte after the last byte copied and
928 // bind the expr.
929 if (IsMempcpy) {
David Blaikie5251abe2013-02-20 05:52:05 +0000930 loc::MemRegionVal destRegVal = destVal.castAs<loc::MemRegionVal>();
Jordy Rose7182b962011-06-04 01:50:25 +0000931
932 // Get the length to copy.
David Blaikie5251abe2013-02-20 05:52:05 +0000933 if (llvm::Optional<NonLoc> lenValNonLoc = sizeVal.getAs<NonLoc>()) {
Jordy Rose7182b962011-06-04 01:50:25 +0000934 // Get the byte after the last byte copied.
935 SVal lastElement = C.getSValBuilder().evalBinOpLN(state, BO_Add,
David Blaikie5251abe2013-02-20 05:52:05 +0000936 destRegVal,
Jordy Rose7182b962011-06-04 01:50:25 +0000937 *lenValNonLoc,
938 Dest->getType());
939
940 // The byte after the last byte copied is the return value.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000941 state = state->BindExpr(CE, LCtx, lastElement);
Jordy Rose3f8bb2f2011-06-04 01:47:27 +0000942 } else {
Jordy Rose7182b962011-06-04 01:50:25 +0000943 // If we don't know how much we copied, we can at least
944 // conjure a return value for later.
Ted Kremenek66c486f2012-08-22 06:26:15 +0000945 SVal result = C.getSValBuilder().conjureSymbolVal(0, CE, LCtx,
946 C.blockCount());
Ted Kremenek5eca4822012-01-06 22:09:28 +0000947 state = state->BindExpr(CE, LCtx, result);
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000948 }
949
Jordy Rose7182b962011-06-04 01:50:25 +0000950 } else {
951 // All other copies return the destination buffer.
952 // (Well, bcopy() has a void return type, but this won't hurt.)
Ted Kremenek5eca4822012-01-06 22:09:28 +0000953 state = state->BindExpr(CE, LCtx, destVal);
Jordy Rosee64f3112010-08-16 07:51:42 +0000954 }
Jordy Rose7182b962011-06-04 01:50:25 +0000955
956 // Invalidate the destination.
957 // FIXME: Even if we can't perfectly model the copy, we should see if we
958 // can use LazyCompoundVals to copy the source values into the destination.
959 // This would probably remove any existing bindings past the end of the
960 // copied region, but that's still an improvement over blank invalidation.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000961 state = InvalidateBuffer(C, state, Dest,
962 state->getSVal(Dest, C.getLocationContext()));
Anna Zaks0bd6b112011-10-26 21:06:34 +0000963 C.addTransition(state);
Jordy Rosed325ffb2010-07-08 23:57:29 +0000964 }
965}
966
967
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000968void CStringChecker::evalMemcpy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +0000969 if (CE->getNumArgs() < 3)
970 return;
971
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000972 // void *memcpy(void *restrict dst, const void *restrict src, size_t n);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000973 // The return value is the address of the destination buffer.
Jordy Rosed325ffb2010-07-08 23:57:29 +0000974 const Expr *Dest = CE->getArg(0);
Ted Kremenek8bef8232012-01-26 21:29:00 +0000975 ProgramStateRef state = C.getState();
Jordy Rose3f8bb2f2011-06-04 01:47:27 +0000976
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000977 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1), true);
978}
979
980void CStringChecker::evalMempcpy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +0000981 if (CE->getNumArgs() < 3)
982 return;
983
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000984 // void *mempcpy(void *restrict dst, const void *restrict src, size_t n);
985 // The return value is a pointer to the byte following the last written byte.
986 const Expr *Dest = CE->getArg(0);
Ted Kremenek8bef8232012-01-26 21:29:00 +0000987 ProgramStateRef state = C.getState();
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000988
989 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1), true, true);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000990}
991
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000992void CStringChecker::evalMemmove(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +0000993 if (CE->getNumArgs() < 3)
994 return;
995
Jordy Rosed325ffb2010-07-08 23:57:29 +0000996 // void *memmove(void *dst, const void *src, size_t n);
997 // The return value is the address of the destination buffer.
998 const Expr *Dest = CE->getArg(0);
Ted Kremenek8bef8232012-01-26 21:29:00 +0000999 ProgramStateRef state = C.getState();
Jordy Rose3f8bb2f2011-06-04 01:47:27 +00001000
Lenny Maioranib8b875b2011-03-31 21:36:53 +00001001 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1));
Jordy Rosed325ffb2010-07-08 23:57:29 +00001002}
1003
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001004void CStringChecker::evalBcopy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001005 if (CE->getNumArgs() < 3)
1006 return;
1007
Jordy Rosed325ffb2010-07-08 23:57:29 +00001008 // void bcopy(const void *src, void *dst, size_t n);
Lenny Maioranib8b875b2011-03-31 21:36:53 +00001009 evalCopyCommon(C, CE, C.getState(),
1010 CE->getArg(2), CE->getArg(1), CE->getArg(0));
Jordy Rosed325ffb2010-07-08 23:57:29 +00001011}
1012
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001013void CStringChecker::evalMemcmp(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001014 if (CE->getNumArgs() < 3)
1015 return;
1016
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001017 // int memcmp(const void *s1, const void *s2, size_t n);
Jordy Rose9e49d9f2011-06-20 02:06:40 +00001018 CurrentFunctionDescription = "memory comparison function";
1019
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001020 const Expr *Left = CE->getArg(0);
1021 const Expr *Right = CE->getArg(1);
1022 const Expr *Size = CE->getArg(2);
1023
Ted Kremenek8bef8232012-01-26 21:29:00 +00001024 ProgramStateRef state = C.getState();
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001025 SValBuilder &svalBuilder = C.getSValBuilder();
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001026
Jordy Rosed325ffb2010-07-08 23:57:29 +00001027 // See if the size argument is zero.
Ted Kremenek5eca4822012-01-06 22:09:28 +00001028 const LocationContext *LCtx = C.getLocationContext();
1029 SVal sizeVal = state->getSVal(Size, LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001030 QualType sizeTy = Size->getType();
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001031
Ted Kremenek8bef8232012-01-26 21:29:00 +00001032 ProgramStateRef stateZeroSize, stateNonZeroSize;
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001033 llvm::tie(stateZeroSize, stateNonZeroSize) =
1034 assumeZero(C, state, sizeVal, sizeTy);
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001035
Jordy Rosed325ffb2010-07-08 23:57:29 +00001036 // If the size can be zero, the result will be 0 in that case, and we don't
1037 // have to check either of the buffers.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001038 if (stateZeroSize) {
1039 state = stateZeroSize;
Ted Kremenek5eca4822012-01-06 22:09:28 +00001040 state = state->BindExpr(CE, LCtx,
1041 svalBuilder.makeZeroVal(CE->getType()));
Anna Zaks0bd6b112011-10-26 21:06:34 +00001042 C.addTransition(state);
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001043 }
1044
Jordy Rosed325ffb2010-07-08 23:57:29 +00001045 // If the size can be nonzero, we have to check the other arguments.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001046 if (stateNonZeroSize) {
1047 state = stateNonZeroSize;
Jordy Rosed325ffb2010-07-08 23:57:29 +00001048 // If we know the two buffers are the same, we know the result is 0.
1049 // First, get the two buffers' addresses. Another checker will have already
1050 // made sure they're not undefined.
Ted Kremenek5eca4822012-01-06 22:09:28 +00001051 DefinedOrUnknownSVal LV =
David Blaikie5251abe2013-02-20 05:52:05 +00001052 state->getSVal(Left, LCtx).castAs<DefinedOrUnknownSVal>();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001053 DefinedOrUnknownSVal RV =
David Blaikie5251abe2013-02-20 05:52:05 +00001054 state->getSVal(Right, LCtx).castAs<DefinedOrUnknownSVal>();
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001055
Jordy Rosed325ffb2010-07-08 23:57:29 +00001056 // See if they are the same.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001057 DefinedOrUnknownSVal SameBuf = svalBuilder.evalEQ(state, LV, RV);
Ted Kremenek8bef8232012-01-26 21:29:00 +00001058 ProgramStateRef StSameBuf, StNotSameBuf;
Ted Kremenek28f47b92010-12-01 22:16:56 +00001059 llvm::tie(StSameBuf, StNotSameBuf) = state->assume(SameBuf);
Jordy Rosed325ffb2010-07-08 23:57:29 +00001060
Jordy Rose1e022412011-06-16 05:51:02 +00001061 // If the two arguments might be the same buffer, we know the result is 0,
Jordy Rosed325ffb2010-07-08 23:57:29 +00001062 // and we only need to check one size.
1063 if (StSameBuf) {
1064 state = StSameBuf;
1065 state = CheckBufferAccess(C, state, Size, Left);
1066 if (state) {
Ted Kremenek5eca4822012-01-06 22:09:28 +00001067 state = StSameBuf->BindExpr(CE, LCtx,
1068 svalBuilder.makeZeroVal(CE->getType()));
Anna Zaks0bd6b112011-10-26 21:06:34 +00001069 C.addTransition(state);
Jordy Rosed325ffb2010-07-08 23:57:29 +00001070 }
1071 }
1072
1073 // If the two arguments might be different buffers, we have to check the
1074 // size of both of them.
1075 if (StNotSameBuf) {
1076 state = StNotSameBuf;
1077 state = CheckBufferAccess(C, state, Size, Left, Right);
1078 if (state) {
1079 // The return value is the comparison result, which we don't know.
Ted Kremenek66c486f2012-08-22 06:26:15 +00001080 SVal CmpV = svalBuilder.conjureSymbolVal(0, CE, LCtx, C.blockCount());
Ted Kremenek5eca4822012-01-06 22:09:28 +00001081 state = state->BindExpr(CE, LCtx, CmpV);
Anna Zaks0bd6b112011-10-26 21:06:34 +00001082 C.addTransition(state);
Jordy Rosed325ffb2010-07-08 23:57:29 +00001083 }
1084 }
1085 }
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001086}
1087
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001088void CStringChecker::evalstrLength(CheckerContext &C,
1089 const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001090 if (CE->getNumArgs() < 1)
1091 return;
1092
Jordy Rose19c5dd12010-07-27 01:37:31 +00001093 // size_t strlen(const char *s);
Ted Kremenekbe4242c2011-02-22 04:55:05 +00001094 evalstrLengthCommon(C, CE, /* IsStrnlen = */ false);
1095}
1096
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001097void CStringChecker::evalstrnLength(CheckerContext &C,
1098 const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001099 if (CE->getNumArgs() < 2)
1100 return;
1101
Ted Kremenekbe4242c2011-02-22 04:55:05 +00001102 // size_t strnlen(const char *s, size_t maxlen);
1103 evalstrLengthCommon(C, CE, /* IsStrnlen = */ true);
1104}
1105
1106void CStringChecker::evalstrLengthCommon(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001107 bool IsStrnlen) const {
Jordy Rose9e49d9f2011-06-20 02:06:40 +00001108 CurrentFunctionDescription = "string length function";
Ted Kremenek8bef8232012-01-26 21:29:00 +00001109 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001110 const LocationContext *LCtx = C.getLocationContext();
Jordy Rose793bff32011-06-14 01:15:31 +00001111
1112 if (IsStrnlen) {
1113 const Expr *maxlenExpr = CE->getArg(1);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001114 SVal maxlenVal = state->getSVal(maxlenExpr, LCtx);
Jordy Rose793bff32011-06-14 01:15:31 +00001115
Ted Kremenek8bef8232012-01-26 21:29:00 +00001116 ProgramStateRef stateZeroSize, stateNonZeroSize;
Jordy Rose793bff32011-06-14 01:15:31 +00001117 llvm::tie(stateZeroSize, stateNonZeroSize) =
1118 assumeZero(C, state, maxlenVal, maxlenExpr->getType());
1119
1120 // If the size can be zero, the result will be 0 in that case, and we don't
1121 // have to check the string itself.
1122 if (stateZeroSize) {
1123 SVal zero = C.getSValBuilder().makeZeroVal(CE->getType());
Ted Kremenek5eca4822012-01-06 22:09:28 +00001124 stateZeroSize = stateZeroSize->BindExpr(CE, LCtx, zero);
Anna Zaks0bd6b112011-10-26 21:06:34 +00001125 C.addTransition(stateZeroSize);
Jordy Rose793bff32011-06-14 01:15:31 +00001126 }
1127
1128 // If the size is GUARANTEED to be zero, we're done!
1129 if (!stateNonZeroSize)
1130 return;
1131
1132 // Otherwise, record the assumption that the size is nonzero.
1133 state = stateNonZeroSize;
1134 }
1135
1136 // Check that the string argument is non-null.
Jordy Rose19c5dd12010-07-27 01:37:31 +00001137 const Expr *Arg = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001138 SVal ArgVal = state->getSVal(Arg, LCtx);
Jordy Rose19c5dd12010-07-27 01:37:31 +00001139
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001140 state = checkNonNull(C, state, Arg, ArgVal);
Jordy Rose19c5dd12010-07-27 01:37:31 +00001141
Jordy Rosebd32bee2011-06-14 01:26:48 +00001142 if (!state)
1143 return;
Jordy Rosea5261542010-08-14 21:02:52 +00001144
Jordy Rosebd32bee2011-06-14 01:26:48 +00001145 SVal strLength = getCStringLength(C, state, Arg, ArgVal);
Jordy Rosea5261542010-08-14 21:02:52 +00001146
Jordy Rosebd32bee2011-06-14 01:26:48 +00001147 // If the argument isn't a valid C string, there's no valid state to
1148 // transition to.
1149 if (strLength.isUndef())
1150 return;
Jordy Rose793bff32011-06-14 01:15:31 +00001151
Jordy Rosebd32bee2011-06-14 01:26:48 +00001152 DefinedOrUnknownSVal result = UnknownVal();
Jordy Rose793bff32011-06-14 01:15:31 +00001153
Jordy Rosebd32bee2011-06-14 01:26:48 +00001154 // If the check is for strnlen() then bind the return value to no more than
1155 // the maxlen value.
1156 if (IsStrnlen) {
Jordy Roseee2fde12011-06-16 05:56:50 +00001157 QualType cmpTy = C.getSValBuilder().getConditionType();
Jordy Rose793bff32011-06-14 01:15:31 +00001158
Jordy Rosebd32bee2011-06-14 01:26:48 +00001159 // It's a little unfortunate to be getting this again,
1160 // but it's not that expensive...
1161 const Expr *maxlenExpr = CE->getArg(1);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001162 SVal maxlenVal = state->getSVal(maxlenExpr, LCtx);
Ted Kremenekbe4242c2011-02-22 04:55:05 +00001163
David Blaikie5251abe2013-02-20 05:52:05 +00001164 llvm::Optional<NonLoc> strLengthNL = strLength.getAs<NonLoc>();
1165 llvm::Optional<NonLoc> maxlenValNL = maxlenVal.getAs<NonLoc>();
Ted Kremenekbe4242c2011-02-22 04:55:05 +00001166
Jordy Rosebd32bee2011-06-14 01:26:48 +00001167 if (strLengthNL && maxlenValNL) {
Ted Kremenek8bef8232012-01-26 21:29:00 +00001168 ProgramStateRef stateStringTooLong, stateStringNotTooLong;
Jordy Rose793bff32011-06-14 01:15:31 +00001169
Jordy Rosebd32bee2011-06-14 01:26:48 +00001170 // Check if the strLength is greater than the maxlen.
1171 llvm::tie(stateStringTooLong, stateStringNotTooLong) =
David Blaikie5251abe2013-02-20 05:52:05 +00001172 state->assume(C.getSValBuilder().evalBinOpNN(
1173 state, BO_GT, *strLengthNL, *maxlenValNL, cmpTy)
1174 .castAs<DefinedOrUnknownSVal>());
Jordy Rose793bff32011-06-14 01:15:31 +00001175
Jordy Rosebd32bee2011-06-14 01:26:48 +00001176 if (stateStringTooLong && !stateStringNotTooLong) {
1177 // If the string is longer than maxlen, return maxlen.
1178 result = *maxlenValNL;
1179 } else if (stateStringNotTooLong && !stateStringTooLong) {
1180 // If the string is shorter than maxlen, return its length.
1181 result = *strLengthNL;
Ted Kremenekbe4242c2011-02-22 04:55:05 +00001182 }
1183 }
1184
Jordy Rosebd32bee2011-06-14 01:26:48 +00001185 if (result.isUnknown()) {
1186 // If we don't have enough information for a comparison, there's
1187 // no guarantee the full string length will actually be returned.
1188 // All we know is the return value is the min of the string length
1189 // and the limit. This is better than nothing.
Ted Kremenek66c486f2012-08-22 06:26:15 +00001190 result = C.getSValBuilder().conjureSymbolVal(0, CE, LCtx, C.blockCount());
David Blaikie5251abe2013-02-20 05:52:05 +00001191 NonLoc resultNL = result.castAs<NonLoc>();
Jordy Rosebd32bee2011-06-14 01:26:48 +00001192
1193 if (strLengthNL) {
David Blaikie5251abe2013-02-20 05:52:05 +00001194 state = state->assume(C.getSValBuilder().evalBinOpNN(
1195 state, BO_LE, resultNL, *strLengthNL, cmpTy)
1196 .castAs<DefinedOrUnknownSVal>(), true);
Jordy Rosebd32bee2011-06-14 01:26:48 +00001197 }
1198
1199 if (maxlenValNL) {
David Blaikie5251abe2013-02-20 05:52:05 +00001200 state = state->assume(C.getSValBuilder().evalBinOpNN(
1201 state, BO_LE, resultNL, *maxlenValNL, cmpTy)
1202 .castAs<DefinedOrUnknownSVal>(), true);
Jordy Rosebd32bee2011-06-14 01:26:48 +00001203 }
1204 }
1205
1206 } else {
1207 // This is a plain strlen(), not strnlen().
David Blaikie5251abe2013-02-20 05:52:05 +00001208 result = strLength.castAs<DefinedOrUnknownSVal>();
Jordy Rosebd32bee2011-06-14 01:26:48 +00001209
1210 // If we don't know the length of the string, conjure a return
1211 // value, so it can be used in constraints, at least.
1212 if (result.isUnknown()) {
Ted Kremenek66c486f2012-08-22 06:26:15 +00001213 result = C.getSValBuilder().conjureSymbolVal(0, CE, LCtx, C.blockCount());
Jordy Rosebd32bee2011-06-14 01:26:48 +00001214 }
Jordy Rose19c5dd12010-07-27 01:37:31 +00001215 }
Jordy Rosebd32bee2011-06-14 01:26:48 +00001216
1217 // Bind the return value.
1218 assert(!result.isUnknown() && "Should have conjured a value by now");
Ted Kremenek5eca4822012-01-06 22:09:28 +00001219 state = state->BindExpr(CE, LCtx, result);
Anna Zaks0bd6b112011-10-26 21:06:34 +00001220 C.addTransition(state);
Jordy Rose19c5dd12010-07-27 01:37:31 +00001221}
1222
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001223void CStringChecker::evalStrcpy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001224 if (CE->getNumArgs() < 2)
1225 return;
1226
Jordy Rosee64f3112010-08-16 07:51:42 +00001227 // char *strcpy(char *restrict dst, const char *restrict src);
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001228 evalStrcpyCommon(C, CE,
1229 /* returnEnd = */ false,
1230 /* isBounded = */ false,
1231 /* isAppending = */ false);
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001232}
1233
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001234void CStringChecker::evalStrncpy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001235 if (CE->getNumArgs() < 3)
1236 return;
1237
Jordy Rosec1525862011-06-04 00:05:23 +00001238 // char *strncpy(char *restrict dst, const char *restrict src, size_t n);
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001239 evalStrcpyCommon(C, CE,
1240 /* returnEnd = */ false,
1241 /* isBounded = */ true,
1242 /* isAppending = */ false);
Jordy Rosee64f3112010-08-16 07:51:42 +00001243}
1244
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001245void CStringChecker::evalStpcpy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001246 if (CE->getNumArgs() < 2)
1247 return;
1248
Jordy Rosee64f3112010-08-16 07:51:42 +00001249 // char *stpcpy(char *restrict dst, const char *restrict src);
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001250 evalStrcpyCommon(C, CE,
1251 /* returnEnd = */ true,
1252 /* isBounded = */ false,
1253 /* isAppending = */ false);
1254}
1255
1256void CStringChecker::evalStrcat(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001257 if (CE->getNumArgs() < 2)
1258 return;
1259
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001260 //char *strcat(char *restrict s1, const char *restrict s2);
1261 evalStrcpyCommon(C, CE,
1262 /* returnEnd = */ false,
1263 /* isBounded = */ false,
1264 /* isAppending = */ true);
1265}
1266
1267void CStringChecker::evalStrncat(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001268 if (CE->getNumArgs() < 3)
1269 return;
1270
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001271 //char *strncat(char *restrict s1, const char *restrict s2, size_t n);
1272 evalStrcpyCommon(C, CE,
1273 /* returnEnd = */ false,
1274 /* isBounded = */ true,
1275 /* isAppending = */ true);
Jordy Rosee64f3112010-08-16 07:51:42 +00001276}
1277
Ted Kremenek9c149532010-12-01 21:57:22 +00001278void CStringChecker::evalStrcpyCommon(CheckerContext &C, const CallExpr *CE,
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001279 bool returnEnd, bool isBounded,
1280 bool isAppending) const {
Jordy Rose9e49d9f2011-06-20 02:06:40 +00001281 CurrentFunctionDescription = "string copy function";
Ted Kremenek8bef8232012-01-26 21:29:00 +00001282 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001283 const LocationContext *LCtx = C.getLocationContext();
Jordy Rosee64f3112010-08-16 07:51:42 +00001284
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001285 // Check that the destination is non-null.
Jordy Rosee64f3112010-08-16 07:51:42 +00001286 const Expr *Dst = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001287 SVal DstVal = state->getSVal(Dst, LCtx);
Jordy Rosee64f3112010-08-16 07:51:42 +00001288
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001289 state = checkNonNull(C, state, Dst, DstVal);
Jordy Rosee64f3112010-08-16 07:51:42 +00001290 if (!state)
1291 return;
1292
1293 // Check that the source is non-null.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001294 const Expr *srcExpr = CE->getArg(1);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001295 SVal srcVal = state->getSVal(srcExpr, LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001296 state = checkNonNull(C, state, srcExpr, srcVal);
Jordy Rosee64f3112010-08-16 07:51:42 +00001297 if (!state)
1298 return;
1299
1300 // Get the string length of the source.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001301 SVal strLength = getCStringLength(C, state, srcExpr, srcVal);
Jordy Rosee64f3112010-08-16 07:51:42 +00001302
1303 // If the source isn't a valid C string, give up.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001304 if (strLength.isUndef())
Jordy Rosee64f3112010-08-16 07:51:42 +00001305 return;
1306
Jordy Rosed5af0e12011-06-15 05:52:56 +00001307 SValBuilder &svalBuilder = C.getSValBuilder();
1308 QualType cmpTy = svalBuilder.getConditionType();
Jordy Rose8912aae2011-06-20 21:55:40 +00001309 QualType sizeTy = svalBuilder.getContext().getSizeType();
Jordy Rosed5af0e12011-06-15 05:52:56 +00001310
Jordy Rose8912aae2011-06-20 21:55:40 +00001311 // These two values allow checking two kinds of errors:
1312 // - actual overflows caused by a source that doesn't fit in the destination
1313 // - potential overflows caused by a bound that could exceed the destination
Jordy Rosed5af0e12011-06-15 05:52:56 +00001314 SVal amountCopied = UnknownVal();
Jordy Rose8912aae2011-06-20 21:55:40 +00001315 SVal maxLastElementIndex = UnknownVal();
1316 const char *boundWarning = NULL;
Jordy Rosed5af0e12011-06-15 05:52:56 +00001317
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001318 // If the function is strncpy, strncat, etc... it is bounded.
1319 if (isBounded) {
1320 // Get the max number of characters to copy.
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001321 const Expr *lenExpr = CE->getArg(2);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001322 SVal lenVal = state->getSVal(lenExpr, LCtx);
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001323
Jordy Rosed5af0e12011-06-15 05:52:56 +00001324 // Protect against misdeclared strncpy().
Jordy Rose8912aae2011-06-20 21:55:40 +00001325 lenVal = svalBuilder.evalCast(lenVal, sizeTy, lenExpr->getType());
Jordy Rosed5af0e12011-06-15 05:52:56 +00001326
David Blaikie5251abe2013-02-20 05:52:05 +00001327 llvm::Optional<NonLoc> strLengthNL = strLength.getAs<NonLoc>();
1328 llvm::Optional<NonLoc> lenValNL = lenVal.getAs<NonLoc>();
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001329
Jordy Rosed5af0e12011-06-15 05:52:56 +00001330 // If we know both values, we might be able to figure out how much
1331 // we're copying.
1332 if (strLengthNL && lenValNL) {
Ted Kremenek8bef8232012-01-26 21:29:00 +00001333 ProgramStateRef stateSourceTooLong, stateSourceNotTooLong;
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001334
Jordy Rosed5af0e12011-06-15 05:52:56 +00001335 // Check if the max number to copy is less than the length of the src.
Jordy Rose8912aae2011-06-20 21:55:40 +00001336 // If the bound is equal to the source length, strncpy won't null-
1337 // terminate the result!
David Blaikie5251abe2013-02-20 05:52:05 +00001338 llvm::tie(stateSourceTooLong, stateSourceNotTooLong) = state->assume(
1339 svalBuilder.evalBinOpNN(state, BO_GE, *strLengthNL, *lenValNL, cmpTy)
1340 .castAs<DefinedOrUnknownSVal>());
Jordy Rosed5af0e12011-06-15 05:52:56 +00001341
1342 if (stateSourceTooLong && !stateSourceNotTooLong) {
1343 // Max number to copy is less than the length of the src, so the actual
1344 // strLength copied is the max number arg.
1345 state = stateSourceTooLong;
1346 amountCopied = lenVal;
1347
1348 } else if (!stateSourceTooLong && stateSourceNotTooLong) {
1349 // The source buffer entirely fits in the bound.
1350 state = stateSourceNotTooLong;
1351 amountCopied = strLength;
1352 }
1353 }
1354
Jordy Rose5e5f1502011-06-20 03:49:16 +00001355 // We still want to know if the bound is known to be too large.
Jordy Rose8912aae2011-06-20 21:55:40 +00001356 if (lenValNL) {
1357 if (isAppending) {
1358 // For strncat, the check is strlen(dst) + lenVal < sizeof(dst)
1359
1360 // Get the string length of the destination. If the destination is
1361 // memory that can't have a string length, we shouldn't be copying
1362 // into it anyway.
1363 SVal dstStrLength = getCStringLength(C, state, Dst, DstVal);
1364 if (dstStrLength.isUndef())
1365 return;
1366
David Blaikie5251abe2013-02-20 05:52:05 +00001367 if (llvm::Optional<NonLoc> dstStrLengthNL =
1368 dstStrLength.getAs<NonLoc>()) {
Jordy Rose8912aae2011-06-20 21:55:40 +00001369 maxLastElementIndex = svalBuilder.evalBinOpNN(state, BO_Add,
1370 *lenValNL,
1371 *dstStrLengthNL,
1372 sizeTy);
1373 boundWarning = "Size argument is greater than the free space in the "
1374 "destination buffer";
1375 }
1376
1377 } else {
1378 // For strncpy, this is just checking that lenVal <= sizeof(dst)
1379 // (Yes, strncpy and strncat differ in how they treat termination.
1380 // strncat ALWAYS terminates, but strncpy doesn't.)
Jordy Rose6e4244e2012-05-14 17:58:35 +00001381
1382 // We need a special case for when the copy size is zero, in which
1383 // case strncpy will do no work at all. Our bounds check uses n-1
1384 // as the last element accessed, so n == 0 is problematic.
1385 ProgramStateRef StateZeroSize, StateNonZeroSize;
1386 llvm::tie(StateZeroSize, StateNonZeroSize) =
1387 assumeZero(C, state, *lenValNL, sizeTy);
1388
1389 // If the size is known to be zero, we're done.
1390 if (StateZeroSize && !StateNonZeroSize) {
1391 StateZeroSize = StateZeroSize->BindExpr(CE, LCtx, DstVal);
1392 C.addTransition(StateZeroSize);
1393 return;
1394 }
1395
1396 // Otherwise, go ahead and figure out the last element we'll touch.
1397 // We don't record the non-zero assumption here because we can't
1398 // be sure. We won't warn on a possible zero.
David Blaikie5251abe2013-02-20 05:52:05 +00001399 NonLoc one = svalBuilder.makeIntVal(1, sizeTy).castAs<NonLoc>();
Jordy Rose8912aae2011-06-20 21:55:40 +00001400 maxLastElementIndex = svalBuilder.evalBinOpNN(state, BO_Sub, *lenValNL,
1401 one, sizeTy);
1402 boundWarning = "Size argument is greater than the length of the "
1403 "destination buffer";
1404 }
1405 }
Jordy Rose5e5f1502011-06-20 03:49:16 +00001406
Jordy Rosed5af0e12011-06-15 05:52:56 +00001407 // If we couldn't pin down the copy length, at least bound it.
Jordy Rose8912aae2011-06-20 21:55:40 +00001408 // FIXME: We should actually run this code path for append as well, but
1409 // right now it creates problems with constraints (since we can end up
1410 // trying to pass constraints from symbol to symbol).
1411 if (amountCopied.isUnknown() && !isAppending) {
Jordy Rosed5af0e12011-06-15 05:52:56 +00001412 // Try to get a "hypothetical" string length symbol, which we can later
1413 // set as a real value if that turns out to be the case.
1414 amountCopied = getCStringLength(C, state, lenExpr, srcVal, true);
1415 assert(!amountCopied.isUndef());
1416
David Blaikie5251abe2013-02-20 05:52:05 +00001417 if (llvm::Optional<NonLoc> amountCopiedNL =
1418 amountCopied.getAs<NonLoc>()) {
Jordy Rosed5af0e12011-06-15 05:52:56 +00001419 if (lenValNL) {
1420 // amountCopied <= lenVal
1421 SVal copiedLessThanBound = svalBuilder.evalBinOpNN(state, BO_LE,
1422 *amountCopiedNL,
1423 *lenValNL,
1424 cmpTy);
David Blaikie5251abe2013-02-20 05:52:05 +00001425 state = state->assume(
1426 copiedLessThanBound.castAs<DefinedOrUnknownSVal>(), true);
Jordy Rosed5af0e12011-06-15 05:52:56 +00001427 if (!state)
1428 return;
1429 }
1430
1431 if (strLengthNL) {
1432 // amountCopied <= strlen(source)
1433 SVal copiedLessThanSrc = svalBuilder.evalBinOpNN(state, BO_LE,
1434 *amountCopiedNL,
1435 *strLengthNL,
1436 cmpTy);
David Blaikie5251abe2013-02-20 05:52:05 +00001437 state = state->assume(
1438 copiedLessThanSrc.castAs<DefinedOrUnknownSVal>(), true);
Jordy Rosed5af0e12011-06-15 05:52:56 +00001439 if (!state)
1440 return;
1441 }
1442 }
1443 }
1444
1445 } else {
1446 // The function isn't bounded. The amount copied should match the length
1447 // of the source buffer.
1448 amountCopied = strLength;
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001449 }
1450
Jordy Rosed5af0e12011-06-15 05:52:56 +00001451 assert(state);
1452
1453 // This represents the number of characters copied into the destination
1454 // buffer. (It may not actually be the strlen if the destination buffer
1455 // is not terminated.)
1456 SVal finalStrLength = UnknownVal();
1457
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001458 // If this is an appending function (strcat, strncat...) then set the
1459 // string length to strlen(src) + strlen(dst) since the buffer will
1460 // ultimately contain both.
1461 if (isAppending) {
Jordy Rose1e022412011-06-16 05:51:02 +00001462 // Get the string length of the destination. If the destination is memory
1463 // that can't have a string length, we shouldn't be copying into it anyway.
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001464 SVal dstStrLength = getCStringLength(C, state, Dst, DstVal);
1465 if (dstStrLength.isUndef())
1466 return;
1467
David Blaikie5251abe2013-02-20 05:52:05 +00001468 llvm::Optional<NonLoc> srcStrLengthNL = amountCopied.getAs<NonLoc>();
1469 llvm::Optional<NonLoc> dstStrLengthNL = dstStrLength.getAs<NonLoc>();
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001470
Jordy Rosed5af0e12011-06-15 05:52:56 +00001471 // If we know both string lengths, we might know the final string length.
1472 if (srcStrLengthNL && dstStrLengthNL) {
1473 // Make sure the two lengths together don't overflow a size_t.
1474 state = checkAdditionOverflow(C, state, *srcStrLengthNL, *dstStrLengthNL);
1475 if (!state)
1476 return;
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001477
Jordy Rosed5af0e12011-06-15 05:52:56 +00001478 finalStrLength = svalBuilder.evalBinOpNN(state, BO_Add, *srcStrLengthNL,
1479 *dstStrLengthNL, sizeTy);
1480 }
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001481
Jordy Rosed5af0e12011-06-15 05:52:56 +00001482 // If we couldn't get a single value for the final string length,
1483 // we can at least bound it by the individual lengths.
1484 if (finalStrLength.isUnknown()) {
1485 // Try to get a "hypothetical" string length symbol, which we can later
1486 // set as a real value if that turns out to be the case.
1487 finalStrLength = getCStringLength(C, state, CE, DstVal, true);
1488 assert(!finalStrLength.isUndef());
1489
David Blaikie5251abe2013-02-20 05:52:05 +00001490 if (llvm::Optional<NonLoc> finalStrLengthNL =
1491 finalStrLength.getAs<NonLoc>()) {
Jordy Rosed5af0e12011-06-15 05:52:56 +00001492 if (srcStrLengthNL) {
1493 // finalStrLength >= srcStrLength
1494 SVal sourceInResult = svalBuilder.evalBinOpNN(state, BO_GE,
1495 *finalStrLengthNL,
1496 *srcStrLengthNL,
1497 cmpTy);
David Blaikie5251abe2013-02-20 05:52:05 +00001498 state = state->assume(sourceInResult.castAs<DefinedOrUnknownSVal>(),
Jordy Rosed5af0e12011-06-15 05:52:56 +00001499 true);
1500 if (!state)
1501 return;
1502 }
1503
1504 if (dstStrLengthNL) {
1505 // finalStrLength >= dstStrLength
1506 SVal destInResult = svalBuilder.evalBinOpNN(state, BO_GE,
1507 *finalStrLengthNL,
1508 *dstStrLengthNL,
1509 cmpTy);
David Blaikie5251abe2013-02-20 05:52:05 +00001510 state =
1511 state->assume(destInResult.castAs<DefinedOrUnknownSVal>(), true);
Jordy Rosed5af0e12011-06-15 05:52:56 +00001512 if (!state)
1513 return;
1514 }
1515 }
1516 }
1517
1518 } else {
1519 // Otherwise, this is a copy-over function (strcpy, strncpy, ...), and
1520 // the final string length will match the input string length.
1521 finalStrLength = amountCopied;
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001522 }
1523
Jordy Rosed5af0e12011-06-15 05:52:56 +00001524 // The final result of the function will either be a pointer past the last
1525 // copied element, or a pointer to the start of the destination buffer.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001526 SVal Result = (returnEnd ? UnknownVal() : DstVal);
Jordy Rosee64f3112010-08-16 07:51:42 +00001527
Jordy Rosed5af0e12011-06-15 05:52:56 +00001528 assert(state);
1529
Jordy Rosee64f3112010-08-16 07:51:42 +00001530 // If the destination is a MemRegion, try to check for a buffer overflow and
1531 // record the new string length.
David Blaikie5251abe2013-02-20 05:52:05 +00001532 if (llvm::Optional<loc::MemRegionVal> dstRegVal =
1533 DstVal.getAs<loc::MemRegionVal>()) {
Jordy Rose8912aae2011-06-20 21:55:40 +00001534 QualType ptrTy = Dst->getType();
1535
1536 // If we have an exact value on a bounded copy, use that to check for
1537 // overflows, rather than our estimate about how much is actually copied.
1538 if (boundWarning) {
David Blaikie5251abe2013-02-20 05:52:05 +00001539 if (llvm::Optional<NonLoc> maxLastNL =
1540 maxLastElementIndex.getAs<NonLoc>()) {
Jordy Rose8912aae2011-06-20 21:55:40 +00001541 SVal maxLastElement = svalBuilder.evalBinOpLN(state, BO_Add, *dstRegVal,
1542 *maxLastNL, ptrTy);
1543 state = CheckLocation(C, state, CE->getArg(2), maxLastElement,
1544 boundWarning);
1545 if (!state)
1546 return;
1547 }
1548 }
1549
1550 // Then, if the final length is known...
David Blaikie5251abe2013-02-20 05:52:05 +00001551 if (llvm::Optional<NonLoc> knownStrLength =
1552 finalStrLength.getAs<NonLoc>()) {
Jordy Rosed5af0e12011-06-15 05:52:56 +00001553 SVal lastElement = svalBuilder.evalBinOpLN(state, BO_Add, *dstRegVal,
Jordy Rose8912aae2011-06-20 21:55:40 +00001554 *knownStrLength, ptrTy);
Jordy Rosee64f3112010-08-16 07:51:42 +00001555
Jordy Rose8912aae2011-06-20 21:55:40 +00001556 // ...and we haven't checked the bound, we'll check the actual copy.
1557 if (!boundWarning) {
1558 const char * const warningMsg =
1559 "String copy function overflows destination buffer";
1560 state = CheckLocation(C, state, Dst, lastElement, warningMsg);
1561 if (!state)
1562 return;
1563 }
Jordy Rosee64f3112010-08-16 07:51:42 +00001564
1565 // If this is a stpcpy-style copy, the last element is the return value.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001566 if (returnEnd)
1567 Result = lastElement;
Jordy Rosee64f3112010-08-16 07:51:42 +00001568 }
1569
1570 // Invalidate the destination. This must happen before we set the C string
1571 // length because invalidation will clear the length.
1572 // FIXME: Even if we can't perfectly model the copy, we should see if we
1573 // can use LazyCompoundVals to copy the source values into the destination.
1574 // This would probably remove any existing bindings past the end of the
1575 // string, but that's still an improvement over blank invalidation.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001576 state = InvalidateBuffer(C, state, Dst, *dstRegVal);
Jordy Rosee64f3112010-08-16 07:51:42 +00001577
Jordy Rose5e5f1502011-06-20 03:49:16 +00001578 // Set the C string length of the destination, if we know it.
Jordy Rose8912aae2011-06-20 21:55:40 +00001579 if (isBounded && !isAppending) {
1580 // strncpy is annoying in that it doesn't guarantee to null-terminate
1581 // the result string. If the original string didn't fit entirely inside
1582 // the bound (including the null-terminator), we don't know how long the
1583 // result is.
1584 if (amountCopied != strLength)
1585 finalStrLength = UnknownVal();
1586 }
1587 state = setCStringLength(state, dstRegVal->getRegion(), finalStrLength);
Jordy Rosee64f3112010-08-16 07:51:42 +00001588 }
1589
Jordy Rosed5af0e12011-06-15 05:52:56 +00001590 assert(state);
1591
Jordy Rosee64f3112010-08-16 07:51:42 +00001592 // If this is a stpcpy-style copy, but we were unable to check for a buffer
1593 // overflow, we still need a result. Conjure a return value.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001594 if (returnEnd && Result.isUnknown()) {
Ted Kremenek66c486f2012-08-22 06:26:15 +00001595 Result = svalBuilder.conjureSymbolVal(0, CE, LCtx, C.blockCount());
Jordy Rosee64f3112010-08-16 07:51:42 +00001596 }
1597
1598 // Set the return value.
Ted Kremenek5eca4822012-01-06 22:09:28 +00001599 state = state->BindExpr(CE, LCtx, Result);
Anna Zaks0bd6b112011-10-26 21:06:34 +00001600 C.addTransition(state);
Jordy Rosee64f3112010-08-16 07:51:42 +00001601}
1602
Lenny Maiorani318dd922011-04-12 17:08:43 +00001603void CStringChecker::evalStrcmp(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001604 if (CE->getNumArgs() < 2)
1605 return;
1606
Jordy Roseadc42d42011-06-16 07:13:34 +00001607 //int strcmp(const char *s1, const char *s2);
Lenny Maioranibd1d16a2011-04-28 15:09:11 +00001608 evalStrcmpCommon(C, CE, /* isBounded = */ false, /* ignoreCase = */ false);
Lenny Maiorani357f6ee2011-04-25 22:21:00 +00001609}
Lenny Maiorani318dd922011-04-12 17:08:43 +00001610
Lenny Maiorani357f6ee2011-04-25 22:21:00 +00001611void CStringChecker::evalStrncmp(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001612 if (CE->getNumArgs() < 3)
1613 return;
1614
Jordy Roseadc42d42011-06-16 07:13:34 +00001615 //int strncmp(const char *s1, const char *s2, size_t n);
Lenny Maioranibd1d16a2011-04-28 15:09:11 +00001616 evalStrcmpCommon(C, CE, /* isBounded = */ true, /* ignoreCase = */ false);
1617}
1618
1619void CStringChecker::evalStrcasecmp(CheckerContext &C,
1620 const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001621 if (CE->getNumArgs() < 2)
1622 return;
1623
Jordy Roseadc42d42011-06-16 07:13:34 +00001624 //int strcasecmp(const char *s1, const char *s2);
Lenny Maioranibd1d16a2011-04-28 15:09:11 +00001625 evalStrcmpCommon(C, CE, /* isBounded = */ false, /* ignoreCase = */ true);
Lenny Maiorani357f6ee2011-04-25 22:21:00 +00001626}
1627
Lenny Maiorani454fd2d2011-05-02 19:05:49 +00001628void CStringChecker::evalStrncasecmp(CheckerContext &C,
1629 const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001630 if (CE->getNumArgs() < 3)
1631 return;
1632
Jordy Roseadc42d42011-06-16 07:13:34 +00001633 //int strncasecmp(const char *s1, const char *s2, size_t n);
Lenny Maiorani454fd2d2011-05-02 19:05:49 +00001634 evalStrcmpCommon(C, CE, /* isBounded = */ true, /* ignoreCase = */ true);
1635}
1636
Lenny Maiorani357f6ee2011-04-25 22:21:00 +00001637void CStringChecker::evalStrcmpCommon(CheckerContext &C, const CallExpr *CE,
Lenny Maioranibd1d16a2011-04-28 15:09:11 +00001638 bool isBounded, bool ignoreCase) const {
Jordy Rose9e49d9f2011-06-20 02:06:40 +00001639 CurrentFunctionDescription = "string comparison function";
Ted Kremenek8bef8232012-01-26 21:29:00 +00001640 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001641 const LocationContext *LCtx = C.getLocationContext();
Lenny Maiorani318dd922011-04-12 17:08:43 +00001642
1643 // Check that the first string is non-null
1644 const Expr *s1 = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001645 SVal s1Val = state->getSVal(s1, LCtx);
Lenny Maiorani318dd922011-04-12 17:08:43 +00001646 state = checkNonNull(C, state, s1, s1Val);
1647 if (!state)
1648 return;
1649
1650 // Check that the second string is non-null.
1651 const Expr *s2 = CE->getArg(1);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001652 SVal s2Val = state->getSVal(s2, LCtx);
Lenny Maiorani318dd922011-04-12 17:08:43 +00001653 state = checkNonNull(C, state, s2, s2Val);
1654 if (!state)
1655 return;
1656
1657 // Get the string length of the first string or give up.
1658 SVal s1Length = getCStringLength(C, state, s1, s1Val);
1659 if (s1Length.isUndef())
1660 return;
1661
1662 // Get the string length of the second string or give up.
1663 SVal s2Length = getCStringLength(C, state, s2, s2Val);
1664 if (s2Length.isUndef())
1665 return;
1666
Jordy Roseadc42d42011-06-16 07:13:34 +00001667 // If we know the two buffers are the same, we know the result is 0.
1668 // First, get the two buffers' addresses. Another checker will have already
1669 // made sure they're not undefined.
David Blaikie5251abe2013-02-20 05:52:05 +00001670 DefinedOrUnknownSVal LV = s1Val.castAs<DefinedOrUnknownSVal>();
1671 DefinedOrUnknownSVal RV = s2Val.castAs<DefinedOrUnknownSVal>();
Lenny Maiorani318dd922011-04-12 17:08:43 +00001672
Jordy Roseadc42d42011-06-16 07:13:34 +00001673 // See if they are the same.
Lenny Maiorani318dd922011-04-12 17:08:43 +00001674 SValBuilder &svalBuilder = C.getSValBuilder();
Jordy Roseadc42d42011-06-16 07:13:34 +00001675 DefinedOrUnknownSVal SameBuf = svalBuilder.evalEQ(state, LV, RV);
Ted Kremenek8bef8232012-01-26 21:29:00 +00001676 ProgramStateRef StSameBuf, StNotSameBuf;
Jordy Roseadc42d42011-06-16 07:13:34 +00001677 llvm::tie(StSameBuf, StNotSameBuf) = state->assume(SameBuf);
Lenny Maiorani318dd922011-04-12 17:08:43 +00001678
Jordy Roseadc42d42011-06-16 07:13:34 +00001679 // If the two arguments might be the same buffer, we know the result is 0,
1680 // and we only need to check one size.
1681 if (StSameBuf) {
Ted Kremenek5eca4822012-01-06 22:09:28 +00001682 StSameBuf = StSameBuf->BindExpr(CE, LCtx,
1683 svalBuilder.makeZeroVal(CE->getType()));
Anna Zaks0bd6b112011-10-26 21:06:34 +00001684 C.addTransition(StSameBuf);
Jordy Roseadc42d42011-06-16 07:13:34 +00001685
1686 // If the two arguments are GUARANTEED to be the same, we're done!
1687 if (!StNotSameBuf)
1688 return;
1689 }
1690
1691 assert(StNotSameBuf);
1692 state = StNotSameBuf;
1693
1694 // At this point we can go about comparing the two buffers.
1695 // For now, we only do this if they're both known string literals.
1696
1697 // Attempt to extract string literals from both expressions.
1698 const StringLiteral *s1StrLiteral = getCStringLiteral(C, state, s1, s1Val);
1699 const StringLiteral *s2StrLiteral = getCStringLiteral(C, state, s2, s2Val);
1700 bool canComputeResult = false;
1701
1702 if (s1StrLiteral && s2StrLiteral) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001703 StringRef s1StrRef = s1StrLiteral->getString();
1704 StringRef s2StrRef = s2StrLiteral->getString();
Jordy Roseadc42d42011-06-16 07:13:34 +00001705
1706 if (isBounded) {
1707 // Get the max number of characters to compare.
1708 const Expr *lenExpr = CE->getArg(2);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001709 SVal lenVal = state->getSVal(lenExpr, LCtx);
Jordy Roseadc42d42011-06-16 07:13:34 +00001710
1711 // If the length is known, we can get the right substrings.
1712 if (const llvm::APSInt *len = svalBuilder.getKnownValue(state, lenVal)) {
1713 // Create substrings of each to compare the prefix.
1714 s1StrRef = s1StrRef.substr(0, (size_t)len->getZExtValue());
1715 s2StrRef = s2StrRef.substr(0, (size_t)len->getZExtValue());
1716 canComputeResult = true;
1717 }
1718 } else {
1719 // This is a normal, unbounded strcmp.
1720 canComputeResult = true;
1721 }
1722
1723 if (canComputeResult) {
1724 // Real strcmp stops at null characters.
1725 size_t s1Term = s1StrRef.find('\0');
Chris Lattner5f9e2722011-07-23 10:55:15 +00001726 if (s1Term != StringRef::npos)
Jordy Roseadc42d42011-06-16 07:13:34 +00001727 s1StrRef = s1StrRef.substr(0, s1Term);
1728
1729 size_t s2Term = s2StrRef.find('\0');
Chris Lattner5f9e2722011-07-23 10:55:15 +00001730 if (s2Term != StringRef::npos)
Jordy Roseadc42d42011-06-16 07:13:34 +00001731 s2StrRef = s2StrRef.substr(0, s2Term);
1732
1733 // Use StringRef's comparison methods to compute the actual result.
1734 int result;
1735
1736 if (ignoreCase) {
1737 // Compare string 1 to string 2 the same way strcasecmp() does.
1738 result = s1StrRef.compare_lower(s2StrRef);
1739 } else {
1740 // Compare string 1 to string 2 the same way strcmp() does.
1741 result = s1StrRef.compare(s2StrRef);
1742 }
1743
1744 // Build the SVal of the comparison and bind the return value.
1745 SVal resultVal = svalBuilder.makeIntVal(result, CE->getType());
Ted Kremenek5eca4822012-01-06 22:09:28 +00001746 state = state->BindExpr(CE, LCtx, resultVal);
Jordy Roseadc42d42011-06-16 07:13:34 +00001747 }
1748 }
1749
1750 if (!canComputeResult) {
1751 // Conjure a symbolic value. It's the best we can do.
Ted Kremenek66c486f2012-08-22 06:26:15 +00001752 SVal resultVal = svalBuilder.conjureSymbolVal(0, CE, LCtx, C.blockCount());
Ted Kremenek5eca4822012-01-06 22:09:28 +00001753 state = state->BindExpr(CE, LCtx, resultVal);
Jordy Roseadc42d42011-06-16 07:13:34 +00001754 }
1755
1756 // Record this as a possible path.
Anna Zaks0bd6b112011-10-26 21:06:34 +00001757 C.addTransition(state);
Lenny Maiorani318dd922011-04-12 17:08:43 +00001758}
1759
Jordy Rosed325ffb2010-07-08 23:57:29 +00001760//===----------------------------------------------------------------------===//
Jordy Rosea5261542010-08-14 21:02:52 +00001761// The driver method, and other Checker callbacks.
Jordy Rosed325ffb2010-07-08 23:57:29 +00001762//===----------------------------------------------------------------------===//
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001763
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001764bool CStringChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
Anna Zaks998e2752012-02-17 22:35:26 +00001765 const FunctionDecl *FDecl = C.getCalleeDecl(CE);
1766
1767 if (!FDecl)
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001768 return false;
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001769
Anna Zaks998e2752012-02-17 22:35:26 +00001770 FnCheck evalFunction = 0;
1771 if (C.isCLibraryFunction(FDecl, "memcpy"))
1772 evalFunction = &CStringChecker::evalMemcpy;
1773 else if (C.isCLibraryFunction(FDecl, "mempcpy"))
1774 evalFunction = &CStringChecker::evalMempcpy;
1775 else if (C.isCLibraryFunction(FDecl, "memcmp"))
1776 evalFunction = &CStringChecker::evalMemcmp;
1777 else if (C.isCLibraryFunction(FDecl, "memmove"))
1778 evalFunction = &CStringChecker::evalMemmove;
1779 else if (C.isCLibraryFunction(FDecl, "strcpy"))
1780 evalFunction = &CStringChecker::evalStrcpy;
1781 else if (C.isCLibraryFunction(FDecl, "strncpy"))
1782 evalFunction = &CStringChecker::evalStrncpy;
1783 else if (C.isCLibraryFunction(FDecl, "stpcpy"))
1784 evalFunction = &CStringChecker::evalStpcpy;
1785 else if (C.isCLibraryFunction(FDecl, "strcat"))
1786 evalFunction = &CStringChecker::evalStrcat;
1787 else if (C.isCLibraryFunction(FDecl, "strncat"))
1788 evalFunction = &CStringChecker::evalStrncat;
1789 else if (C.isCLibraryFunction(FDecl, "strlen"))
1790 evalFunction = &CStringChecker::evalstrLength;
1791 else if (C.isCLibraryFunction(FDecl, "strnlen"))
1792 evalFunction = &CStringChecker::evalstrnLength;
1793 else if (C.isCLibraryFunction(FDecl, "strcmp"))
1794 evalFunction = &CStringChecker::evalStrcmp;
1795 else if (C.isCLibraryFunction(FDecl, "strncmp"))
1796 evalFunction = &CStringChecker::evalStrncmp;
1797 else if (C.isCLibraryFunction(FDecl, "strcasecmp"))
1798 evalFunction = &CStringChecker::evalStrcasecmp;
1799 else if (C.isCLibraryFunction(FDecl, "strncasecmp"))
1800 evalFunction = &CStringChecker::evalStrncasecmp;
1801 else if (C.isCLibraryFunction(FDecl, "bcopy"))
1802 evalFunction = &CStringChecker::evalBcopy;
1803 else if (C.isCLibraryFunction(FDecl, "bcmp"))
1804 evalFunction = &CStringChecker::evalMemcmp;
1805
Jordy Rosed325ffb2010-07-08 23:57:29 +00001806 // If the callee isn't a string function, let another checker handle it.
Ted Kremenek9c149532010-12-01 21:57:22 +00001807 if (!evalFunction)
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001808 return false;
1809
Jordy Rose9e49d9f2011-06-20 02:06:40 +00001810 // Make sure each function sets its own description.
1811 // (But don't bother in a release build.)
1812 assert(!(CurrentFunctionDescription = NULL));
1813
Jordy Rosed325ffb2010-07-08 23:57:29 +00001814 // Check and evaluate the call.
Ted Kremenek9c149532010-12-01 21:57:22 +00001815 (this->*evalFunction)(C, CE);
Anna Zaks57300762012-02-07 00:56:14 +00001816
1817 // If the evaluate call resulted in no change, chain to the next eval call
1818 // handler.
1819 // Note, the custom CString evaluation calls assume that basic safety
1820 // properties are held. However, if the user chooses to turn off some of these
1821 // checks, we ignore the issues and leave the call evaluation to a generic
1822 // handler.
1823 if (!C.isDifferent())
1824 return false;
1825
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001826 return true;
1827}
Jordy Rosea5261542010-08-14 21:02:52 +00001828
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001829void CStringChecker::checkPreStmt(const DeclStmt *DS, CheckerContext &C) const {
Jordy Rosea5261542010-08-14 21:02:52 +00001830 // Record string length for char a[] = "abc";
Ted Kremenek8bef8232012-01-26 21:29:00 +00001831 ProgramStateRef state = C.getState();
Jordy Rosea5261542010-08-14 21:02:52 +00001832
1833 for (DeclStmt::const_decl_iterator I = DS->decl_begin(), E = DS->decl_end();
1834 I != E; ++I) {
1835 const VarDecl *D = dyn_cast<VarDecl>(*I);
1836 if (!D)
1837 continue;
1838
1839 // FIXME: Handle array fields of structs.
1840 if (!D->getType()->isArrayType())
1841 continue;
1842
1843 const Expr *Init = D->getInit();
1844 if (!Init)
1845 continue;
1846 if (!isa<StringLiteral>(Init))
1847 continue;
1848
Anna Zaks39ac1872011-10-26 21:06:44 +00001849 Loc VarLoc = state->getLValue(D, C.getLocationContext());
Jordy Rosea5261542010-08-14 21:02:52 +00001850 const MemRegion *MR = VarLoc.getAsRegion();
1851 if (!MR)
1852 continue;
1853
Ted Kremenek5eca4822012-01-06 22:09:28 +00001854 SVal StrVal = state->getSVal(Init, C.getLocationContext());
Jordy Rosea5261542010-08-14 21:02:52 +00001855 assert(StrVal.isValid() && "Initializer string is unknown or undefined");
David Blaikie5251abe2013-02-20 05:52:05 +00001856 DefinedOrUnknownSVal strLength =
1857 getCStringLength(C, state, Init, StrVal).castAs<DefinedOrUnknownSVal>();
Jordy Rosea5261542010-08-14 21:02:52 +00001858
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001859 state = state->set<CStringLength>(MR, strLength);
Jordy Rosea5261542010-08-14 21:02:52 +00001860 }
1861
Anna Zaks0bd6b112011-10-26 21:06:34 +00001862 C.addTransition(state);
Jordy Rosea5261542010-08-14 21:02:52 +00001863}
1864
Ted Kremenek8bef8232012-01-26 21:29:00 +00001865bool CStringChecker::wantsRegionChangeUpdate(ProgramStateRef state) const {
Jordan Rose166d5022012-11-02 01:54:06 +00001866 CStringLengthTy Entries = state->get<CStringLength>();
Jordy Rosea5261542010-08-14 21:02:52 +00001867 return !Entries.isEmpty();
1868}
1869
Ted Kremenek8bef8232012-01-26 21:29:00 +00001870ProgramStateRef
1871CStringChecker::checkRegionChanges(ProgramStateRef state,
Anna Zaksbf53dfa2012-12-20 00:38:25 +00001872 const InvalidatedSymbols *,
Jordy Rose537716a2011-08-27 22:51:26 +00001873 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00001874 ArrayRef<const MemRegion *> Regions,
Jordan Rose740d4902012-07-02 19:27:35 +00001875 const CallEvent *Call) const {
Jordan Rose166d5022012-11-02 01:54:06 +00001876 CStringLengthTy Entries = state->get<CStringLength>();
Jordy Rosea5261542010-08-14 21:02:52 +00001877 if (Entries.isEmpty())
1878 return state;
1879
1880 llvm::SmallPtrSet<const MemRegion *, 8> Invalidated;
1881 llvm::SmallPtrSet<const MemRegion *, 32> SuperRegions;
1882
1883 // First build sets for the changed regions and their super-regions.
Jordy Rose537716a2011-08-27 22:51:26 +00001884 for (ArrayRef<const MemRegion *>::iterator
1885 I = Regions.begin(), E = Regions.end(); I != E; ++I) {
1886 const MemRegion *MR = *I;
Jordy Rosea5261542010-08-14 21:02:52 +00001887 Invalidated.insert(MR);
1888
1889 SuperRegions.insert(MR);
1890 while (const SubRegion *SR = dyn_cast<SubRegion>(MR)) {
1891 MR = SR->getSuperRegion();
1892 SuperRegions.insert(MR);
1893 }
1894 }
1895
Jordan Rose166d5022012-11-02 01:54:06 +00001896 CStringLengthTy::Factory &F = state->get_context<CStringLength>();
Jordy Rosea5261542010-08-14 21:02:52 +00001897
1898 // Then loop over the entries in the current state.
Jordan Rose166d5022012-11-02 01:54:06 +00001899 for (CStringLengthTy::iterator I = Entries.begin(),
Jordy Rosea5261542010-08-14 21:02:52 +00001900 E = Entries.end(); I != E; ++I) {
1901 const MemRegion *MR = I.getKey();
1902
1903 // Is this entry for a super-region of a changed region?
1904 if (SuperRegions.count(MR)) {
Ted Kremenek3baf6722010-11-24 00:54:37 +00001905 Entries = F.remove(Entries, MR);
Jordy Rosea5261542010-08-14 21:02:52 +00001906 continue;
1907 }
1908
1909 // Is this entry for a sub-region of a changed region?
1910 const MemRegion *Super = MR;
1911 while (const SubRegion *SR = dyn_cast<SubRegion>(Super)) {
1912 Super = SR->getSuperRegion();
1913 if (Invalidated.count(Super)) {
Ted Kremenek3baf6722010-11-24 00:54:37 +00001914 Entries = F.remove(Entries, MR);
Jordy Rosea5261542010-08-14 21:02:52 +00001915 break;
1916 }
1917 }
1918 }
1919
1920 return state->set<CStringLength>(Entries);
1921}
1922
Ted Kremenek8bef8232012-01-26 21:29:00 +00001923void CStringChecker::checkLiveSymbols(ProgramStateRef state,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001924 SymbolReaper &SR) const {
Jordy Rosea5261542010-08-14 21:02:52 +00001925 // Mark all symbols in our string length map as valid.
Jordan Rose166d5022012-11-02 01:54:06 +00001926 CStringLengthTy Entries = state->get<CStringLength>();
Jordy Rosea5261542010-08-14 21:02:52 +00001927
Jordan Rose166d5022012-11-02 01:54:06 +00001928 for (CStringLengthTy::iterator I = Entries.begin(), E = Entries.end();
Jordy Rosea5261542010-08-14 21:02:52 +00001929 I != E; ++I) {
1930 SVal Len = I.getData();
Jordy Rosed5af0e12011-06-15 05:52:56 +00001931
Anna Zaks1d1d5152011-12-06 23:12:33 +00001932 for (SymExpr::symbol_iterator si = Len.symbol_begin(),
1933 se = Len.symbol_end(); si != se; ++si)
Jordy Rosed5af0e12011-06-15 05:52:56 +00001934 SR.markInUse(*si);
Jordy Rosea5261542010-08-14 21:02:52 +00001935 }
1936}
1937
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001938void CStringChecker::checkDeadSymbols(SymbolReaper &SR,
1939 CheckerContext &C) const {
Jordy Rosea5261542010-08-14 21:02:52 +00001940 if (!SR.hasDeadSymbols())
1941 return;
1942
Ted Kremenek8bef8232012-01-26 21:29:00 +00001943 ProgramStateRef state = C.getState();
Jordan Rose166d5022012-11-02 01:54:06 +00001944 CStringLengthTy Entries = state->get<CStringLength>();
Jordy Rosea5261542010-08-14 21:02:52 +00001945 if (Entries.isEmpty())
1946 return;
1947
Jordan Rose166d5022012-11-02 01:54:06 +00001948 CStringLengthTy::Factory &F = state->get_context<CStringLength>();
1949 for (CStringLengthTy::iterator I = Entries.begin(), E = Entries.end();
Jordy Rosea5261542010-08-14 21:02:52 +00001950 I != E; ++I) {
1951 SVal Len = I.getData();
1952 if (SymbolRef Sym = Len.getAsSymbol()) {
1953 if (SR.isDead(Sym))
Ted Kremenek3baf6722010-11-24 00:54:37 +00001954 Entries = F.remove(Entries, I.getKey());
Jordy Rosea5261542010-08-14 21:02:52 +00001955 }
1956 }
1957
1958 state = state->set<CStringLength>(Entries);
Anna Zaks0bd6b112011-10-26 21:06:34 +00001959 C.addTransition(state);
Jordy Rosea5261542010-08-14 21:02:52 +00001960}
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001961
Anna Zaks57300762012-02-07 00:56:14 +00001962#define REGISTER_CHECKER(name) \
1963void ento::register##name(CheckerManager &mgr) {\
1964 static CStringChecker *TheChecker = 0; \
1965 if (TheChecker == 0) \
1966 TheChecker = mgr.registerChecker<CStringChecker>(); \
1967 TheChecker->Filter.Check##name = true; \
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001968}
Anna Zaks57300762012-02-07 00:56:14 +00001969
1970REGISTER_CHECKER(CStringNullArg)
1971REGISTER_CHECKER(CStringOutOfBounds)
1972REGISTER_CHECKER(CStringBufferOverlap)
1973REGISTER_CHECKER(CStringNotNullTerm)
Anna Zaksf0dfc9c2012-02-17 22:35:31 +00001974
1975void ento::registerCStringCheckerBasic(CheckerManager &Mgr) {
1976 registerCStringNullArg(Mgr);
1977}