blob: 0a94747d043ff899d521e6523e4cbe381523db8b [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) {
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000204 DefinedSVal *val = dyn_cast<DefinedSVal>(&V);
205 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));
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000281 DefinedOrUnknownSVal Size = cast<DefinedOrUnknownSVal>(Extent);
282
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);
Jordy Rosed325ffb2010-07-08 23:57:29 +0000362 NonLoc *Length = dyn_cast<NonLoc>(&LengthVal);
363 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.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000367 NonLoc One = cast<NonLoc>(svalBuilder.makeIntVal(1, sizeTy));
368 NonLoc LastOffset = cast<NonLoc>(svalBuilder.evalBinOpNN(state, BO_Sub,
369 *Length, One, sizeTy));
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());
Jordy Roseb6a40262010-08-05 23:11:30 +0000373 if (Loc *BufLoc = dyn_cast<Loc>(&BufStart)) {
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());
Jordy Roseb6a40262010-08-05 23:11:30 +0000393 if (Loc *BufLoc = dyn_cast<Loc>(&BufStart)) {
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
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000429 Loc *firstLoc = dyn_cast<Loc>(&firstVal);
430 if (!firstLoc)
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000431 return state;
432
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000433 Loc *secondLoc = dyn_cast<Loc>(&secondVal);
434 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);
456 DefinedOrUnknownSVal *reverseTest = dyn_cast<DefinedOrUnknownSVal>(&reverse);
457 if (!reverseTest)
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000458 return state;
459
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000460 llvm::tie(stateTrue, stateFalse) = state->assume(*reverseTest);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000461 if (stateTrue) {
462 if (stateFalse) {
463 // If we don't know which one comes first, we can't perform this test.
464 return state;
465 } else {
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000466 // Switch the values so that firstVal is before secondVal.
467 Loc *tmpLoc = firstLoc;
468 firstLoc = secondLoc;
469 secondLoc = tmpLoc;
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000470
471 // Switch the Exprs as well, so that they still correspond.
472 const Expr *tmpExpr = First;
473 First = Second;
474 Second = tmpExpr;
475 }
476 }
477
478 // Get the length, and make sure it too is known.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000479 SVal LengthVal = state->getSVal(Size, LCtx);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000480 NonLoc *Length = dyn_cast<NonLoc>(&LengthVal);
481 if (!Length)
482 return state;
483
484 // Convert the first buffer's start address to char*.
485 // Bail out if the cast fails.
Jordy Roseee2fde12011-06-16 05:56:50 +0000486 ASTContext &Ctx = svalBuilder.getContext();
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000487 QualType CharPtrTy = Ctx.getPointerType(Ctx.CharTy);
Jordy Rose1e022412011-06-16 05:51:02 +0000488 SVal FirstStart = svalBuilder.evalCast(*firstLoc, CharPtrTy,
489 First->getType());
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000490 Loc *FirstStartLoc = dyn_cast<Loc>(&FirstStart);
491 if (!FirstStartLoc)
492 return state;
493
494 // Compute the end of the first buffer. Bail out if THAT fails.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000495 SVal FirstEnd = svalBuilder.evalBinOpLN(state, BO_Add,
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000496 *FirstStartLoc, *Length, CharPtrTy);
497 Loc *FirstEndLoc = dyn_cast<Loc>(&FirstEnd);
498 if (!FirstEndLoc)
499 return state;
500
501 // Is the end of the first buffer past the start of the second buffer?
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000502 SVal Overlap = svalBuilder.evalBinOpLL(state, BO_GT,
503 *FirstEndLoc, *secondLoc, cmpTy);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000504 DefinedOrUnknownSVal *OverlapTest = dyn_cast<DefinedOrUnknownSVal>(&Overlap);
505 if (!OverlapTest)
506 return state;
507
Ted Kremenek28f47b92010-12-01 22:16:56 +0000508 llvm::tie(stateTrue, stateFalse) = state->assume(*OverlapTest);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000509
510 if (stateTrue && !stateFalse) {
511 // Overlap!
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000512 emitOverlapBug(C, stateTrue, First, Second);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000513 return NULL;
514 }
515
Ted Kremenek28f47b92010-12-01 22:16:56 +0000516 // assume the two expressions don't overlap.
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000517 assert(stateFalse);
518 return stateFalse;
519}
520
Ted Kremenek8bef8232012-01-26 21:29:00 +0000521void CStringChecker::emitOverlapBug(CheckerContext &C, ProgramStateRef state,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000522 const Stmt *First, const Stmt *Second) const {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000523 ExplodedNode *N = C.generateSink(state);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000524 if (!N)
525 return;
526
527 if (!BT_Overlap)
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000528 BT_Overlap.reset(new BugType("Unix API", "Improper arguments"));
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000529
530 // Generate a report for this bug.
Anna Zakse172e8b2011-08-17 23:00:25 +0000531 BugReport *report =
532 new BugReport(*BT_Overlap,
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000533 "Arguments must not be overlapping buffers", N);
534 report->addRange(First->getSourceRange());
535 report->addRange(Second->getSourceRange());
536
Jordan Rose785950e2012-11-02 01:53:40 +0000537 C.emitReport(report);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000538}
539
Ted Kremenek8bef8232012-01-26 21:29:00 +0000540ProgramStateRef CStringChecker::checkAdditionOverflow(CheckerContext &C,
541 ProgramStateRef state,
Jordy Rosed5af0e12011-06-15 05:52:56 +0000542 NonLoc left,
543 NonLoc right) const {
Anna Zaks57300762012-02-07 00:56:14 +0000544 // If out-of-bounds checking is turned off, skip the rest.
545 if (!Filter.CheckCStringOutOfBounds)
546 return state;
547
Jordy Rosed5af0e12011-06-15 05:52:56 +0000548 // If a previous check has failed, propagate the failure.
549 if (!state)
550 return NULL;
551
552 SValBuilder &svalBuilder = C.getSValBuilder();
553 BasicValueFactory &BVF = svalBuilder.getBasicValueFactory();
554
555 QualType sizeTy = svalBuilder.getContext().getSizeType();
556 const llvm::APSInt &maxValInt = BVF.getMaxValue(sizeTy);
557 NonLoc maxVal = svalBuilder.makeIntVal(maxValInt);
558
Anna Zakse3d250e2011-12-11 18:43:40 +0000559 SVal maxMinusRight;
560 if (isa<nonloc::ConcreteInt>(right)) {
561 maxMinusRight = svalBuilder.evalBinOpNN(state, BO_Sub, maxVal, right,
562 sizeTy);
563 } else {
Jordy Rosed5af0e12011-06-15 05:52:56 +0000564 // Try switching the operands. (The order of these two assignments is
565 // important!)
566 maxMinusRight = svalBuilder.evalBinOpNN(state, BO_Sub, maxVal, left,
567 sizeTy);
568 left = right;
569 }
570
571 if (NonLoc *maxMinusRightNL = dyn_cast<NonLoc>(&maxMinusRight)) {
572 QualType cmpTy = svalBuilder.getConditionType();
573 // If left > max - right, we have an overflow.
574 SVal willOverflow = svalBuilder.evalBinOpNN(state, BO_GT, left,
575 *maxMinusRightNL, cmpTy);
576
Ted Kremenek8bef8232012-01-26 21:29:00 +0000577 ProgramStateRef stateOverflow, stateOkay;
Jordy Rosed5af0e12011-06-15 05:52:56 +0000578 llvm::tie(stateOverflow, stateOkay) =
579 state->assume(cast<DefinedOrUnknownSVal>(willOverflow));
580
581 if (stateOverflow && !stateOkay) {
582 // We have an overflow. Emit a bug report.
583 ExplodedNode *N = C.generateSink(stateOverflow);
584 if (!N)
585 return NULL;
586
587 if (!BT_AdditionOverflow)
588 BT_AdditionOverflow.reset(new BuiltinBug("API",
589 "Sum of expressions causes overflow"));
590
Jordy Rosed5af0e12011-06-15 05:52:56 +0000591 // This isn't a great error message, but this should never occur in real
592 // code anyway -- you'd have to create a buffer longer than a size_t can
593 // represent, which is sort of a contradiction.
Jordy Rose8cc24912011-06-20 03:51:53 +0000594 const char *warning =
595 "This expression will create a string whose length is too big to "
596 "be represented as a size_t";
Jordy Rosed5af0e12011-06-15 05:52:56 +0000597
598 // Generate a report for this bug.
Jordy Rose8cc24912011-06-20 03:51:53 +0000599 BugReport *report = new BugReport(*BT_AdditionOverflow, warning, N);
Jordan Rose785950e2012-11-02 01:53:40 +0000600 C.emitReport(report);
Jordy Rosed5af0e12011-06-15 05:52:56 +0000601
602 return NULL;
603 }
604
605 // From now on, assume an overflow didn't occur.
606 assert(stateOkay);
607 state = stateOkay;
608 }
609
610 return state;
611}
612
Ted Kremenek8bef8232012-01-26 21:29:00 +0000613ProgramStateRef CStringChecker::setCStringLength(ProgramStateRef state,
Jordy Rosee64f3112010-08-16 07:51:42 +0000614 const MemRegion *MR,
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000615 SVal strLength) {
616 assert(!strLength.isUndef() && "Attempt to set an undefined string length");
Jordy Rosee64f3112010-08-16 07:51:42 +0000617
618 MR = MR->StripCasts();
619
620 switch (MR->getKind()) {
621 case MemRegion::StringRegionKind:
622 // FIXME: This can happen if we strcpy() into a string region. This is
623 // undefined [C99 6.4.5p6], but we should still warn about it.
624 return state;
625
626 case MemRegion::SymbolicRegionKind:
627 case MemRegion::AllocaRegionKind:
628 case MemRegion::VarRegionKind:
629 case MemRegion::FieldRegionKind:
630 case MemRegion::ObjCIvarRegionKind:
Jordy Rose210c05b2011-06-15 05:14:03 +0000631 // These are the types we can currently track string lengths for.
632 break;
Jordy Rosee64f3112010-08-16 07:51:42 +0000633
634 case MemRegion::ElementRegionKind:
635 // FIXME: Handle element regions by upper-bounding the parent region's
636 // string length.
637 return state;
638
639 default:
640 // Other regions (mostly non-data) can't have a reliable C string length.
641 // For now, just ignore the change.
642 // FIXME: These are rare but not impossible. We should output some kind of
643 // warning for things like strcpy((char[]){'a', 0}, "b");
644 return state;
645 }
Jordy Rose210c05b2011-06-15 05:14:03 +0000646
647 if (strLength.isUnknown())
648 return state->remove<CStringLength>(MR);
649
650 return state->set<CStringLength>(MR, strLength);
Jordy Rosee64f3112010-08-16 07:51:42 +0000651}
652
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000653SVal CStringChecker::getCStringLengthForRegion(CheckerContext &C,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000654 ProgramStateRef &state,
Jordy Rosea5261542010-08-14 21:02:52 +0000655 const Expr *Ex,
Jordy Rosed5af0e12011-06-15 05:52:56 +0000656 const MemRegion *MR,
657 bool hypothetical) {
658 if (!hypothetical) {
659 // If there's a recorded length, go ahead and return it.
660 const SVal *Recorded = state->get<CStringLength>(MR);
661 if (Recorded)
662 return *Recorded;
663 }
Jordy Rosea5261542010-08-14 21:02:52 +0000664
665 // Otherwise, get a new symbol and update the state.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000666 SValBuilder &svalBuilder = C.getSValBuilder();
667 QualType sizeTy = svalBuilder.getContext().getSizeType();
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000668 SVal strLength = svalBuilder.getMetadataSymbolVal(CStringChecker::getTag(),
Ted Kremenek66c486f2012-08-22 06:26:15 +0000669 MR, Ex, sizeTy,
670 C.blockCount());
Jordy Rosed5af0e12011-06-15 05:52:56 +0000671
672 if (!hypothetical)
673 state = state->set<CStringLength>(MR, strLength);
674
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000675 return strLength;
Jordy Rosea5261542010-08-14 21:02:52 +0000676}
677
Ted Kremenek8bef8232012-01-26 21:29:00 +0000678SVal CStringChecker::getCStringLength(CheckerContext &C, ProgramStateRef &state,
Jordy Rosed5af0e12011-06-15 05:52:56 +0000679 const Expr *Ex, SVal Buf,
680 bool hypothetical) const {
Jordy Rose19c5dd12010-07-27 01:37:31 +0000681 const MemRegion *MR = Buf.getAsRegion();
682 if (!MR) {
683 // If we can't get a region, see if it's something we /know/ isn't a
684 // C string. In the context of locations, the only time we can issue such
685 // a warning is for labels.
686 if (loc::GotoLabel *Label = dyn_cast<loc::GotoLabel>(&Buf)) {
Anna Zaks57300762012-02-07 00:56:14 +0000687 if (!Filter.CheckCStringNotNullTerm)
688 return UndefinedVal();
689
Anna Zaks0bd6b112011-10-26 21:06:34 +0000690 if (ExplodedNode *N = C.addTransition(state)) {
Jordy Rose19c5dd12010-07-27 01:37:31 +0000691 if (!BT_NotCString)
Anna Zaks57300762012-02-07 00:56:14 +0000692 BT_NotCString.reset(new BuiltinBug("Unix API",
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000693 "Argument is not a null-terminated string."));
Jordy Rose19c5dd12010-07-27 01:37:31 +0000694
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000695 SmallString<120> buf;
Jordy Rose19c5dd12010-07-27 01:37:31 +0000696 llvm::raw_svector_ostream os(buf);
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000697 assert(CurrentFunctionDescription);
698 os << "Argument to " << CurrentFunctionDescription
699 << " is the address of the label '" << Label->getLabel()->getName()
Jordy Rose19c5dd12010-07-27 01:37:31 +0000700 << "', which is not a null-terminated string";
701
702 // Generate a report for this bug.
Anna Zakse172e8b2011-08-17 23:00:25 +0000703 BugReport *report = new BugReport(*BT_NotCString,
Jordy Rose19c5dd12010-07-27 01:37:31 +0000704 os.str(), N);
705
706 report->addRange(Ex->getSourceRange());
Jordan Rose785950e2012-11-02 01:53:40 +0000707 C.emitReport(report);
Jordy Rose19c5dd12010-07-27 01:37:31 +0000708 }
Jordy Rose19c5dd12010-07-27 01:37:31 +0000709 return UndefinedVal();
Anna Zaks57300762012-02-07 00:56:14 +0000710
Jordy Rose19c5dd12010-07-27 01:37:31 +0000711 }
712
Jordy Rosea5261542010-08-14 21:02:52 +0000713 // If it's not a region and not a label, give up.
714 return UnknownVal();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000715 }
716
Jordy Rosea5261542010-08-14 21:02:52 +0000717 // If we have a region, strip casts from it and see if we can figure out
718 // its length. For anything we can't figure out, just return UnknownVal.
719 MR = MR->StripCasts();
720
721 switch (MR->getKind()) {
722 case MemRegion::StringRegionKind: {
723 // Modifying the contents of string regions is undefined [C99 6.4.5p6],
724 // so we can assume that the byte length is the correct C string length.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000725 SValBuilder &svalBuilder = C.getSValBuilder();
726 QualType sizeTy = svalBuilder.getContext().getSizeType();
727 const StringLiteral *strLit = cast<StringRegion>(MR)->getStringLiteral();
728 return svalBuilder.makeIntVal(strLit->getByteLength(), sizeTy);
Jordy Rosea5261542010-08-14 21:02:52 +0000729 }
730 case MemRegion::SymbolicRegionKind:
731 case MemRegion::AllocaRegionKind:
732 case MemRegion::VarRegionKind:
733 case MemRegion::FieldRegionKind:
734 case MemRegion::ObjCIvarRegionKind:
Jordy Rosed5af0e12011-06-15 05:52:56 +0000735 return getCStringLengthForRegion(C, state, Ex, MR, hypothetical);
Jordy Rosea5261542010-08-14 21:02:52 +0000736 case MemRegion::CompoundLiteralRegionKind:
737 // FIXME: Can we track this? Is it necessary?
738 return UnknownVal();
739 case MemRegion::ElementRegionKind:
740 // FIXME: How can we handle this? It's not good enough to subtract the
741 // offset from the base string length; consider "123\x00567" and &a[5].
742 return UnknownVal();
743 default:
744 // Other regions (mostly non-data) can't have a reliable C string length.
745 // In this case, an error is emitted and UndefinedVal is returned.
746 // The caller should always be prepared to handle this case.
Anna Zaks57300762012-02-07 00:56:14 +0000747 if (!Filter.CheckCStringNotNullTerm)
748 return UndefinedVal();
749
Anna Zaks0bd6b112011-10-26 21:06:34 +0000750 if (ExplodedNode *N = C.addTransition(state)) {
Jordy Rosea5261542010-08-14 21:02:52 +0000751 if (!BT_NotCString)
Anna Zaks57300762012-02-07 00:56:14 +0000752 BT_NotCString.reset(new BuiltinBug("Unix API",
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000753 "Argument is not a null-terminated string."));
Jordy Rosea5261542010-08-14 21:02:52 +0000754
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000755 SmallString<120> buf;
Jordy Rosea5261542010-08-14 21:02:52 +0000756 llvm::raw_svector_ostream os(buf);
757
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000758 assert(CurrentFunctionDescription);
759 os << "Argument to " << CurrentFunctionDescription << " is ";
Jordy Rosea5261542010-08-14 21:02:52 +0000760
761 if (SummarizeRegion(os, C.getASTContext(), MR))
762 os << ", which is not a null-terminated string";
763 else
764 os << "not a null-terminated string";
765
766 // Generate a report for this bug.
Anna Zakse172e8b2011-08-17 23:00:25 +0000767 BugReport *report = new BugReport(*BT_NotCString,
Jordy Rosea5261542010-08-14 21:02:52 +0000768 os.str(), N);
769
770 report->addRange(Ex->getSourceRange());
Jordan Rose785950e2012-11-02 01:53:40 +0000771 C.emitReport(report);
Jordy Rosea5261542010-08-14 21:02:52 +0000772 }
773
774 return UndefinedVal();
775 }
Jordy Rose19c5dd12010-07-27 01:37:31 +0000776}
777
Lenny Maiorani318dd922011-04-12 17:08:43 +0000778const StringLiteral *CStringChecker::getCStringLiteral(CheckerContext &C,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000779 ProgramStateRef &state, const Expr *expr, SVal val) const {
Lenny Maiorani318dd922011-04-12 17:08:43 +0000780
781 // Get the memory region pointed to by the val.
782 const MemRegion *bufRegion = val.getAsRegion();
783 if (!bufRegion)
784 return NULL;
785
786 // Strip casts off the memory region.
787 bufRegion = bufRegion->StripCasts();
788
789 // Cast the memory region to a string region.
790 const StringRegion *strRegion= dyn_cast<StringRegion>(bufRegion);
791 if (!strRegion)
792 return NULL;
793
794 // Return the actual string in the string region.
795 return strRegion->getStringLiteral();
796}
797
Ted Kremenek8bef8232012-01-26 21:29:00 +0000798ProgramStateRef CStringChecker::InvalidateBuffer(CheckerContext &C,
799 ProgramStateRef state,
Jordy Rosee64f3112010-08-16 07:51:42 +0000800 const Expr *E, SVal V) {
801 Loc *L = dyn_cast<Loc>(&V);
802 if (!L)
803 return state;
804
805 // FIXME: This is a simplified version of what's in CFRefCount.cpp -- it makes
806 // some assumptions about the value that CFRefCount can't. Even so, it should
807 // probably be refactored.
808 if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(L)) {
809 const MemRegion *R = MR->getRegion()->StripCasts();
810
811 // Are we dealing with an ElementRegion? If so, we should be invalidating
812 // the super-region.
813 if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
814 R = ER->getSuperRegion();
815 // FIXME: What about layers of ElementRegions?
816 }
817
818 // Invalidate this region.
Ted Kremenek3133f792012-02-17 23:13:45 +0000819 const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
Anna Zaksbf53dfa2012-12-20 00:38:25 +0000820 return state->invalidateRegions(R, E, C.blockCount(), LCtx,
Anna Zaks64eb0702013-01-16 01:35:54 +0000821 /*CausesPointerEscape*/ false);
Jordy Rosee64f3112010-08-16 07:51:42 +0000822 }
823
824 // If we have a non-region value by chance, just remove the binding.
825 // FIXME: is this necessary or correct? This handles the non-Region
826 // cases. Is it ever valid to store to these?
Ted Kremenek56a46b52012-08-22 06:37:46 +0000827 return state->killBinding(*L);
Jordy Rosee64f3112010-08-16 07:51:42 +0000828}
829
Ted Kremenek9c378f72011-08-12 23:37:29 +0000830bool CStringChecker::SummarizeRegion(raw_ostream &os, ASTContext &Ctx,
Jordy Rose19c5dd12010-07-27 01:37:31 +0000831 const MemRegion *MR) {
Ted Kremenek96979342011-08-12 20:02:48 +0000832 const TypedValueRegion *TVR = dyn_cast<TypedValueRegion>(MR);
Jordy Rose19c5dd12010-07-27 01:37:31 +0000833
Jordy Rose096aef92011-08-12 21:41:07 +0000834 switch (MR->getKind()) {
Jordy Rose19c5dd12010-07-27 01:37:31 +0000835 case MemRegion::FunctionTextRegionKind: {
Anna Zaks5fc1d0c2012-09-17 19:13:56 +0000836 const NamedDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000837 if (FD)
Benjamin Kramerb8989f22011-10-14 18:45:37 +0000838 os << "the address of the function '" << *FD << '\'';
Jordy Rose19c5dd12010-07-27 01:37:31 +0000839 else
840 os << "the address of a function";
841 return true;
842 }
843 case MemRegion::BlockTextRegionKind:
844 os << "block text";
845 return true;
846 case MemRegion::BlockDataRegionKind:
847 os << "a block";
848 return true;
849 case MemRegion::CXXThisRegionKind:
Zhongxing Xu02fe28c2010-11-26 08:52:48 +0000850 case MemRegion::CXXTempObjectRegionKind:
Ted Kremenek96979342011-08-12 20:02:48 +0000851 os << "a C++ temp object of type " << TVR->getValueType().getAsString();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000852 return true;
853 case MemRegion::VarRegionKind:
Ted Kremenek96979342011-08-12 20:02:48 +0000854 os << "a variable of type" << TVR->getValueType().getAsString();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000855 return true;
856 case MemRegion::FieldRegionKind:
Ted Kremenek96979342011-08-12 20:02:48 +0000857 os << "a field of type " << TVR->getValueType().getAsString();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000858 return true;
859 case MemRegion::ObjCIvarRegionKind:
Ted Kremenek96979342011-08-12 20:02:48 +0000860 os << "an instance variable of type " << TVR->getValueType().getAsString();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000861 return true;
862 default:
863 return false;
864 }
865}
866
Jordy Rosed325ffb2010-07-08 23:57:29 +0000867//===----------------------------------------------------------------------===//
Ted Kremenek9c149532010-12-01 21:57:22 +0000868// evaluation of individual function calls.
Jordy Rosed325ffb2010-07-08 23:57:29 +0000869//===----------------------------------------------------------------------===//
870
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000871void CStringChecker::evalCopyCommon(CheckerContext &C,
872 const CallExpr *CE,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000873 ProgramStateRef state,
Jordy Rosed325ffb2010-07-08 23:57:29 +0000874 const Expr *Size, const Expr *Dest,
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000875 const Expr *Source, bool Restricted,
876 bool IsMempcpy) const {
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000877 CurrentFunctionDescription = "memory copy function";
878
Jordy Rosed325ffb2010-07-08 23:57:29 +0000879 // See if the size argument is zero.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000880 const LocationContext *LCtx = C.getLocationContext();
881 SVal sizeVal = state->getSVal(Size, LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000882 QualType sizeTy = Size->getType();
Jordy Rosed325ffb2010-07-08 23:57:29 +0000883
Ted Kremenek8bef8232012-01-26 21:29:00 +0000884 ProgramStateRef stateZeroSize, stateNonZeroSize;
Jordy Rose1e022412011-06-16 05:51:02 +0000885 llvm::tie(stateZeroSize, stateNonZeroSize) =
886 assumeZero(C, state, sizeVal, sizeTy);
Jordy Rosed325ffb2010-07-08 23:57:29 +0000887
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000888 // Get the value of the Dest.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000889 SVal destVal = state->getSVal(Dest, LCtx);
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000890
891 // If the size is zero, there won't be any actual memory access, so
892 // just bind the return value to the destination buffer and return.
Anna Zaksdd160f32012-05-03 18:21:28 +0000893 if (stateZeroSize && !stateNonZeroSize) {
Ted Kremenek5eca4822012-01-06 22:09:28 +0000894 stateZeroSize = stateZeroSize->BindExpr(CE, LCtx, destVal);
Anna Zaks0bd6b112011-10-26 21:06:34 +0000895 C.addTransition(stateZeroSize);
Anna Zaksdd160f32012-05-03 18:21:28 +0000896 return;
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000897 }
Jordy Rosed325ffb2010-07-08 23:57:29 +0000898
899 // If the size can be nonzero, we have to check the other arguments.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000900 if (stateNonZeroSize) {
Jordy Rose22d27172011-06-04 00:04:22 +0000901 state = stateNonZeroSize;
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000902
903 // Ensure the destination is not null. If it is NULL there will be a
904 // NULL pointer dereference.
905 state = checkNonNull(C, state, Dest, destVal);
906 if (!state)
907 return;
908
909 // Get the value of the Src.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000910 SVal srcVal = state->getSVal(Source, LCtx);
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000911
912 // Ensure the source is not null. If it is NULL there will be a
913 // NULL pointer dereference.
914 state = checkNonNull(C, state, Source, srcVal);
915 if (!state)
916 return;
917
Jordy Rose7182b962011-06-04 01:50:25 +0000918 // Ensure the accesses are valid and that the buffers do not overlap.
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000919 const char * const writeWarning =
920 "Memory copy function overflows destination buffer";
Jordy Rosee64f3112010-08-16 07:51:42 +0000921 state = CheckBufferAccess(C, state, Size, Dest, Source,
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000922 writeWarning, /* sourceWarning = */ NULL);
Jordy Rosed325ffb2010-07-08 23:57:29 +0000923 if (Restricted)
924 state = CheckOverlap(C, state, Size, Dest, Source);
Jordy Rosee64f3112010-08-16 07:51:42 +0000925
Jordy Rose7182b962011-06-04 01:50:25 +0000926 if (!state)
927 return;
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000928
Jordy Rose7182b962011-06-04 01:50:25 +0000929 // If this is mempcpy, get the byte after the last byte copied and
930 // bind the expr.
931 if (IsMempcpy) {
932 loc::MemRegionVal *destRegVal = dyn_cast<loc::MemRegionVal>(&destVal);
933 assert(destRegVal && "Destination should be a known MemRegionVal here");
934
935 // Get the length to copy.
936 NonLoc *lenValNonLoc = dyn_cast<NonLoc>(&sizeVal);
937
938 if (lenValNonLoc) {
939 // Get the byte after the last byte copied.
940 SVal lastElement = C.getSValBuilder().evalBinOpLN(state, BO_Add,
941 *destRegVal,
942 *lenValNonLoc,
943 Dest->getType());
944
945 // The byte after the last byte copied is the return value.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000946 state = state->BindExpr(CE, LCtx, lastElement);
Jordy Rose3f8bb2f2011-06-04 01:47:27 +0000947 } else {
Jordy Rose7182b962011-06-04 01:50:25 +0000948 // If we don't know how much we copied, we can at least
949 // conjure a return value for later.
Ted Kremenek66c486f2012-08-22 06:26:15 +0000950 SVal result = C.getSValBuilder().conjureSymbolVal(0, CE, LCtx,
951 C.blockCount());
Ted Kremenek5eca4822012-01-06 22:09:28 +0000952 state = state->BindExpr(CE, LCtx, result);
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000953 }
954
Jordy Rose7182b962011-06-04 01:50:25 +0000955 } else {
956 // All other copies return the destination buffer.
957 // (Well, bcopy() has a void return type, but this won't hurt.)
Ted Kremenek5eca4822012-01-06 22:09:28 +0000958 state = state->BindExpr(CE, LCtx, destVal);
Jordy Rosee64f3112010-08-16 07:51:42 +0000959 }
Jordy Rose7182b962011-06-04 01:50:25 +0000960
961 // Invalidate the destination.
962 // FIXME: Even if we can't perfectly model the copy, we should see if we
963 // can use LazyCompoundVals to copy the source values into the destination.
964 // This would probably remove any existing bindings past the end of the
965 // copied region, but that's still an improvement over blank invalidation.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000966 state = InvalidateBuffer(C, state, Dest,
967 state->getSVal(Dest, C.getLocationContext()));
Anna Zaks0bd6b112011-10-26 21:06:34 +0000968 C.addTransition(state);
Jordy Rosed325ffb2010-07-08 23:57:29 +0000969 }
970}
971
972
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000973void CStringChecker::evalMemcpy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +0000974 if (CE->getNumArgs() < 3)
975 return;
976
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000977 // void *memcpy(void *restrict dst, const void *restrict src, size_t n);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000978 // The return value is the address of the destination buffer.
Jordy Rosed325ffb2010-07-08 23:57:29 +0000979 const Expr *Dest = CE->getArg(0);
Ted Kremenek8bef8232012-01-26 21:29:00 +0000980 ProgramStateRef state = C.getState();
Jordy Rose3f8bb2f2011-06-04 01:47:27 +0000981
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000982 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1), true);
983}
984
985void CStringChecker::evalMempcpy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +0000986 if (CE->getNumArgs() < 3)
987 return;
988
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000989 // void *mempcpy(void *restrict dst, const void *restrict src, size_t n);
990 // The return value is a pointer to the byte following the last written byte.
991 const Expr *Dest = CE->getArg(0);
Ted Kremenek8bef8232012-01-26 21:29:00 +0000992 ProgramStateRef state = C.getState();
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000993
994 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1), true, true);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000995}
996
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000997void CStringChecker::evalMemmove(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +0000998 if (CE->getNumArgs() < 3)
999 return;
1000
Jordy Rosed325ffb2010-07-08 23:57:29 +00001001 // void *memmove(void *dst, const void *src, size_t n);
1002 // The return value is the address of the destination buffer.
1003 const Expr *Dest = CE->getArg(0);
Ted Kremenek8bef8232012-01-26 21:29:00 +00001004 ProgramStateRef state = C.getState();
Jordy Rose3f8bb2f2011-06-04 01:47:27 +00001005
Lenny Maioranib8b875b2011-03-31 21:36:53 +00001006 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1));
Jordy Rosed325ffb2010-07-08 23:57:29 +00001007}
1008
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001009void CStringChecker::evalBcopy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001010 if (CE->getNumArgs() < 3)
1011 return;
1012
Jordy Rosed325ffb2010-07-08 23:57:29 +00001013 // void bcopy(const void *src, void *dst, size_t n);
Lenny Maioranib8b875b2011-03-31 21:36:53 +00001014 evalCopyCommon(C, CE, C.getState(),
1015 CE->getArg(2), CE->getArg(1), CE->getArg(0));
Jordy Rosed325ffb2010-07-08 23:57:29 +00001016}
1017
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001018void CStringChecker::evalMemcmp(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001019 if (CE->getNumArgs() < 3)
1020 return;
1021
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001022 // int memcmp(const void *s1, const void *s2, size_t n);
Jordy Rose9e49d9f2011-06-20 02:06:40 +00001023 CurrentFunctionDescription = "memory comparison function";
1024
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001025 const Expr *Left = CE->getArg(0);
1026 const Expr *Right = CE->getArg(1);
1027 const Expr *Size = CE->getArg(2);
1028
Ted Kremenek8bef8232012-01-26 21:29:00 +00001029 ProgramStateRef state = C.getState();
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001030 SValBuilder &svalBuilder = C.getSValBuilder();
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001031
Jordy Rosed325ffb2010-07-08 23:57:29 +00001032 // See if the size argument is zero.
Ted Kremenek5eca4822012-01-06 22:09:28 +00001033 const LocationContext *LCtx = C.getLocationContext();
1034 SVal sizeVal = state->getSVal(Size, LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001035 QualType sizeTy = Size->getType();
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001036
Ted Kremenek8bef8232012-01-26 21:29:00 +00001037 ProgramStateRef stateZeroSize, stateNonZeroSize;
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001038 llvm::tie(stateZeroSize, stateNonZeroSize) =
1039 assumeZero(C, state, sizeVal, sizeTy);
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001040
Jordy Rosed325ffb2010-07-08 23:57:29 +00001041 // If the size can be zero, the result will be 0 in that case, and we don't
1042 // have to check either of the buffers.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001043 if (stateZeroSize) {
1044 state = stateZeroSize;
Ted Kremenek5eca4822012-01-06 22:09:28 +00001045 state = state->BindExpr(CE, LCtx,
1046 svalBuilder.makeZeroVal(CE->getType()));
Anna Zaks0bd6b112011-10-26 21:06:34 +00001047 C.addTransition(state);
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001048 }
1049
Jordy Rosed325ffb2010-07-08 23:57:29 +00001050 // If the size can be nonzero, we have to check the other arguments.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001051 if (stateNonZeroSize) {
1052 state = stateNonZeroSize;
Jordy Rosed325ffb2010-07-08 23:57:29 +00001053 // If we know the two buffers are the same, we know the result is 0.
1054 // First, get the two buffers' addresses. Another checker will have already
1055 // made sure they're not undefined.
Ted Kremenek5eca4822012-01-06 22:09:28 +00001056 DefinedOrUnknownSVal LV =
1057 cast<DefinedOrUnknownSVal>(state->getSVal(Left, LCtx));
1058 DefinedOrUnknownSVal RV =
1059 cast<DefinedOrUnknownSVal>(state->getSVal(Right, LCtx));
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001060
Jordy Rosed325ffb2010-07-08 23:57:29 +00001061 // See if they are the same.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001062 DefinedOrUnknownSVal SameBuf = svalBuilder.evalEQ(state, LV, RV);
Ted Kremenek8bef8232012-01-26 21:29:00 +00001063 ProgramStateRef StSameBuf, StNotSameBuf;
Ted Kremenek28f47b92010-12-01 22:16:56 +00001064 llvm::tie(StSameBuf, StNotSameBuf) = state->assume(SameBuf);
Jordy Rosed325ffb2010-07-08 23:57:29 +00001065
Jordy Rose1e022412011-06-16 05:51:02 +00001066 // If the two arguments might be the same buffer, we know the result is 0,
Jordy Rosed325ffb2010-07-08 23:57:29 +00001067 // and we only need to check one size.
1068 if (StSameBuf) {
1069 state = StSameBuf;
1070 state = CheckBufferAccess(C, state, Size, Left);
1071 if (state) {
Ted Kremenek5eca4822012-01-06 22:09:28 +00001072 state = StSameBuf->BindExpr(CE, LCtx,
1073 svalBuilder.makeZeroVal(CE->getType()));
Anna Zaks0bd6b112011-10-26 21:06:34 +00001074 C.addTransition(state);
Jordy Rosed325ffb2010-07-08 23:57:29 +00001075 }
1076 }
1077
1078 // If the two arguments might be different buffers, we have to check the
1079 // size of both of them.
1080 if (StNotSameBuf) {
1081 state = StNotSameBuf;
1082 state = CheckBufferAccess(C, state, Size, Left, Right);
1083 if (state) {
1084 // The return value is the comparison result, which we don't know.
Ted Kremenek66c486f2012-08-22 06:26:15 +00001085 SVal CmpV = svalBuilder.conjureSymbolVal(0, CE, LCtx, C.blockCount());
Ted Kremenek5eca4822012-01-06 22:09:28 +00001086 state = state->BindExpr(CE, LCtx, CmpV);
Anna Zaks0bd6b112011-10-26 21:06:34 +00001087 C.addTransition(state);
Jordy Rosed325ffb2010-07-08 23:57:29 +00001088 }
1089 }
1090 }
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001091}
1092
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001093void CStringChecker::evalstrLength(CheckerContext &C,
1094 const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001095 if (CE->getNumArgs() < 1)
1096 return;
1097
Jordy Rose19c5dd12010-07-27 01:37:31 +00001098 // size_t strlen(const char *s);
Ted Kremenekbe4242c2011-02-22 04:55:05 +00001099 evalstrLengthCommon(C, CE, /* IsStrnlen = */ false);
1100}
1101
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001102void CStringChecker::evalstrnLength(CheckerContext &C,
1103 const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001104 if (CE->getNumArgs() < 2)
1105 return;
1106
Ted Kremenekbe4242c2011-02-22 04:55:05 +00001107 // size_t strnlen(const char *s, size_t maxlen);
1108 evalstrLengthCommon(C, CE, /* IsStrnlen = */ true);
1109}
1110
1111void CStringChecker::evalstrLengthCommon(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001112 bool IsStrnlen) const {
Jordy Rose9e49d9f2011-06-20 02:06:40 +00001113 CurrentFunctionDescription = "string length function";
Ted Kremenek8bef8232012-01-26 21:29:00 +00001114 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001115 const LocationContext *LCtx = C.getLocationContext();
Jordy Rose793bff32011-06-14 01:15:31 +00001116
1117 if (IsStrnlen) {
1118 const Expr *maxlenExpr = CE->getArg(1);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001119 SVal maxlenVal = state->getSVal(maxlenExpr, LCtx);
Jordy Rose793bff32011-06-14 01:15:31 +00001120
Ted Kremenek8bef8232012-01-26 21:29:00 +00001121 ProgramStateRef stateZeroSize, stateNonZeroSize;
Jordy Rose793bff32011-06-14 01:15:31 +00001122 llvm::tie(stateZeroSize, stateNonZeroSize) =
1123 assumeZero(C, state, maxlenVal, maxlenExpr->getType());
1124
1125 // If the size can be zero, the result will be 0 in that case, and we don't
1126 // have to check the string itself.
1127 if (stateZeroSize) {
1128 SVal zero = C.getSValBuilder().makeZeroVal(CE->getType());
Ted Kremenek5eca4822012-01-06 22:09:28 +00001129 stateZeroSize = stateZeroSize->BindExpr(CE, LCtx, zero);
Anna Zaks0bd6b112011-10-26 21:06:34 +00001130 C.addTransition(stateZeroSize);
Jordy Rose793bff32011-06-14 01:15:31 +00001131 }
1132
1133 // If the size is GUARANTEED to be zero, we're done!
1134 if (!stateNonZeroSize)
1135 return;
1136
1137 // Otherwise, record the assumption that the size is nonzero.
1138 state = stateNonZeroSize;
1139 }
1140
1141 // Check that the string argument is non-null.
Jordy Rose19c5dd12010-07-27 01:37:31 +00001142 const Expr *Arg = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001143 SVal ArgVal = state->getSVal(Arg, LCtx);
Jordy Rose19c5dd12010-07-27 01:37:31 +00001144
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001145 state = checkNonNull(C, state, Arg, ArgVal);
Jordy Rose19c5dd12010-07-27 01:37:31 +00001146
Jordy Rosebd32bee2011-06-14 01:26:48 +00001147 if (!state)
1148 return;
Jordy Rosea5261542010-08-14 21:02:52 +00001149
Jordy Rosebd32bee2011-06-14 01:26:48 +00001150 SVal strLength = getCStringLength(C, state, Arg, ArgVal);
Jordy Rosea5261542010-08-14 21:02:52 +00001151
Jordy Rosebd32bee2011-06-14 01:26:48 +00001152 // If the argument isn't a valid C string, there's no valid state to
1153 // transition to.
1154 if (strLength.isUndef())
1155 return;
Jordy Rose793bff32011-06-14 01:15:31 +00001156
Jordy Rosebd32bee2011-06-14 01:26:48 +00001157 DefinedOrUnknownSVal result = UnknownVal();
Jordy Rose793bff32011-06-14 01:15:31 +00001158
Jordy Rosebd32bee2011-06-14 01:26:48 +00001159 // If the check is for strnlen() then bind the return value to no more than
1160 // the maxlen value.
1161 if (IsStrnlen) {
Jordy Roseee2fde12011-06-16 05:56:50 +00001162 QualType cmpTy = C.getSValBuilder().getConditionType();
Jordy Rose793bff32011-06-14 01:15:31 +00001163
Jordy Rosebd32bee2011-06-14 01:26:48 +00001164 // It's a little unfortunate to be getting this again,
1165 // but it's not that expensive...
1166 const Expr *maxlenExpr = CE->getArg(1);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001167 SVal maxlenVal = state->getSVal(maxlenExpr, LCtx);
Ted Kremenekbe4242c2011-02-22 04:55:05 +00001168
Jordy Rosebd32bee2011-06-14 01:26:48 +00001169 NonLoc *strLengthNL = dyn_cast<NonLoc>(&strLength);
1170 NonLoc *maxlenValNL = dyn_cast<NonLoc>(&maxlenVal);
Ted Kremenekbe4242c2011-02-22 04:55:05 +00001171
Jordy Rosebd32bee2011-06-14 01:26:48 +00001172 if (strLengthNL && maxlenValNL) {
Ted Kremenek8bef8232012-01-26 21:29:00 +00001173 ProgramStateRef stateStringTooLong, stateStringNotTooLong;
Jordy Rose793bff32011-06-14 01:15:31 +00001174
Jordy Rosebd32bee2011-06-14 01:26:48 +00001175 // Check if the strLength is greater than the maxlen.
1176 llvm::tie(stateStringTooLong, stateStringNotTooLong) =
1177 state->assume(cast<DefinedOrUnknownSVal>
1178 (C.getSValBuilder().evalBinOpNN(state, BO_GT,
1179 *strLengthNL,
1180 *maxlenValNL,
1181 cmpTy)));
Jordy Rose793bff32011-06-14 01:15:31 +00001182
Jordy Rosebd32bee2011-06-14 01:26:48 +00001183 if (stateStringTooLong && !stateStringNotTooLong) {
1184 // If the string is longer than maxlen, return maxlen.
1185 result = *maxlenValNL;
1186 } else if (stateStringNotTooLong && !stateStringTooLong) {
1187 // If the string is shorter than maxlen, return its length.
1188 result = *strLengthNL;
Ted Kremenekbe4242c2011-02-22 04:55:05 +00001189 }
1190 }
1191
Jordy Rosebd32bee2011-06-14 01:26:48 +00001192 if (result.isUnknown()) {
1193 // If we don't have enough information for a comparison, there's
1194 // no guarantee the full string length will actually be returned.
1195 // All we know is the return value is the min of the string length
1196 // and the limit. This is better than nothing.
Ted Kremenek66c486f2012-08-22 06:26:15 +00001197 result = C.getSValBuilder().conjureSymbolVal(0, CE, LCtx, C.blockCount());
Jordy Rosebd32bee2011-06-14 01:26:48 +00001198 NonLoc *resultNL = cast<NonLoc>(&result);
1199
1200 if (strLengthNL) {
1201 state = state->assume(cast<DefinedOrUnknownSVal>
1202 (C.getSValBuilder().evalBinOpNN(state, BO_LE,
1203 *resultNL,
1204 *strLengthNL,
1205 cmpTy)), true);
1206 }
1207
1208 if (maxlenValNL) {
1209 state = state->assume(cast<DefinedOrUnknownSVal>
1210 (C.getSValBuilder().evalBinOpNN(state, BO_LE,
1211 *resultNL,
1212 *maxlenValNL,
1213 cmpTy)), true);
1214 }
1215 }
1216
1217 } else {
1218 // This is a plain strlen(), not strnlen().
1219 result = cast<DefinedOrUnknownSVal>(strLength);
1220
1221 // If we don't know the length of the string, conjure a return
1222 // value, so it can be used in constraints, at least.
1223 if (result.isUnknown()) {
Ted Kremenek66c486f2012-08-22 06:26:15 +00001224 result = C.getSValBuilder().conjureSymbolVal(0, CE, LCtx, C.blockCount());
Jordy Rosebd32bee2011-06-14 01:26:48 +00001225 }
Jordy Rose19c5dd12010-07-27 01:37:31 +00001226 }
Jordy Rosebd32bee2011-06-14 01:26:48 +00001227
1228 // Bind the return value.
1229 assert(!result.isUnknown() && "Should have conjured a value by now");
Ted Kremenek5eca4822012-01-06 22:09:28 +00001230 state = state->BindExpr(CE, LCtx, result);
Anna Zaks0bd6b112011-10-26 21:06:34 +00001231 C.addTransition(state);
Jordy Rose19c5dd12010-07-27 01:37:31 +00001232}
1233
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001234void CStringChecker::evalStrcpy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001235 if (CE->getNumArgs() < 2)
1236 return;
1237
Jordy Rosee64f3112010-08-16 07:51:42 +00001238 // char *strcpy(char *restrict dst, const char *restrict src);
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001239 evalStrcpyCommon(C, CE,
1240 /* returnEnd = */ false,
1241 /* isBounded = */ false,
1242 /* isAppending = */ false);
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001243}
1244
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001245void CStringChecker::evalStrncpy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001246 if (CE->getNumArgs() < 3)
1247 return;
1248
Jordy Rosec1525862011-06-04 00:05:23 +00001249 // char *strncpy(char *restrict dst, const char *restrict src, size_t n);
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001250 evalStrcpyCommon(C, CE,
1251 /* returnEnd = */ false,
1252 /* isBounded = */ true,
1253 /* isAppending = */ false);
Jordy Rosee64f3112010-08-16 07:51:42 +00001254}
1255
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001256void CStringChecker::evalStpcpy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001257 if (CE->getNumArgs() < 2)
1258 return;
1259
Jordy Rosee64f3112010-08-16 07:51:42 +00001260 // char *stpcpy(char *restrict dst, const char *restrict src);
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001261 evalStrcpyCommon(C, CE,
1262 /* returnEnd = */ true,
1263 /* isBounded = */ false,
1264 /* isAppending = */ false);
1265}
1266
1267void CStringChecker::evalStrcat(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001268 if (CE->getNumArgs() < 2)
1269 return;
1270
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001271 //char *strcat(char *restrict s1, const char *restrict s2);
1272 evalStrcpyCommon(C, CE,
1273 /* returnEnd = */ false,
1274 /* isBounded = */ false,
1275 /* isAppending = */ true);
1276}
1277
1278void CStringChecker::evalStrncat(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001279 if (CE->getNumArgs() < 3)
1280 return;
1281
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001282 //char *strncat(char *restrict s1, const char *restrict s2, size_t n);
1283 evalStrcpyCommon(C, CE,
1284 /* returnEnd = */ false,
1285 /* isBounded = */ true,
1286 /* isAppending = */ true);
Jordy Rosee64f3112010-08-16 07:51:42 +00001287}
1288
Ted Kremenek9c149532010-12-01 21:57:22 +00001289void CStringChecker::evalStrcpyCommon(CheckerContext &C, const CallExpr *CE,
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001290 bool returnEnd, bool isBounded,
1291 bool isAppending) const {
Jordy Rose9e49d9f2011-06-20 02:06:40 +00001292 CurrentFunctionDescription = "string copy function";
Ted Kremenek8bef8232012-01-26 21:29:00 +00001293 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001294 const LocationContext *LCtx = C.getLocationContext();
Jordy Rosee64f3112010-08-16 07:51:42 +00001295
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001296 // Check that the destination is non-null.
Jordy Rosee64f3112010-08-16 07:51:42 +00001297 const Expr *Dst = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001298 SVal DstVal = state->getSVal(Dst, LCtx);
Jordy Rosee64f3112010-08-16 07:51:42 +00001299
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001300 state = checkNonNull(C, state, Dst, DstVal);
Jordy Rosee64f3112010-08-16 07:51:42 +00001301 if (!state)
1302 return;
1303
1304 // Check that the source is non-null.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001305 const Expr *srcExpr = CE->getArg(1);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001306 SVal srcVal = state->getSVal(srcExpr, LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001307 state = checkNonNull(C, state, srcExpr, srcVal);
Jordy Rosee64f3112010-08-16 07:51:42 +00001308 if (!state)
1309 return;
1310
1311 // Get the string length of the source.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001312 SVal strLength = getCStringLength(C, state, srcExpr, srcVal);
Jordy Rosee64f3112010-08-16 07:51:42 +00001313
1314 // If the source isn't a valid C string, give up.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001315 if (strLength.isUndef())
Jordy Rosee64f3112010-08-16 07:51:42 +00001316 return;
1317
Jordy Rosed5af0e12011-06-15 05:52:56 +00001318 SValBuilder &svalBuilder = C.getSValBuilder();
1319 QualType cmpTy = svalBuilder.getConditionType();
Jordy Rose8912aae2011-06-20 21:55:40 +00001320 QualType sizeTy = svalBuilder.getContext().getSizeType();
Jordy Rosed5af0e12011-06-15 05:52:56 +00001321
Jordy Rose8912aae2011-06-20 21:55:40 +00001322 // These two values allow checking two kinds of errors:
1323 // - actual overflows caused by a source that doesn't fit in the destination
1324 // - potential overflows caused by a bound that could exceed the destination
Jordy Rosed5af0e12011-06-15 05:52:56 +00001325 SVal amountCopied = UnknownVal();
Jordy Rose8912aae2011-06-20 21:55:40 +00001326 SVal maxLastElementIndex = UnknownVal();
1327 const char *boundWarning = NULL;
Jordy Rosed5af0e12011-06-15 05:52:56 +00001328
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001329 // If the function is strncpy, strncat, etc... it is bounded.
1330 if (isBounded) {
1331 // Get the max number of characters to copy.
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001332 const Expr *lenExpr = CE->getArg(2);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001333 SVal lenVal = state->getSVal(lenExpr, LCtx);
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001334
Jordy Rosed5af0e12011-06-15 05:52:56 +00001335 // Protect against misdeclared strncpy().
Jordy Rose8912aae2011-06-20 21:55:40 +00001336 lenVal = svalBuilder.evalCast(lenVal, sizeTy, lenExpr->getType());
Jordy Rosed5af0e12011-06-15 05:52:56 +00001337
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001338 NonLoc *strLengthNL = dyn_cast<NonLoc>(&strLength);
1339 NonLoc *lenValNL = dyn_cast<NonLoc>(&lenVal);
1340
Jordy Rosed5af0e12011-06-15 05:52:56 +00001341 // If we know both values, we might be able to figure out how much
1342 // we're copying.
1343 if (strLengthNL && lenValNL) {
Ted Kremenek8bef8232012-01-26 21:29:00 +00001344 ProgramStateRef stateSourceTooLong, stateSourceNotTooLong;
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001345
Jordy Rosed5af0e12011-06-15 05:52:56 +00001346 // Check if the max number to copy is less than the length of the src.
Jordy Rose8912aae2011-06-20 21:55:40 +00001347 // If the bound is equal to the source length, strncpy won't null-
1348 // terminate the result!
Jordy Rosed5af0e12011-06-15 05:52:56 +00001349 llvm::tie(stateSourceTooLong, stateSourceNotTooLong) =
1350 state->assume(cast<DefinedOrUnknownSVal>
Jordy Rose8912aae2011-06-20 21:55:40 +00001351 (svalBuilder.evalBinOpNN(state, BO_GE, *strLengthNL,
Jordy Rosed5af0e12011-06-15 05:52:56 +00001352 *lenValNL, cmpTy)));
1353
1354 if (stateSourceTooLong && !stateSourceNotTooLong) {
1355 // Max number to copy is less than the length of the src, so the actual
1356 // strLength copied is the max number arg.
1357 state = stateSourceTooLong;
1358 amountCopied = lenVal;
1359
1360 } else if (!stateSourceTooLong && stateSourceNotTooLong) {
1361 // The source buffer entirely fits in the bound.
1362 state = stateSourceNotTooLong;
1363 amountCopied = strLength;
1364 }
1365 }
1366
Jordy Rose5e5f1502011-06-20 03:49:16 +00001367 // We still want to know if the bound is known to be too large.
Jordy Rose8912aae2011-06-20 21:55:40 +00001368 if (lenValNL) {
1369 if (isAppending) {
1370 // For strncat, the check is strlen(dst) + lenVal < sizeof(dst)
1371
1372 // Get the string length of the destination. If the destination is
1373 // memory that can't have a string length, we shouldn't be copying
1374 // into it anyway.
1375 SVal dstStrLength = getCStringLength(C, state, Dst, DstVal);
1376 if (dstStrLength.isUndef())
1377 return;
1378
1379 if (NonLoc *dstStrLengthNL = dyn_cast<NonLoc>(&dstStrLength)) {
1380 maxLastElementIndex = svalBuilder.evalBinOpNN(state, BO_Add,
1381 *lenValNL,
1382 *dstStrLengthNL,
1383 sizeTy);
1384 boundWarning = "Size argument is greater than the free space in the "
1385 "destination buffer";
1386 }
1387
1388 } else {
1389 // For strncpy, this is just checking that lenVal <= sizeof(dst)
1390 // (Yes, strncpy and strncat differ in how they treat termination.
1391 // strncat ALWAYS terminates, but strncpy doesn't.)
Jordy Rose6e4244e2012-05-14 17:58:35 +00001392
1393 // We need a special case for when the copy size is zero, in which
1394 // case strncpy will do no work at all. Our bounds check uses n-1
1395 // as the last element accessed, so n == 0 is problematic.
1396 ProgramStateRef StateZeroSize, StateNonZeroSize;
1397 llvm::tie(StateZeroSize, StateNonZeroSize) =
1398 assumeZero(C, state, *lenValNL, sizeTy);
1399
1400 // If the size is known to be zero, we're done.
1401 if (StateZeroSize && !StateNonZeroSize) {
1402 StateZeroSize = StateZeroSize->BindExpr(CE, LCtx, DstVal);
1403 C.addTransition(StateZeroSize);
1404 return;
1405 }
1406
1407 // Otherwise, go ahead and figure out the last element we'll touch.
1408 // We don't record the non-zero assumption here because we can't
1409 // be sure. We won't warn on a possible zero.
Jordy Rose8912aae2011-06-20 21:55:40 +00001410 NonLoc one = cast<NonLoc>(svalBuilder.makeIntVal(1, sizeTy));
1411 maxLastElementIndex = svalBuilder.evalBinOpNN(state, BO_Sub, *lenValNL,
1412 one, sizeTy);
1413 boundWarning = "Size argument is greater than the length of the "
1414 "destination buffer";
1415 }
1416 }
Jordy Rose5e5f1502011-06-20 03:49:16 +00001417
Jordy Rosed5af0e12011-06-15 05:52:56 +00001418 // If we couldn't pin down the copy length, at least bound it.
Jordy Rose8912aae2011-06-20 21:55:40 +00001419 // FIXME: We should actually run this code path for append as well, but
1420 // right now it creates problems with constraints (since we can end up
1421 // trying to pass constraints from symbol to symbol).
1422 if (amountCopied.isUnknown() && !isAppending) {
Jordy Rosed5af0e12011-06-15 05:52:56 +00001423 // Try to get a "hypothetical" string length symbol, which we can later
1424 // set as a real value if that turns out to be the case.
1425 amountCopied = getCStringLength(C, state, lenExpr, srcVal, true);
1426 assert(!amountCopied.isUndef());
1427
1428 if (NonLoc *amountCopiedNL = dyn_cast<NonLoc>(&amountCopied)) {
1429 if (lenValNL) {
1430 // amountCopied <= lenVal
1431 SVal copiedLessThanBound = svalBuilder.evalBinOpNN(state, BO_LE,
1432 *amountCopiedNL,
1433 *lenValNL,
1434 cmpTy);
1435 state = state->assume(cast<DefinedOrUnknownSVal>(copiedLessThanBound),
1436 true);
1437 if (!state)
1438 return;
1439 }
1440
1441 if (strLengthNL) {
1442 // amountCopied <= strlen(source)
1443 SVal copiedLessThanSrc = svalBuilder.evalBinOpNN(state, BO_LE,
1444 *amountCopiedNL,
1445 *strLengthNL,
1446 cmpTy);
1447 state = state->assume(cast<DefinedOrUnknownSVal>(copiedLessThanSrc),
1448 true);
1449 if (!state)
1450 return;
1451 }
1452 }
1453 }
1454
1455 } else {
1456 // The function isn't bounded. The amount copied should match the length
1457 // of the source buffer.
1458 amountCopied = strLength;
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001459 }
1460
Jordy Rosed5af0e12011-06-15 05:52:56 +00001461 assert(state);
1462
1463 // This represents the number of characters copied into the destination
1464 // buffer. (It may not actually be the strlen if the destination buffer
1465 // is not terminated.)
1466 SVal finalStrLength = UnknownVal();
1467
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001468 // If this is an appending function (strcat, strncat...) then set the
1469 // string length to strlen(src) + strlen(dst) since the buffer will
1470 // ultimately contain both.
1471 if (isAppending) {
Jordy Rose1e022412011-06-16 05:51:02 +00001472 // Get the string length of the destination. If the destination is memory
1473 // that can't have a string length, we shouldn't be copying into it anyway.
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001474 SVal dstStrLength = getCStringLength(C, state, Dst, DstVal);
1475 if (dstStrLength.isUndef())
1476 return;
1477
Jordy Rosed5af0e12011-06-15 05:52:56 +00001478 NonLoc *srcStrLengthNL = dyn_cast<NonLoc>(&amountCopied);
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001479 NonLoc *dstStrLengthNL = dyn_cast<NonLoc>(&dstStrLength);
1480
Jordy Rosed5af0e12011-06-15 05:52:56 +00001481 // If we know both string lengths, we might know the final string length.
1482 if (srcStrLengthNL && dstStrLengthNL) {
1483 // Make sure the two lengths together don't overflow a size_t.
1484 state = checkAdditionOverflow(C, state, *srcStrLengthNL, *dstStrLengthNL);
1485 if (!state)
1486 return;
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001487
Jordy Rosed5af0e12011-06-15 05:52:56 +00001488 finalStrLength = svalBuilder.evalBinOpNN(state, BO_Add, *srcStrLengthNL,
1489 *dstStrLengthNL, sizeTy);
1490 }
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001491
Jordy Rosed5af0e12011-06-15 05:52:56 +00001492 // If we couldn't get a single value for the final string length,
1493 // we can at least bound it by the individual lengths.
1494 if (finalStrLength.isUnknown()) {
1495 // Try to get a "hypothetical" string length symbol, which we can later
1496 // set as a real value if that turns out to be the case.
1497 finalStrLength = getCStringLength(C, state, CE, DstVal, true);
1498 assert(!finalStrLength.isUndef());
1499
1500 if (NonLoc *finalStrLengthNL = dyn_cast<NonLoc>(&finalStrLength)) {
1501 if (srcStrLengthNL) {
1502 // finalStrLength >= srcStrLength
1503 SVal sourceInResult = svalBuilder.evalBinOpNN(state, BO_GE,
1504 *finalStrLengthNL,
1505 *srcStrLengthNL,
1506 cmpTy);
1507 state = state->assume(cast<DefinedOrUnknownSVal>(sourceInResult),
1508 true);
1509 if (!state)
1510 return;
1511 }
1512
1513 if (dstStrLengthNL) {
1514 // finalStrLength >= dstStrLength
1515 SVal destInResult = svalBuilder.evalBinOpNN(state, BO_GE,
1516 *finalStrLengthNL,
1517 *dstStrLengthNL,
1518 cmpTy);
1519 state = state->assume(cast<DefinedOrUnknownSVal>(destInResult),
1520 true);
1521 if (!state)
1522 return;
1523 }
1524 }
1525 }
1526
1527 } else {
1528 // Otherwise, this is a copy-over function (strcpy, strncpy, ...), and
1529 // the final string length will match the input string length.
1530 finalStrLength = amountCopied;
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001531 }
1532
Jordy Rosed5af0e12011-06-15 05:52:56 +00001533 // The final result of the function will either be a pointer past the last
1534 // copied element, or a pointer to the start of the destination buffer.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001535 SVal Result = (returnEnd ? UnknownVal() : DstVal);
Jordy Rosee64f3112010-08-16 07:51:42 +00001536
Jordy Rosed5af0e12011-06-15 05:52:56 +00001537 assert(state);
1538
Jordy Rosee64f3112010-08-16 07:51:42 +00001539 // If the destination is a MemRegion, try to check for a buffer overflow and
1540 // record the new string length.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001541 if (loc::MemRegionVal *dstRegVal = dyn_cast<loc::MemRegionVal>(&DstVal)) {
Jordy Rose8912aae2011-06-20 21:55:40 +00001542 QualType ptrTy = Dst->getType();
1543
1544 // If we have an exact value on a bounded copy, use that to check for
1545 // overflows, rather than our estimate about how much is actually copied.
1546 if (boundWarning) {
1547 if (NonLoc *maxLastNL = dyn_cast<NonLoc>(&maxLastElementIndex)) {
1548 SVal maxLastElement = svalBuilder.evalBinOpLN(state, BO_Add, *dstRegVal,
1549 *maxLastNL, ptrTy);
1550 state = CheckLocation(C, state, CE->getArg(2), maxLastElement,
1551 boundWarning);
1552 if (!state)
1553 return;
1554 }
1555 }
1556
1557 // Then, if the final length is known...
Jordy Rosed5af0e12011-06-15 05:52:56 +00001558 if (NonLoc *knownStrLength = dyn_cast<NonLoc>(&finalStrLength)) {
1559 SVal lastElement = svalBuilder.evalBinOpLN(state, BO_Add, *dstRegVal,
Jordy Rose8912aae2011-06-20 21:55:40 +00001560 *knownStrLength, ptrTy);
Jordy Rosee64f3112010-08-16 07:51:42 +00001561
Jordy Rose8912aae2011-06-20 21:55:40 +00001562 // ...and we haven't checked the bound, we'll check the actual copy.
1563 if (!boundWarning) {
1564 const char * const warningMsg =
1565 "String copy function overflows destination buffer";
1566 state = CheckLocation(C, state, Dst, lastElement, warningMsg);
1567 if (!state)
1568 return;
1569 }
Jordy Rosee64f3112010-08-16 07:51:42 +00001570
1571 // If this is a stpcpy-style copy, the last element is the return value.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001572 if (returnEnd)
1573 Result = lastElement;
Jordy Rosee64f3112010-08-16 07:51:42 +00001574 }
1575
1576 // Invalidate the destination. This must happen before we set the C string
1577 // length because invalidation will clear the length.
1578 // FIXME: Even if we can't perfectly model the copy, we should see if we
1579 // can use LazyCompoundVals to copy the source values into the destination.
1580 // This would probably remove any existing bindings past the end of the
1581 // string, but that's still an improvement over blank invalidation.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001582 state = InvalidateBuffer(C, state, Dst, *dstRegVal);
Jordy Rosee64f3112010-08-16 07:51:42 +00001583
Jordy Rose5e5f1502011-06-20 03:49:16 +00001584 // Set the C string length of the destination, if we know it.
Jordy Rose8912aae2011-06-20 21:55:40 +00001585 if (isBounded && !isAppending) {
1586 // strncpy is annoying in that it doesn't guarantee to null-terminate
1587 // the result string. If the original string didn't fit entirely inside
1588 // the bound (including the null-terminator), we don't know how long the
1589 // result is.
1590 if (amountCopied != strLength)
1591 finalStrLength = UnknownVal();
1592 }
1593 state = setCStringLength(state, dstRegVal->getRegion(), finalStrLength);
Jordy Rosee64f3112010-08-16 07:51:42 +00001594 }
1595
Jordy Rosed5af0e12011-06-15 05:52:56 +00001596 assert(state);
1597
Jordy Rosee64f3112010-08-16 07:51:42 +00001598 // If this is a stpcpy-style copy, but we were unable to check for a buffer
1599 // overflow, we still need a result. Conjure a return value.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001600 if (returnEnd && Result.isUnknown()) {
Ted Kremenek66c486f2012-08-22 06:26:15 +00001601 Result = svalBuilder.conjureSymbolVal(0, CE, LCtx, C.blockCount());
Jordy Rosee64f3112010-08-16 07:51:42 +00001602 }
1603
1604 // Set the return value.
Ted Kremenek5eca4822012-01-06 22:09:28 +00001605 state = state->BindExpr(CE, LCtx, Result);
Anna Zaks0bd6b112011-10-26 21:06:34 +00001606 C.addTransition(state);
Jordy Rosee64f3112010-08-16 07:51:42 +00001607}
1608
Lenny Maiorani318dd922011-04-12 17:08:43 +00001609void CStringChecker::evalStrcmp(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001610 if (CE->getNumArgs() < 2)
1611 return;
1612
Jordy Roseadc42d42011-06-16 07:13:34 +00001613 //int strcmp(const char *s1, const char *s2);
Lenny Maioranibd1d16a2011-04-28 15:09:11 +00001614 evalStrcmpCommon(C, CE, /* isBounded = */ false, /* ignoreCase = */ false);
Lenny Maiorani357f6ee2011-04-25 22:21:00 +00001615}
Lenny Maiorani318dd922011-04-12 17:08:43 +00001616
Lenny Maiorani357f6ee2011-04-25 22:21:00 +00001617void CStringChecker::evalStrncmp(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001618 if (CE->getNumArgs() < 3)
1619 return;
1620
Jordy Roseadc42d42011-06-16 07:13:34 +00001621 //int strncmp(const char *s1, const char *s2, size_t n);
Lenny Maioranibd1d16a2011-04-28 15:09:11 +00001622 evalStrcmpCommon(C, CE, /* isBounded = */ true, /* ignoreCase = */ false);
1623}
1624
1625void CStringChecker::evalStrcasecmp(CheckerContext &C,
1626 const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001627 if (CE->getNumArgs() < 2)
1628 return;
1629
Jordy Roseadc42d42011-06-16 07:13:34 +00001630 //int strcasecmp(const char *s1, const char *s2);
Lenny Maioranibd1d16a2011-04-28 15:09:11 +00001631 evalStrcmpCommon(C, CE, /* isBounded = */ false, /* ignoreCase = */ true);
Lenny Maiorani357f6ee2011-04-25 22:21:00 +00001632}
1633
Lenny Maiorani454fd2d2011-05-02 19:05:49 +00001634void CStringChecker::evalStrncasecmp(CheckerContext &C,
1635 const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001636 if (CE->getNumArgs() < 3)
1637 return;
1638
Jordy Roseadc42d42011-06-16 07:13:34 +00001639 //int strncasecmp(const char *s1, const char *s2, size_t n);
Lenny Maiorani454fd2d2011-05-02 19:05:49 +00001640 evalStrcmpCommon(C, CE, /* isBounded = */ true, /* ignoreCase = */ true);
1641}
1642
Lenny Maiorani357f6ee2011-04-25 22:21:00 +00001643void CStringChecker::evalStrcmpCommon(CheckerContext &C, const CallExpr *CE,
Lenny Maioranibd1d16a2011-04-28 15:09:11 +00001644 bool isBounded, bool ignoreCase) const {
Jordy Rose9e49d9f2011-06-20 02:06:40 +00001645 CurrentFunctionDescription = "string comparison function";
Ted Kremenek8bef8232012-01-26 21:29:00 +00001646 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001647 const LocationContext *LCtx = C.getLocationContext();
Lenny Maiorani318dd922011-04-12 17:08:43 +00001648
1649 // Check that the first string is non-null
1650 const Expr *s1 = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001651 SVal s1Val = state->getSVal(s1, LCtx);
Lenny Maiorani318dd922011-04-12 17:08:43 +00001652 state = checkNonNull(C, state, s1, s1Val);
1653 if (!state)
1654 return;
1655
1656 // Check that the second string is non-null.
1657 const Expr *s2 = CE->getArg(1);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001658 SVal s2Val = state->getSVal(s2, LCtx);
Lenny Maiorani318dd922011-04-12 17:08:43 +00001659 state = checkNonNull(C, state, s2, s2Val);
1660 if (!state)
1661 return;
1662
1663 // Get the string length of the first string or give up.
1664 SVal s1Length = getCStringLength(C, state, s1, s1Val);
1665 if (s1Length.isUndef())
1666 return;
1667
1668 // Get the string length of the second string or give up.
1669 SVal s2Length = getCStringLength(C, state, s2, s2Val);
1670 if (s2Length.isUndef())
1671 return;
1672
Jordy Roseadc42d42011-06-16 07:13:34 +00001673 // If we know the two buffers are the same, we know the result is 0.
1674 // First, get the two buffers' addresses. Another checker will have already
1675 // made sure they're not undefined.
1676 DefinedOrUnknownSVal LV = cast<DefinedOrUnknownSVal>(s1Val);
1677 DefinedOrUnknownSVal RV = cast<DefinedOrUnknownSVal>(s2Val);
Lenny Maiorani318dd922011-04-12 17:08:43 +00001678
Jordy Roseadc42d42011-06-16 07:13:34 +00001679 // See if they are the same.
Lenny Maiorani318dd922011-04-12 17:08:43 +00001680 SValBuilder &svalBuilder = C.getSValBuilder();
Jordy Roseadc42d42011-06-16 07:13:34 +00001681 DefinedOrUnknownSVal SameBuf = svalBuilder.evalEQ(state, LV, RV);
Ted Kremenek8bef8232012-01-26 21:29:00 +00001682 ProgramStateRef StSameBuf, StNotSameBuf;
Jordy Roseadc42d42011-06-16 07:13:34 +00001683 llvm::tie(StSameBuf, StNotSameBuf) = state->assume(SameBuf);
Lenny Maiorani318dd922011-04-12 17:08:43 +00001684
Jordy Roseadc42d42011-06-16 07:13:34 +00001685 // If the two arguments might be the same buffer, we know the result is 0,
1686 // and we only need to check one size.
1687 if (StSameBuf) {
Ted Kremenek5eca4822012-01-06 22:09:28 +00001688 StSameBuf = StSameBuf->BindExpr(CE, LCtx,
1689 svalBuilder.makeZeroVal(CE->getType()));
Anna Zaks0bd6b112011-10-26 21:06:34 +00001690 C.addTransition(StSameBuf);
Jordy Roseadc42d42011-06-16 07:13:34 +00001691
1692 // If the two arguments are GUARANTEED to be the same, we're done!
1693 if (!StNotSameBuf)
1694 return;
1695 }
1696
1697 assert(StNotSameBuf);
1698 state = StNotSameBuf;
1699
1700 // At this point we can go about comparing the two buffers.
1701 // For now, we only do this if they're both known string literals.
1702
1703 // Attempt to extract string literals from both expressions.
1704 const StringLiteral *s1StrLiteral = getCStringLiteral(C, state, s1, s1Val);
1705 const StringLiteral *s2StrLiteral = getCStringLiteral(C, state, s2, s2Val);
1706 bool canComputeResult = false;
1707
1708 if (s1StrLiteral && s2StrLiteral) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001709 StringRef s1StrRef = s1StrLiteral->getString();
1710 StringRef s2StrRef = s2StrLiteral->getString();
Jordy Roseadc42d42011-06-16 07:13:34 +00001711
1712 if (isBounded) {
1713 // Get the max number of characters to compare.
1714 const Expr *lenExpr = CE->getArg(2);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001715 SVal lenVal = state->getSVal(lenExpr, LCtx);
Jordy Roseadc42d42011-06-16 07:13:34 +00001716
1717 // If the length is known, we can get the right substrings.
1718 if (const llvm::APSInt *len = svalBuilder.getKnownValue(state, lenVal)) {
1719 // Create substrings of each to compare the prefix.
1720 s1StrRef = s1StrRef.substr(0, (size_t)len->getZExtValue());
1721 s2StrRef = s2StrRef.substr(0, (size_t)len->getZExtValue());
1722 canComputeResult = true;
1723 }
1724 } else {
1725 // This is a normal, unbounded strcmp.
1726 canComputeResult = true;
1727 }
1728
1729 if (canComputeResult) {
1730 // Real strcmp stops at null characters.
1731 size_t s1Term = s1StrRef.find('\0');
Chris Lattner5f9e2722011-07-23 10:55:15 +00001732 if (s1Term != StringRef::npos)
Jordy Roseadc42d42011-06-16 07:13:34 +00001733 s1StrRef = s1StrRef.substr(0, s1Term);
1734
1735 size_t s2Term = s2StrRef.find('\0');
Chris Lattner5f9e2722011-07-23 10:55:15 +00001736 if (s2Term != StringRef::npos)
Jordy Roseadc42d42011-06-16 07:13:34 +00001737 s2StrRef = s2StrRef.substr(0, s2Term);
1738
1739 // Use StringRef's comparison methods to compute the actual result.
1740 int result;
1741
1742 if (ignoreCase) {
1743 // Compare string 1 to string 2 the same way strcasecmp() does.
1744 result = s1StrRef.compare_lower(s2StrRef);
1745 } else {
1746 // Compare string 1 to string 2 the same way strcmp() does.
1747 result = s1StrRef.compare(s2StrRef);
1748 }
1749
1750 // Build the SVal of the comparison and bind the return value.
1751 SVal resultVal = svalBuilder.makeIntVal(result, CE->getType());
Ted Kremenek5eca4822012-01-06 22:09:28 +00001752 state = state->BindExpr(CE, LCtx, resultVal);
Jordy Roseadc42d42011-06-16 07:13:34 +00001753 }
1754 }
1755
1756 if (!canComputeResult) {
1757 // Conjure a symbolic value. It's the best we can do.
Ted Kremenek66c486f2012-08-22 06:26:15 +00001758 SVal resultVal = svalBuilder.conjureSymbolVal(0, CE, LCtx, C.blockCount());
Ted Kremenek5eca4822012-01-06 22:09:28 +00001759 state = state->BindExpr(CE, LCtx, resultVal);
Jordy Roseadc42d42011-06-16 07:13:34 +00001760 }
1761
1762 // Record this as a possible path.
Anna Zaks0bd6b112011-10-26 21:06:34 +00001763 C.addTransition(state);
Lenny Maiorani318dd922011-04-12 17:08:43 +00001764}
1765
Jordy Rosed325ffb2010-07-08 23:57:29 +00001766//===----------------------------------------------------------------------===//
Jordy Rosea5261542010-08-14 21:02:52 +00001767// The driver method, and other Checker callbacks.
Jordy Rosed325ffb2010-07-08 23:57:29 +00001768//===----------------------------------------------------------------------===//
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001769
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001770bool CStringChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
Anna Zaks998e2752012-02-17 22:35:26 +00001771 const FunctionDecl *FDecl = C.getCalleeDecl(CE);
1772
1773 if (!FDecl)
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001774 return false;
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001775
Anna Zaks998e2752012-02-17 22:35:26 +00001776 FnCheck evalFunction = 0;
1777 if (C.isCLibraryFunction(FDecl, "memcpy"))
1778 evalFunction = &CStringChecker::evalMemcpy;
1779 else if (C.isCLibraryFunction(FDecl, "mempcpy"))
1780 evalFunction = &CStringChecker::evalMempcpy;
1781 else if (C.isCLibraryFunction(FDecl, "memcmp"))
1782 evalFunction = &CStringChecker::evalMemcmp;
1783 else if (C.isCLibraryFunction(FDecl, "memmove"))
1784 evalFunction = &CStringChecker::evalMemmove;
1785 else if (C.isCLibraryFunction(FDecl, "strcpy"))
1786 evalFunction = &CStringChecker::evalStrcpy;
1787 else if (C.isCLibraryFunction(FDecl, "strncpy"))
1788 evalFunction = &CStringChecker::evalStrncpy;
1789 else if (C.isCLibraryFunction(FDecl, "stpcpy"))
1790 evalFunction = &CStringChecker::evalStpcpy;
1791 else if (C.isCLibraryFunction(FDecl, "strcat"))
1792 evalFunction = &CStringChecker::evalStrcat;
1793 else if (C.isCLibraryFunction(FDecl, "strncat"))
1794 evalFunction = &CStringChecker::evalStrncat;
1795 else if (C.isCLibraryFunction(FDecl, "strlen"))
1796 evalFunction = &CStringChecker::evalstrLength;
1797 else if (C.isCLibraryFunction(FDecl, "strnlen"))
1798 evalFunction = &CStringChecker::evalstrnLength;
1799 else if (C.isCLibraryFunction(FDecl, "strcmp"))
1800 evalFunction = &CStringChecker::evalStrcmp;
1801 else if (C.isCLibraryFunction(FDecl, "strncmp"))
1802 evalFunction = &CStringChecker::evalStrncmp;
1803 else if (C.isCLibraryFunction(FDecl, "strcasecmp"))
1804 evalFunction = &CStringChecker::evalStrcasecmp;
1805 else if (C.isCLibraryFunction(FDecl, "strncasecmp"))
1806 evalFunction = &CStringChecker::evalStrncasecmp;
1807 else if (C.isCLibraryFunction(FDecl, "bcopy"))
1808 evalFunction = &CStringChecker::evalBcopy;
1809 else if (C.isCLibraryFunction(FDecl, "bcmp"))
1810 evalFunction = &CStringChecker::evalMemcmp;
1811
Jordy Rosed325ffb2010-07-08 23:57:29 +00001812 // If the callee isn't a string function, let another checker handle it.
Ted Kremenek9c149532010-12-01 21:57:22 +00001813 if (!evalFunction)
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001814 return false;
1815
Jordy Rose9e49d9f2011-06-20 02:06:40 +00001816 // Make sure each function sets its own description.
1817 // (But don't bother in a release build.)
1818 assert(!(CurrentFunctionDescription = NULL));
1819
Jordy Rosed325ffb2010-07-08 23:57:29 +00001820 // Check and evaluate the call.
Ted Kremenek9c149532010-12-01 21:57:22 +00001821 (this->*evalFunction)(C, CE);
Anna Zaks57300762012-02-07 00:56:14 +00001822
1823 // If the evaluate call resulted in no change, chain to the next eval call
1824 // handler.
1825 // Note, the custom CString evaluation calls assume that basic safety
1826 // properties are held. However, if the user chooses to turn off some of these
1827 // checks, we ignore the issues and leave the call evaluation to a generic
1828 // handler.
1829 if (!C.isDifferent())
1830 return false;
1831
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001832 return true;
1833}
Jordy Rosea5261542010-08-14 21:02:52 +00001834
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001835void CStringChecker::checkPreStmt(const DeclStmt *DS, CheckerContext &C) const {
Jordy Rosea5261542010-08-14 21:02:52 +00001836 // Record string length for char a[] = "abc";
Ted Kremenek8bef8232012-01-26 21:29:00 +00001837 ProgramStateRef state = C.getState();
Jordy Rosea5261542010-08-14 21:02:52 +00001838
1839 for (DeclStmt::const_decl_iterator I = DS->decl_begin(), E = DS->decl_end();
1840 I != E; ++I) {
1841 const VarDecl *D = dyn_cast<VarDecl>(*I);
1842 if (!D)
1843 continue;
1844
1845 // FIXME: Handle array fields of structs.
1846 if (!D->getType()->isArrayType())
1847 continue;
1848
1849 const Expr *Init = D->getInit();
1850 if (!Init)
1851 continue;
1852 if (!isa<StringLiteral>(Init))
1853 continue;
1854
Anna Zaks39ac1872011-10-26 21:06:44 +00001855 Loc VarLoc = state->getLValue(D, C.getLocationContext());
Jordy Rosea5261542010-08-14 21:02:52 +00001856 const MemRegion *MR = VarLoc.getAsRegion();
1857 if (!MR)
1858 continue;
1859
Ted Kremenek5eca4822012-01-06 22:09:28 +00001860 SVal StrVal = state->getSVal(Init, C.getLocationContext());
Jordy Rosea5261542010-08-14 21:02:52 +00001861 assert(StrVal.isValid() && "Initializer string is unknown or undefined");
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001862 DefinedOrUnknownSVal strLength
1863 = cast<DefinedOrUnknownSVal>(getCStringLength(C, state, Init, StrVal));
Jordy Rosea5261542010-08-14 21:02:52 +00001864
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001865 state = state->set<CStringLength>(MR, strLength);
Jordy Rosea5261542010-08-14 21:02:52 +00001866 }
1867
Anna Zaks0bd6b112011-10-26 21:06:34 +00001868 C.addTransition(state);
Jordy Rosea5261542010-08-14 21:02:52 +00001869}
1870
Ted Kremenek8bef8232012-01-26 21:29:00 +00001871bool CStringChecker::wantsRegionChangeUpdate(ProgramStateRef state) const {
Jordan Rose166d5022012-11-02 01:54:06 +00001872 CStringLengthTy Entries = state->get<CStringLength>();
Jordy Rosea5261542010-08-14 21:02:52 +00001873 return !Entries.isEmpty();
1874}
1875
Ted Kremenek8bef8232012-01-26 21:29:00 +00001876ProgramStateRef
1877CStringChecker::checkRegionChanges(ProgramStateRef state,
Anna Zaksbf53dfa2012-12-20 00:38:25 +00001878 const InvalidatedSymbols *,
Jordy Rose537716a2011-08-27 22:51:26 +00001879 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00001880 ArrayRef<const MemRegion *> Regions,
Jordan Rose740d4902012-07-02 19:27:35 +00001881 const CallEvent *Call) const {
Jordan Rose166d5022012-11-02 01:54:06 +00001882 CStringLengthTy Entries = state->get<CStringLength>();
Jordy Rosea5261542010-08-14 21:02:52 +00001883 if (Entries.isEmpty())
1884 return state;
1885
1886 llvm::SmallPtrSet<const MemRegion *, 8> Invalidated;
1887 llvm::SmallPtrSet<const MemRegion *, 32> SuperRegions;
1888
1889 // First build sets for the changed regions and their super-regions.
Jordy Rose537716a2011-08-27 22:51:26 +00001890 for (ArrayRef<const MemRegion *>::iterator
1891 I = Regions.begin(), E = Regions.end(); I != E; ++I) {
1892 const MemRegion *MR = *I;
Jordy Rosea5261542010-08-14 21:02:52 +00001893 Invalidated.insert(MR);
1894
1895 SuperRegions.insert(MR);
1896 while (const SubRegion *SR = dyn_cast<SubRegion>(MR)) {
1897 MR = SR->getSuperRegion();
1898 SuperRegions.insert(MR);
1899 }
1900 }
1901
Jordan Rose166d5022012-11-02 01:54:06 +00001902 CStringLengthTy::Factory &F = state->get_context<CStringLength>();
Jordy Rosea5261542010-08-14 21:02:52 +00001903
1904 // Then loop over the entries in the current state.
Jordan Rose166d5022012-11-02 01:54:06 +00001905 for (CStringLengthTy::iterator I = Entries.begin(),
Jordy Rosea5261542010-08-14 21:02:52 +00001906 E = Entries.end(); I != E; ++I) {
1907 const MemRegion *MR = I.getKey();
1908
1909 // Is this entry for a super-region of a changed region?
1910 if (SuperRegions.count(MR)) {
Ted Kremenek3baf6722010-11-24 00:54:37 +00001911 Entries = F.remove(Entries, MR);
Jordy Rosea5261542010-08-14 21:02:52 +00001912 continue;
1913 }
1914
1915 // Is this entry for a sub-region of a changed region?
1916 const MemRegion *Super = MR;
1917 while (const SubRegion *SR = dyn_cast<SubRegion>(Super)) {
1918 Super = SR->getSuperRegion();
1919 if (Invalidated.count(Super)) {
Ted Kremenek3baf6722010-11-24 00:54:37 +00001920 Entries = F.remove(Entries, MR);
Jordy Rosea5261542010-08-14 21:02:52 +00001921 break;
1922 }
1923 }
1924 }
1925
1926 return state->set<CStringLength>(Entries);
1927}
1928
Ted Kremenek8bef8232012-01-26 21:29:00 +00001929void CStringChecker::checkLiveSymbols(ProgramStateRef state,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001930 SymbolReaper &SR) const {
Jordy Rosea5261542010-08-14 21:02:52 +00001931 // Mark all symbols in our string length map as valid.
Jordan Rose166d5022012-11-02 01:54:06 +00001932 CStringLengthTy Entries = state->get<CStringLength>();
Jordy Rosea5261542010-08-14 21:02:52 +00001933
Jordan Rose166d5022012-11-02 01:54:06 +00001934 for (CStringLengthTy::iterator I = Entries.begin(), E = Entries.end();
Jordy Rosea5261542010-08-14 21:02:52 +00001935 I != E; ++I) {
1936 SVal Len = I.getData();
Jordy Rosed5af0e12011-06-15 05:52:56 +00001937
Anna Zaks1d1d5152011-12-06 23:12:33 +00001938 for (SymExpr::symbol_iterator si = Len.symbol_begin(),
1939 se = Len.symbol_end(); si != se; ++si)
Jordy Rosed5af0e12011-06-15 05:52:56 +00001940 SR.markInUse(*si);
Jordy Rosea5261542010-08-14 21:02:52 +00001941 }
1942}
1943
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001944void CStringChecker::checkDeadSymbols(SymbolReaper &SR,
1945 CheckerContext &C) const {
Jordy Rosea5261542010-08-14 21:02:52 +00001946 if (!SR.hasDeadSymbols())
1947 return;
1948
Ted Kremenek8bef8232012-01-26 21:29:00 +00001949 ProgramStateRef state = C.getState();
Jordan Rose166d5022012-11-02 01:54:06 +00001950 CStringLengthTy Entries = state->get<CStringLength>();
Jordy Rosea5261542010-08-14 21:02:52 +00001951 if (Entries.isEmpty())
1952 return;
1953
Jordan Rose166d5022012-11-02 01:54:06 +00001954 CStringLengthTy::Factory &F = state->get_context<CStringLength>();
1955 for (CStringLengthTy::iterator I = Entries.begin(), E = Entries.end();
Jordy Rosea5261542010-08-14 21:02:52 +00001956 I != E; ++I) {
1957 SVal Len = I.getData();
1958 if (SymbolRef Sym = Len.getAsSymbol()) {
1959 if (SR.isDead(Sym))
Ted Kremenek3baf6722010-11-24 00:54:37 +00001960 Entries = F.remove(Entries, I.getKey());
Jordy Rosea5261542010-08-14 21:02:52 +00001961 }
1962 }
1963
1964 state = state->set<CStringLength>(Entries);
Anna Zaks0bd6b112011-10-26 21:06:34 +00001965 C.addTransition(state);
Jordy Rosea5261542010-08-14 21:02:52 +00001966}
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001967
Anna Zaks57300762012-02-07 00:56:14 +00001968#define REGISTER_CHECKER(name) \
1969void ento::register##name(CheckerManager &mgr) {\
1970 static CStringChecker *TheChecker = 0; \
1971 if (TheChecker == 0) \
1972 TheChecker = mgr.registerChecker<CStringChecker>(); \
1973 TheChecker->Filter.Check##name = true; \
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001974}
Anna Zaks57300762012-02-07 00:56:14 +00001975
1976REGISTER_CHECKER(CStringNullArg)
1977REGISTER_CHECKER(CStringOutOfBounds)
1978REGISTER_CHECKER(CStringBufferOverlap)
1979REGISTER_CHECKER(CStringNotNullTerm)
Anna Zaksf0dfc9c2012-02-17 22:35:31 +00001980
1981void ento::registerCStringCheckerBasic(CheckerManager &Mgr) {
1982 registerCStringNullArg(Mgr);
1983}