Bug Summary

File:build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
Warning:line 1545, column 17
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name CStringChecker.cpp -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/build-llvm -resource-dir /usr/lib/llvm-16/lib/clang/16.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I tools/clang/lib/StaticAnalyzer/Checkers -I /build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/clang/lib/StaticAnalyzer/Checkers -I /build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/clang/include -I tools/clang/include -I include -I /build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-16/lib/clang/16.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/build-llvm=build-llvm -fmacro-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/build-llvm=build-llvm -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/= -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -Wno-misleading-indentation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/build-llvm=build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2022-09-04-125545-48738-1 -x c++ /build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp

/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp

1//= CStringChecker.cpp - Checks calls to C string functions --------*- C++ -*-//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This defines CStringChecker, which is an assortment of checks on calls
10// to functions in <string.h>.
11//
12//===----------------------------------------------------------------------===//
13
14#include "InterCheckerAPI.h"
15#include "clang/Basic/CharInfo.h"
16#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
17#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
18#include "clang/StaticAnalyzer/Core/Checker.h"
19#include "clang/StaticAnalyzer/Core/CheckerManager.h"
20#include "clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h"
21#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
22#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
23#include "clang/StaticAnalyzer/Core/PathSensitive/DynamicExtent.h"
24#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
25#include "llvm/ADT/STLExtras.h"
26#include "llvm/ADT/SmallString.h"
27#include "llvm/ADT/StringExtras.h"
28#include "llvm/Support/raw_ostream.h"
29#include <functional>
30
31using namespace clang;
32using namespace ento;
33using namespace std::placeholders;
34
35namespace {
36struct AnyArgExpr {
37 // FIXME: Remove constructor in C++17 to turn it into an aggregate.
38 AnyArgExpr(const Expr *Expression, unsigned ArgumentIndex)
39 : Expression{Expression}, ArgumentIndex{ArgumentIndex} {}
40 const Expr *Expression;
41 unsigned ArgumentIndex;
42};
43
44struct SourceArgExpr : AnyArgExpr {
45 using AnyArgExpr::AnyArgExpr; // FIXME: Remove using in C++17.
46};
47
48struct DestinationArgExpr : AnyArgExpr {
49 using AnyArgExpr::AnyArgExpr; // FIXME: Same.
50};
51
52struct SizeArgExpr : AnyArgExpr {
53 using AnyArgExpr::AnyArgExpr; // FIXME: Same.
54};
55
56using ErrorMessage = SmallString<128>;
57enum class AccessKind { write, read };
58
59static ErrorMessage createOutOfBoundErrorMsg(StringRef FunctionDescription,
60 AccessKind Access) {
61 ErrorMessage Message;
62 llvm::raw_svector_ostream Os(Message);
63
64 // Function classification like: Memory copy function
65 Os << toUppercase(FunctionDescription.front())
66 << &FunctionDescription.data()[1];
67
68 if (Access == AccessKind::write) {
69 Os << " overflows the destination buffer";
70 } else { // read access
71 Os << " accesses out-of-bound array element";
72 }
73
74 return Message;
75}
76
77enum class ConcatFnKind { none = 0, strcat = 1, strlcat = 2 };
78
79enum class CharKind { Regular = 0, Wide };
80constexpr CharKind CK_Regular = CharKind::Regular;
81constexpr CharKind CK_Wide = CharKind::Wide;
82
83static QualType getCharPtrType(ASTContext &Ctx, CharKind CK) {
84 return Ctx.getPointerType(CK == CharKind::Regular ? Ctx.CharTy
85 : Ctx.WideCharTy);
86}
87
88class CStringChecker : public Checker< eval::Call,
89 check::PreStmt<DeclStmt>,
90 check::LiveSymbols,
91 check::DeadSymbols,
92 check::RegionChanges
93 > {
94 mutable std::unique_ptr<BugType> BT_Null, BT_Bounds, BT_Overlap,
95 BT_NotCString, BT_AdditionOverflow, BT_UninitRead;
96
97 mutable const char *CurrentFunctionDescription;
98
99public:
100 /// The filter is used to filter out the diagnostics which are not enabled by
101 /// the user.
102 struct CStringChecksFilter {
103 bool CheckCStringNullArg = false;
104 bool CheckCStringOutOfBounds = false;
105 bool CheckCStringBufferOverlap = false;
106 bool CheckCStringNotNullTerm = false;
107 bool CheckCStringUninitializedRead = false;
108
109 CheckerNameRef CheckNameCStringNullArg;
110 CheckerNameRef CheckNameCStringOutOfBounds;
111 CheckerNameRef CheckNameCStringBufferOverlap;
112 CheckerNameRef CheckNameCStringNotNullTerm;
113 CheckerNameRef CheckNameCStringUninitializedRead;
114 };
115
116 CStringChecksFilter Filter;
117
118 static void *getTag() { static int tag; return &tag; }
119
120 bool evalCall(const CallEvent &Call, CheckerContext &C) const;
121 void checkPreStmt(const DeclStmt *DS, CheckerContext &C) const;
122 void checkLiveSymbols(ProgramStateRef state, SymbolReaper &SR) const;
123 void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const;
124
125 ProgramStateRef
126 checkRegionChanges(ProgramStateRef state,
127 const InvalidatedSymbols *,
128 ArrayRef<const MemRegion *> ExplicitRegions,
129 ArrayRef<const MemRegion *> Regions,
130 const LocationContext *LCtx,
131 const CallEvent *Call) const;
132
133 using FnCheck = std::function<void(const CStringChecker *, CheckerContext &,
134 const CallExpr *)>;
135
136 CallDescriptionMap<FnCheck> Callbacks = {
137 {{CDF_MaybeBuiltin, "memcpy", 3},
138 std::bind(&CStringChecker::evalMemcpy, _1, _2, _3, CK_Regular)},
139 {{CDF_MaybeBuiltin, "wmemcpy", 3},
140 std::bind(&CStringChecker::evalMemcpy, _1, _2, _3, CK_Wide)},
141 {{CDF_MaybeBuiltin, "mempcpy", 3},
142 std::bind(&CStringChecker::evalMempcpy, _1, _2, _3, CK_Regular)},
143 {{CDF_None, "wmempcpy", 3},
144 std::bind(&CStringChecker::evalMempcpy, _1, _2, _3, CK_Wide)},
145 {{CDF_MaybeBuiltin, "memcmp", 3},
146 std::bind(&CStringChecker::evalMemcmp, _1, _2, _3, CK_Regular)},
147 {{CDF_MaybeBuiltin, "wmemcmp", 3},
148 std::bind(&CStringChecker::evalMemcmp, _1, _2, _3, CK_Wide)},
149 {{CDF_MaybeBuiltin, "memmove", 3},
150 std::bind(&CStringChecker::evalMemmove, _1, _2, _3, CK_Regular)},
151 {{CDF_MaybeBuiltin, "wmemmove", 3},
152 std::bind(&CStringChecker::evalMemmove, _1, _2, _3, CK_Wide)},
153 {{CDF_MaybeBuiltin, "memset", 3}, &CStringChecker::evalMemset},
154 {{CDF_MaybeBuiltin, "explicit_memset", 3}, &CStringChecker::evalMemset},
155 {{CDF_MaybeBuiltin, "strcpy", 2}, &CStringChecker::evalStrcpy},
156 {{CDF_MaybeBuiltin, "strncpy", 3}, &CStringChecker::evalStrncpy},
157 {{CDF_MaybeBuiltin, "stpcpy", 2}, &CStringChecker::evalStpcpy},
158 {{CDF_MaybeBuiltin, "strlcpy", 3}, &CStringChecker::evalStrlcpy},
159 {{CDF_MaybeBuiltin, "strcat", 2}, &CStringChecker::evalStrcat},
160 {{CDF_MaybeBuiltin, "strncat", 3}, &CStringChecker::evalStrncat},
161 {{CDF_MaybeBuiltin, "strlcat", 3}, &CStringChecker::evalStrlcat},
162 {{CDF_MaybeBuiltin, "strlen", 1}, &CStringChecker::evalstrLength},
163 {{CDF_MaybeBuiltin, "wcslen", 1}, &CStringChecker::evalstrLength},
164 {{CDF_MaybeBuiltin, "strnlen", 2}, &CStringChecker::evalstrnLength},
165 {{CDF_MaybeBuiltin, "wcsnlen", 2}, &CStringChecker::evalstrnLength},
166 {{CDF_MaybeBuiltin, "strcmp", 2}, &CStringChecker::evalStrcmp},
167 {{CDF_MaybeBuiltin, "strncmp", 3}, &CStringChecker::evalStrncmp},
168 {{CDF_MaybeBuiltin, "strcasecmp", 2}, &CStringChecker::evalStrcasecmp},
169 {{CDF_MaybeBuiltin, "strncasecmp", 3}, &CStringChecker::evalStrncasecmp},
170 {{CDF_MaybeBuiltin, "strsep", 2}, &CStringChecker::evalStrsep},
171 {{CDF_MaybeBuiltin, "bcopy", 3}, &CStringChecker::evalBcopy},
172 {{CDF_MaybeBuiltin, "bcmp", 3},
173 std::bind(&CStringChecker::evalMemcmp, _1, _2, _3, CK_Regular)},
174 {{CDF_MaybeBuiltin, "bzero", 2}, &CStringChecker::evalBzero},
175 {{CDF_MaybeBuiltin, "explicit_bzero", 2}, &CStringChecker::evalBzero},
176 };
177
178 // These require a bit of special handling.
179 CallDescription StdCopy{{"std", "copy"}, 3},
180 StdCopyBackward{{"std", "copy_backward"}, 3};
181
182 FnCheck identifyCall(const CallEvent &Call, CheckerContext &C) const;
183 void evalMemcpy(CheckerContext &C, const CallExpr *CE, CharKind CK) const;
184 void evalMempcpy(CheckerContext &C, const CallExpr *CE, CharKind CK) const;
185 void evalMemmove(CheckerContext &C, const CallExpr *CE, CharKind CK) const;
186 void evalBcopy(CheckerContext &C, const CallExpr *CE) const;
187 void evalCopyCommon(CheckerContext &C, const CallExpr *CE,
188 ProgramStateRef state, SizeArgExpr Size,
189 DestinationArgExpr Dest, SourceArgExpr Source,
190 bool Restricted, bool IsMempcpy, CharKind CK) const;
191
192 void evalMemcmp(CheckerContext &C, const CallExpr *CE, CharKind CK) const;
193
194 void evalstrLength(CheckerContext &C, const CallExpr *CE) const;
195 void evalstrnLength(CheckerContext &C, const CallExpr *CE) const;
196 void evalstrLengthCommon(CheckerContext &C,
197 const CallExpr *CE,
198 bool IsStrnlen = false) const;
199
200 void evalStrcpy(CheckerContext &C, const CallExpr *CE) const;
201 void evalStrncpy(CheckerContext &C, const CallExpr *CE) const;
202 void evalStpcpy(CheckerContext &C, const CallExpr *CE) const;
203 void evalStrlcpy(CheckerContext &C, const CallExpr *CE) const;
204 void evalStrcpyCommon(CheckerContext &C, const CallExpr *CE, bool ReturnEnd,
205 bool IsBounded, ConcatFnKind appendK,
206 bool returnPtr = true) const;
207
208 void evalStrcat(CheckerContext &C, const CallExpr *CE) const;
209 void evalStrncat(CheckerContext &C, const CallExpr *CE) const;
210 void evalStrlcat(CheckerContext &C, const CallExpr *CE) const;
211
212 void evalStrcmp(CheckerContext &C, const CallExpr *CE) const;
213 void evalStrncmp(CheckerContext &C, const CallExpr *CE) const;
214 void evalStrcasecmp(CheckerContext &C, const CallExpr *CE) const;
215 void evalStrncasecmp(CheckerContext &C, const CallExpr *CE) const;
216 void evalStrcmpCommon(CheckerContext &C,
217 const CallExpr *CE,
218 bool IsBounded = false,
219 bool IgnoreCase = false) const;
220
221 void evalStrsep(CheckerContext &C, const CallExpr *CE) const;
222
223 void evalStdCopy(CheckerContext &C, const CallExpr *CE) const;
224 void evalStdCopyBackward(CheckerContext &C, const CallExpr *CE) const;
225 void evalStdCopyCommon(CheckerContext &C, const CallExpr *CE) const;
226 void evalMemset(CheckerContext &C, const CallExpr *CE) const;
227 void evalBzero(CheckerContext &C, const CallExpr *CE) const;
228
229 // Utility methods
230 std::pair<ProgramStateRef , ProgramStateRef >
231 static assumeZero(CheckerContext &C,
232 ProgramStateRef state, SVal V, QualType Ty);
233
234 static ProgramStateRef setCStringLength(ProgramStateRef state,
235 const MemRegion *MR,
236 SVal strLength);
237 static SVal getCStringLengthForRegion(CheckerContext &C,
238 ProgramStateRef &state,
239 const Expr *Ex,
240 const MemRegion *MR,
241 bool hypothetical);
242 SVal getCStringLength(CheckerContext &C,
243 ProgramStateRef &state,
244 const Expr *Ex,
245 SVal Buf,
246 bool hypothetical = false) const;
247
248 const StringLiteral *getCStringLiteral(CheckerContext &C,
249 ProgramStateRef &state,
250 const Expr *expr,
251 SVal val) const;
252
253 static ProgramStateRef InvalidateBuffer(CheckerContext &C,
254 ProgramStateRef state,
255 const Expr *Ex, SVal V,
256 bool IsSourceBuffer,
257 const Expr *Size);
258
259 static bool SummarizeRegion(raw_ostream &os, ASTContext &Ctx,
260 const MemRegion *MR);
261
262 static bool memsetAux(const Expr *DstBuffer, SVal CharE,
263 const Expr *Size, CheckerContext &C,
264 ProgramStateRef &State);
265
266 // Re-usable checks
267 ProgramStateRef checkNonNull(CheckerContext &C, ProgramStateRef State,
268 AnyArgExpr Arg, SVal l) const;
269 ProgramStateRef CheckLocation(CheckerContext &C, ProgramStateRef state,
270 AnyArgExpr Buffer, SVal Element,
271 AccessKind Access,
272 CharKind CK = CharKind::Regular) const;
273 ProgramStateRef CheckBufferAccess(CheckerContext &C, ProgramStateRef State,
274 AnyArgExpr Buffer, SizeArgExpr Size,
275 AccessKind Access,
276 CharKind CK = CharKind::Regular) const;
277 ProgramStateRef CheckOverlap(CheckerContext &C, ProgramStateRef state,
278 SizeArgExpr Size, AnyArgExpr First,
279 AnyArgExpr Second,
280 CharKind CK = CharKind::Regular) const;
281 void emitOverlapBug(CheckerContext &C,
282 ProgramStateRef state,
283 const Stmt *First,
284 const Stmt *Second) const;
285
286 void emitNullArgBug(CheckerContext &C, ProgramStateRef State, const Stmt *S,
287 StringRef WarningMsg) const;
288 void emitOutOfBoundsBug(CheckerContext &C, ProgramStateRef State,
289 const Stmt *S, StringRef WarningMsg) const;
290 void emitNotCStringBug(CheckerContext &C, ProgramStateRef State,
291 const Stmt *S, StringRef WarningMsg) const;
292 void emitAdditionOverflowBug(CheckerContext &C, ProgramStateRef State) const;
293 void emitUninitializedReadBug(CheckerContext &C, ProgramStateRef State,
294 const Expr *E) const;
295 ProgramStateRef checkAdditionOverflow(CheckerContext &C,
296 ProgramStateRef state,
297 NonLoc left,
298 NonLoc right) const;
299
300 // Return true if the destination buffer of the copy function may be in bound.
301 // Expects SVal of Size to be positive and unsigned.
302 // Expects SVal of FirstBuf to be a FieldRegion.
303 static bool IsFirstBufInBound(CheckerContext &C,
304 ProgramStateRef state,
305 const Expr *FirstBuf,
306 const Expr *Size);
307};
308
309} //end anonymous namespace
310
311REGISTER_MAP_WITH_PROGRAMSTATE(CStringLength, const MemRegion *, SVal)namespace { class CStringLength {}; using CStringLengthTy = llvm
::ImmutableMap<const MemRegion *, SVal>; } namespace clang
{ namespace ento { template <> struct ProgramStateTrait
<CStringLength> : public ProgramStatePartialTrait<CStringLengthTy
> { static void *GDMIndex() { static int Index; return &
Index; } }; } }
312
313//===----------------------------------------------------------------------===//
314// Individual checks and utility methods.
315//===----------------------------------------------------------------------===//
316
317std::pair<ProgramStateRef , ProgramStateRef >
318CStringChecker::assumeZero(CheckerContext &C, ProgramStateRef state, SVal V,
319 QualType Ty) {
320 Optional<DefinedSVal> val = V.getAs<DefinedSVal>();
321 if (!val)
322 return std::pair<ProgramStateRef , ProgramStateRef >(state, state);
323
324 SValBuilder &svalBuilder = C.getSValBuilder();
325 DefinedOrUnknownSVal zero = svalBuilder.makeZeroVal(Ty);
326 return state->assume(svalBuilder.evalEQ(state, *val, zero));
327}
328
329ProgramStateRef CStringChecker::checkNonNull(CheckerContext &C,
330 ProgramStateRef State,
331 AnyArgExpr Arg, SVal l) const {
332 // If a previous check has failed, propagate the failure.
333 if (!State)
334 return nullptr;
335
336 ProgramStateRef stateNull, stateNonNull;
337 std::tie(stateNull, stateNonNull) =
338 assumeZero(C, State, l, Arg.Expression->getType());
339
340 if (stateNull && !stateNonNull) {
341 if (Filter.CheckCStringNullArg) {
342 SmallString<80> buf;
343 llvm::raw_svector_ostream OS(buf);
344 assert(CurrentFunctionDescription)(static_cast <bool> (CurrentFunctionDescription) ? void
(0) : __assert_fail ("CurrentFunctionDescription", "clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp"
, 344, __extension__ __PRETTY_FUNCTION__))
;
345 OS << "Null pointer passed as " << (Arg.ArgumentIndex + 1)
346 << llvm::getOrdinalSuffix(Arg.ArgumentIndex + 1) << " argument to "
347 << CurrentFunctionDescription;
348
349 emitNullArgBug(C, stateNull, Arg.Expression, OS.str());
350 }
351 return nullptr;
352 }
353
354 // From here on, assume that the value is non-null.
355 assert(stateNonNull)(static_cast <bool> (stateNonNull) ? void (0) : __assert_fail
("stateNonNull", "clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp"
, 355, __extension__ __PRETTY_FUNCTION__))
;
356 return stateNonNull;
357}
358
359// FIXME: This was originally copied from ArrayBoundChecker.cpp. Refactor?
360ProgramStateRef CStringChecker::CheckLocation(CheckerContext &C,
361 ProgramStateRef state,
362 AnyArgExpr Buffer, SVal Element,
363 AccessKind Access,
364 CharKind CK) const {
365
366 // If a previous check has failed, propagate the failure.
367 if (!state)
368 return nullptr;
369
370 // Check for out of bound array element access.
371 const MemRegion *R = Element.getAsRegion();
372 if (!R)
373 return state;
374
375 const auto *ER = dyn_cast<ElementRegion>(R);
376 if (!ER)
377 return state;
378
379 SValBuilder &svalBuilder = C.getSValBuilder();
380 ASTContext &Ctx = svalBuilder.getContext();
381
382 // Get the index of the accessed element.
383 NonLoc Idx = ER->getIndex();
384
385 if (CK == CharKind::Regular) {
386 if (ER->getValueType() != Ctx.CharTy)
387 return state;
388 } else {
389 if (ER->getValueType() != Ctx.WideCharTy)
390 return state;
391
392 QualType SizeTy = Ctx.getSizeType();
393 NonLoc WideSize =
394 svalBuilder
395 .makeIntVal(Ctx.getTypeSizeInChars(Ctx.WideCharTy).getQuantity(),
396 SizeTy)
397 .castAs<NonLoc>();
398 SVal Offset = svalBuilder.evalBinOpNN(state, BO_Mul, Idx, WideSize, SizeTy);
399 if (Offset.isUnknown())
400 return state;
401 Idx = Offset.castAs<NonLoc>();
402 }
403
404 // Get the size of the array.
405 const auto *superReg = cast<SubRegion>(ER->getSuperRegion());
406 DefinedOrUnknownSVal Size =
407 getDynamicExtent(state, superReg, C.getSValBuilder());
408
409 ProgramStateRef StInBound, StOutBound;
410 std::tie(StInBound, StOutBound) = state->assumeInBoundDual(Idx, Size);
411 if (StOutBound && !StInBound) {
412 // These checks are either enabled by the CString out-of-bounds checker
413 // explicitly or implicitly by the Malloc checker.
414 // In the latter case we only do modeling but do not emit warning.
415 if (!Filter.CheckCStringOutOfBounds)
416 return nullptr;
417
418 // Emit a bug report.
419 ErrorMessage Message =
420 createOutOfBoundErrorMsg(CurrentFunctionDescription, Access);
421 emitOutOfBoundsBug(C, StOutBound, Buffer.Expression, Message);
422 return nullptr;
423 }
424
425 // Ensure that we wouldn't read uninitialized value.
426 if (Access == AccessKind::read) {
427 if (Filter.CheckCStringUninitializedRead &&
428 StInBound->getSVal(ER).isUndef()) {
429 emitUninitializedReadBug(C, StInBound, Buffer.Expression);
430 return nullptr;
431 }
432 }
433
434 // Array bound check succeeded. From this point forward the array bound
435 // should always succeed.
436 return StInBound;
437}
438
439ProgramStateRef
440CStringChecker::CheckBufferAccess(CheckerContext &C, ProgramStateRef State,
441 AnyArgExpr Buffer, SizeArgExpr Size,
442 AccessKind Access, CharKind CK) const {
443 // If a previous check has failed, propagate the failure.
444 if (!State)
445 return nullptr;
446
447 SValBuilder &svalBuilder = C.getSValBuilder();
448 ASTContext &Ctx = svalBuilder.getContext();
449
450 QualType SizeTy = Size.Expression->getType();
451 QualType PtrTy = getCharPtrType(Ctx, CK);
452
453 // Check that the first buffer is non-null.
454 SVal BufVal = C.getSVal(Buffer.Expression);
455 State = checkNonNull(C, State, Buffer, BufVal);
456 if (!State)
457 return nullptr;
458
459 // If out-of-bounds checking is turned off, skip the rest.
460 if (!Filter.CheckCStringOutOfBounds)
461 return State;
462
463 // Get the access length and make sure it is known.
464 // FIXME: This assumes the caller has already checked that the access length
465 // is positive. And that it's unsigned.
466 SVal LengthVal = C.getSVal(Size.Expression);
467 Optional<NonLoc> Length = LengthVal.getAs<NonLoc>();
468 if (!Length)
469 return State;
470
471 // Compute the offset of the last element to be accessed: size-1.
472 NonLoc One = svalBuilder.makeIntVal(1, SizeTy).castAs<NonLoc>();
473 SVal Offset = svalBuilder.evalBinOpNN(State, BO_Sub, *Length, One, SizeTy);
474 if (Offset.isUnknown())
475 return nullptr;
476 NonLoc LastOffset = Offset.castAs<NonLoc>();
477
478 // Check that the first buffer is sufficiently long.
479 SVal BufStart =
480 svalBuilder.evalCast(BufVal, PtrTy, Buffer.Expression->getType());
481 if (Optional<Loc> BufLoc = BufStart.getAs<Loc>()) {
482
483 SVal BufEnd =
484 svalBuilder.evalBinOpLN(State, BO_Add, *BufLoc, LastOffset, PtrTy);
485 State = CheckLocation(C, State, Buffer, BufEnd, Access, CK);
486
487 // If the buffer isn't large enough, abort.
488 if (!State)
489 return nullptr;
490 }
491
492 // Large enough or not, return this state!
493 return State;
494}
495
496ProgramStateRef CStringChecker::CheckOverlap(CheckerContext &C,
497 ProgramStateRef state,
498 SizeArgExpr Size, AnyArgExpr First,
499 AnyArgExpr Second,
500 CharKind CK) const {
501 if (!Filter.CheckCStringBufferOverlap)
502 return state;
503
504 // Do a simple check for overlap: if the two arguments are from the same
505 // buffer, see if the end of the first is greater than the start of the second
506 // or vice versa.
507
508 // If a previous check has failed, propagate the failure.
509 if (!state)
510 return nullptr;
511
512 ProgramStateRef stateTrue, stateFalse;
513
514 // Assume different address spaces cannot overlap.
515 if (First.Expression->getType()->getPointeeType().getAddressSpace() !=
516 Second.Expression->getType()->getPointeeType().getAddressSpace())
517 return state;
518
519 // Get the buffer values and make sure they're known locations.
520 const LocationContext *LCtx = C.getLocationContext();
521 SVal firstVal = state->getSVal(First.Expression, LCtx);
522 SVal secondVal = state->getSVal(Second.Expression, LCtx);
523
524 Optional<Loc> firstLoc = firstVal.getAs<Loc>();
525 if (!firstLoc)
526 return state;
527
528 Optional<Loc> secondLoc = secondVal.getAs<Loc>();
529 if (!secondLoc)
530 return state;
531
532 // Are the two values the same?
533 SValBuilder &svalBuilder = C.getSValBuilder();
534 std::tie(stateTrue, stateFalse) =
535 state->assume(svalBuilder.evalEQ(state, *firstLoc, *secondLoc));
536
537 if (stateTrue && !stateFalse) {
538 // If the values are known to be equal, that's automatically an overlap.
539 emitOverlapBug(C, stateTrue, First.Expression, Second.Expression);
540 return nullptr;
541 }
542
543 // assume the two expressions are not equal.
544 assert(stateFalse)(static_cast <bool> (stateFalse) ? void (0) : __assert_fail
("stateFalse", "clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp"
, 544, __extension__ __PRETTY_FUNCTION__))
;
545 state = stateFalse;
546
547 // Which value comes first?
548 QualType cmpTy = svalBuilder.getConditionType();
549 SVal reverse =
550 svalBuilder.evalBinOpLL(state, BO_GT, *firstLoc, *secondLoc, cmpTy);
551 Optional<DefinedOrUnknownSVal> reverseTest =
552 reverse.getAs<DefinedOrUnknownSVal>();
553 if (!reverseTest)
554 return state;
555
556 std::tie(stateTrue, stateFalse) = state->assume(*reverseTest);
557 if (stateTrue) {
558 if (stateFalse) {
559 // If we don't know which one comes first, we can't perform this test.
560 return state;
561 } else {
562 // Switch the values so that firstVal is before secondVal.
563 std::swap(firstLoc, secondLoc);
564
565 // Switch the Exprs as well, so that they still correspond.
566 std::swap(First, Second);
567 }
568 }
569
570 // Get the length, and make sure it too is known.
571 SVal LengthVal = state->getSVal(Size.Expression, LCtx);
572 Optional<NonLoc> Length = LengthVal.getAs<NonLoc>();
573 if (!Length)
574 return state;
575
576 // Convert the first buffer's start address to char*.
577 // Bail out if the cast fails.
578 ASTContext &Ctx = svalBuilder.getContext();
579 QualType CharPtrTy = getCharPtrType(Ctx, CK);
580 SVal FirstStart =
581 svalBuilder.evalCast(*firstLoc, CharPtrTy, First.Expression->getType());
582 Optional<Loc> FirstStartLoc = FirstStart.getAs<Loc>();
583 if (!FirstStartLoc)
584 return state;
585
586 // Compute the end of the first buffer. Bail out if THAT fails.
587 SVal FirstEnd = svalBuilder.evalBinOpLN(state, BO_Add, *FirstStartLoc,
588 *Length, CharPtrTy);
589 Optional<Loc> FirstEndLoc = FirstEnd.getAs<Loc>();
590 if (!FirstEndLoc)
591 return state;
592
593 // Is the end of the first buffer past the start of the second buffer?
594 SVal Overlap =
595 svalBuilder.evalBinOpLL(state, BO_GT, *FirstEndLoc, *secondLoc, cmpTy);
596 Optional<DefinedOrUnknownSVal> OverlapTest =
597 Overlap.getAs<DefinedOrUnknownSVal>();
598 if (!OverlapTest)
599 return state;
600
601 std::tie(stateTrue, stateFalse) = state->assume(*OverlapTest);
602
603 if (stateTrue && !stateFalse) {
604 // Overlap!
605 emitOverlapBug(C, stateTrue, First.Expression, Second.Expression);
606 return nullptr;
607 }
608
609 // assume the two expressions don't overlap.
610 assert(stateFalse)(static_cast <bool> (stateFalse) ? void (0) : __assert_fail
("stateFalse", "clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp"
, 610, __extension__ __PRETTY_FUNCTION__))
;
611 return stateFalse;
612}
613
614void CStringChecker::emitOverlapBug(CheckerContext &C, ProgramStateRef state,
615 const Stmt *First, const Stmt *Second) const {
616 ExplodedNode *N = C.generateErrorNode(state);
617 if (!N)
618 return;
619
620 if (!BT_Overlap)
621 BT_Overlap.reset(new BugType(Filter.CheckNameCStringBufferOverlap,
622 categories::UnixAPI, "Improper arguments"));
623
624 // Generate a report for this bug.
625 auto report = std::make_unique<PathSensitiveBugReport>(
626 *BT_Overlap, "Arguments must not be overlapping buffers", N);
627 report->addRange(First->getSourceRange());
628 report->addRange(Second->getSourceRange());
629
630 C.emitReport(std::move(report));
631}
632
633void CStringChecker::emitNullArgBug(CheckerContext &C, ProgramStateRef State,
634 const Stmt *S, StringRef WarningMsg) const {
635 if (ExplodedNode *N = C.generateErrorNode(State)) {
636 if (!BT_Null)
637 BT_Null.reset(new BuiltinBug(
638 Filter.CheckNameCStringNullArg, categories::UnixAPI,
639 "Null pointer argument in call to byte string function"));
640
641 BuiltinBug *BT = static_cast<BuiltinBug *>(BT_Null.get());
642 auto Report = std::make_unique<PathSensitiveBugReport>(*BT, WarningMsg, N);
643 Report->addRange(S->getSourceRange());
644 if (const auto *Ex = dyn_cast<Expr>(S))
645 bugreporter::trackExpressionValue(N, Ex, *Report);
646 C.emitReport(std::move(Report));
647 }
648}
649
650void CStringChecker::emitUninitializedReadBug(CheckerContext &C,
651 ProgramStateRef State,
652 const Expr *E) const {
653 if (ExplodedNode *N = C.generateErrorNode(State)) {
654 const char *Msg =
655 "Bytes string function accesses uninitialized/garbage values";
656 if (!BT_UninitRead)
657 BT_UninitRead.reset(
658 new BuiltinBug(Filter.CheckNameCStringUninitializedRead,
659 "Accessing unitialized/garbage values", Msg));
660
661 BuiltinBug *BT = static_cast<BuiltinBug *>(BT_UninitRead.get());
662
663 auto Report = std::make_unique<PathSensitiveBugReport>(*BT, Msg, N);
664 Report->addRange(E->getSourceRange());
665 bugreporter::trackExpressionValue(N, E, *Report);
666 C.emitReport(std::move(Report));
667 }
668}
669
670void CStringChecker::emitOutOfBoundsBug(CheckerContext &C,
671 ProgramStateRef State, const Stmt *S,
672 StringRef WarningMsg) const {
673 if (ExplodedNode *N = C.generateErrorNode(State)) {
674 if (!BT_Bounds)
675 BT_Bounds.reset(new BuiltinBug(
676 Filter.CheckCStringOutOfBounds ? Filter.CheckNameCStringOutOfBounds
677 : Filter.CheckNameCStringNullArg,
678 "Out-of-bound array access",
679 "Byte string function accesses out-of-bound array element"));
680
681 BuiltinBug *BT = static_cast<BuiltinBug *>(BT_Bounds.get());
682
683 // FIXME: It would be nice to eventually make this diagnostic more clear,
684 // e.g., by referencing the original declaration or by saying *why* this
685 // reference is outside the range.
686 auto Report = std::make_unique<PathSensitiveBugReport>(*BT, WarningMsg, N);
687 Report->addRange(S->getSourceRange());
688 C.emitReport(std::move(Report));
689 }
690}
691
692void CStringChecker::emitNotCStringBug(CheckerContext &C, ProgramStateRef State,
693 const Stmt *S,
694 StringRef WarningMsg) const {
695 if (ExplodedNode *N = C.generateNonFatalErrorNode(State)) {
696 if (!BT_NotCString)
697 BT_NotCString.reset(new BuiltinBug(
698 Filter.CheckNameCStringNotNullTerm, categories::UnixAPI,
699 "Argument is not a null-terminated string."));
700
701 auto Report =
702 std::make_unique<PathSensitiveBugReport>(*BT_NotCString, WarningMsg, N);
703
704 Report->addRange(S->getSourceRange());
705 C.emitReport(std::move(Report));
706 }
707}
708
709void CStringChecker::emitAdditionOverflowBug(CheckerContext &C,
710 ProgramStateRef State) const {
711 if (ExplodedNode *N = C.generateErrorNode(State)) {
712 if (!BT_AdditionOverflow)
713 BT_AdditionOverflow.reset(
714 new BuiltinBug(Filter.CheckNameCStringOutOfBounds, "API",
715 "Sum of expressions causes overflow."));
716
717 // This isn't a great error message, but this should never occur in real
718 // code anyway -- you'd have to create a buffer longer than a size_t can
719 // represent, which is sort of a contradiction.
720 const char *WarningMsg =
721 "This expression will create a string whose length is too big to "
722 "be represented as a size_t";
723
724 auto Report = std::make_unique<PathSensitiveBugReport>(*BT_AdditionOverflow,
725 WarningMsg, N);
726 C.emitReport(std::move(Report));
727 }
728}
729
730ProgramStateRef CStringChecker::checkAdditionOverflow(CheckerContext &C,
731 ProgramStateRef state,
732 NonLoc left,
733 NonLoc right) const {
734 // If out-of-bounds checking is turned off, skip the rest.
735 if (!Filter.CheckCStringOutOfBounds)
736 return state;
737
738 // If a previous check has failed, propagate the failure.
739 if (!state)
740 return nullptr;
741
742 SValBuilder &svalBuilder = C.getSValBuilder();
743 BasicValueFactory &BVF = svalBuilder.getBasicValueFactory();
744
745 QualType sizeTy = svalBuilder.getContext().getSizeType();
746 const llvm::APSInt &maxValInt = BVF.getMaxValue(sizeTy);
747 NonLoc maxVal = svalBuilder.makeIntVal(maxValInt);
748
749 SVal maxMinusRight;
750 if (isa<nonloc::ConcreteInt>(right)) {
751 maxMinusRight = svalBuilder.evalBinOpNN(state, BO_Sub, maxVal, right,
752 sizeTy);
753 } else {
754 // Try switching the operands. (The order of these two assignments is
755 // important!)
756 maxMinusRight = svalBuilder.evalBinOpNN(state, BO_Sub, maxVal, left,
757 sizeTy);
758 left = right;
759 }
760
761 if (Optional<NonLoc> maxMinusRightNL = maxMinusRight.getAs<NonLoc>()) {
762 QualType cmpTy = svalBuilder.getConditionType();
763 // If left > max - right, we have an overflow.
764 SVal willOverflow = svalBuilder.evalBinOpNN(state, BO_GT, left,
765 *maxMinusRightNL, cmpTy);
766
767 ProgramStateRef stateOverflow, stateOkay;
768 std::tie(stateOverflow, stateOkay) =
769 state->assume(willOverflow.castAs<DefinedOrUnknownSVal>());
770
771 if (stateOverflow && !stateOkay) {
772 // We have an overflow. Emit a bug report.
773 emitAdditionOverflowBug(C, stateOverflow);
774 return nullptr;
775 }
776
777 // From now on, assume an overflow didn't occur.
778 assert(stateOkay)(static_cast <bool> (stateOkay) ? void (0) : __assert_fail
("stateOkay", "clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp"
, 778, __extension__ __PRETTY_FUNCTION__))
;
779 state = stateOkay;
780 }
781
782 return state;
783}
784
785ProgramStateRef CStringChecker::setCStringLength(ProgramStateRef state,
786 const MemRegion *MR,
787 SVal strLength) {
788 assert(!strLength.isUndef() && "Attempt to set an undefined string length")(static_cast <bool> (!strLength.isUndef() && "Attempt to set an undefined string length"
) ? void (0) : __assert_fail ("!strLength.isUndef() && \"Attempt to set an undefined string length\""
, "clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp", 788
, __extension__ __PRETTY_FUNCTION__))
;
789
790 MR = MR->StripCasts();
791
792 switch (MR->getKind()) {
793 case MemRegion::StringRegionKind:
794 // FIXME: This can happen if we strcpy() into a string region. This is
795 // undefined [C99 6.4.5p6], but we should still warn about it.
796 return state;
797
798 case MemRegion::SymbolicRegionKind:
799 case MemRegion::AllocaRegionKind:
800 case MemRegion::NonParamVarRegionKind:
801 case MemRegion::ParamVarRegionKind:
802 case MemRegion::FieldRegionKind:
803 case MemRegion::ObjCIvarRegionKind:
804 // These are the types we can currently track string lengths for.
805 break;
806
807 case MemRegion::ElementRegionKind:
808 // FIXME: Handle element regions by upper-bounding the parent region's
809 // string length.
810 return state;
811
812 default:
813 // Other regions (mostly non-data) can't have a reliable C string length.
814 // For now, just ignore the change.
815 // FIXME: These are rare but not impossible. We should output some kind of
816 // warning for things like strcpy((char[]){'a', 0}, "b");
817 return state;
818 }
819
820 if (strLength.isUnknown())
821 return state->remove<CStringLength>(MR);
822
823 return state->set<CStringLength>(MR, strLength);
824}
825
826SVal CStringChecker::getCStringLengthForRegion(CheckerContext &C,
827 ProgramStateRef &state,
828 const Expr *Ex,
829 const MemRegion *MR,
830 bool hypothetical) {
831 if (!hypothetical) {
832 // If there's a recorded length, go ahead and return it.
833 const SVal *Recorded = state->get<CStringLength>(MR);
834 if (Recorded)
835 return *Recorded;
836 }
837
838 // Otherwise, get a new symbol and update the state.
839 SValBuilder &svalBuilder = C.getSValBuilder();
840 QualType sizeTy = svalBuilder.getContext().getSizeType();
841 SVal strLength = svalBuilder.getMetadataSymbolVal(CStringChecker::getTag(),
842 MR, Ex, sizeTy,
843 C.getLocationContext(),
844 C.blockCount());
845
846 if (!hypothetical) {
847 if (Optional<NonLoc> strLn = strLength.getAs<NonLoc>()) {
848 // In case of unbounded calls strlen etc bound the range to SIZE_MAX/4
849 BasicValueFactory &BVF = svalBuilder.getBasicValueFactory();
850 const llvm::APSInt &maxValInt = BVF.getMaxValue(sizeTy);
851 llvm::APSInt fourInt = APSIntType(maxValInt).getValue(4);
852 const llvm::APSInt *maxLengthInt = BVF.evalAPSInt(BO_Div, maxValInt,
853 fourInt);
854 NonLoc maxLength = svalBuilder.makeIntVal(*maxLengthInt);
855 SVal evalLength = svalBuilder.evalBinOpNN(state, BO_LE, *strLn,
856 maxLength, sizeTy);
857 state = state->assume(evalLength.castAs<DefinedOrUnknownSVal>(), true);
858 }
859 state = state->set<CStringLength>(MR, strLength);
860 }
861
862 return strLength;
863}
864
865SVal CStringChecker::getCStringLength(CheckerContext &C, ProgramStateRef &state,
866 const Expr *Ex, SVal Buf,
867 bool hypothetical) const {
868 const MemRegion *MR = Buf.getAsRegion();
869 if (!MR) {
870 // If we can't get a region, see if it's something we /know/ isn't a
871 // C string. In the context of locations, the only time we can issue such
872 // a warning is for labels.
873 if (Optional<loc::GotoLabel> Label = Buf.getAs<loc::GotoLabel>()) {
874 if (Filter.CheckCStringNotNullTerm) {
875 SmallString<120> buf;
876 llvm::raw_svector_ostream os(buf);
877 assert(CurrentFunctionDescription)(static_cast <bool> (CurrentFunctionDescription) ? void
(0) : __assert_fail ("CurrentFunctionDescription", "clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp"
, 877, __extension__ __PRETTY_FUNCTION__))
;
878 os << "Argument to " << CurrentFunctionDescription
879 << " is the address of the label '" << Label->getLabel()->getName()
880 << "', which is not a null-terminated string";
881
882 emitNotCStringBug(C, state, Ex, os.str());
883 }
884 return UndefinedVal();
885 }
886
887 // If it's not a region and not a label, give up.
888 return UnknownVal();
889 }
890
891 // If we have a region, strip casts from it and see if we can figure out
892 // its length. For anything we can't figure out, just return UnknownVal.
893 MR = MR->StripCasts();
894
895 switch (MR->getKind()) {
896 case MemRegion::StringRegionKind: {
897 // Modifying the contents of string regions is undefined [C99 6.4.5p6],
898 // so we can assume that the byte length is the correct C string length.
899 SValBuilder &svalBuilder = C.getSValBuilder();
900 QualType sizeTy = svalBuilder.getContext().getSizeType();
901 const StringLiteral *strLit = cast<StringRegion>(MR)->getStringLiteral();
902 return svalBuilder.makeIntVal(strLit->getLength(), sizeTy);
903 }
904 case MemRegion::SymbolicRegionKind:
905 case MemRegion::AllocaRegionKind:
906 case MemRegion::NonParamVarRegionKind:
907 case MemRegion::ParamVarRegionKind:
908 case MemRegion::FieldRegionKind:
909 case MemRegion::ObjCIvarRegionKind:
910 return getCStringLengthForRegion(C, state, Ex, MR, hypothetical);
911 case MemRegion::CompoundLiteralRegionKind:
912 // FIXME: Can we track this? Is it necessary?
913 return UnknownVal();
914 case MemRegion::ElementRegionKind:
915 // FIXME: How can we handle this? It's not good enough to subtract the
916 // offset from the base string length; consider "123\x00567" and &a[5].
917 return UnknownVal();
918 default:
919 // Other regions (mostly non-data) can't have a reliable C string length.
920 // In this case, an error is emitted and UndefinedVal is returned.
921 // The caller should always be prepared to handle this case.
922 if (Filter.CheckCStringNotNullTerm) {
923 SmallString<120> buf;
924 llvm::raw_svector_ostream os(buf);
925
926 assert(CurrentFunctionDescription)(static_cast <bool> (CurrentFunctionDescription) ? void
(0) : __assert_fail ("CurrentFunctionDescription", "clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp"
, 926, __extension__ __PRETTY_FUNCTION__))
;
927 os << "Argument to " << CurrentFunctionDescription << " is ";
928
929 if (SummarizeRegion(os, C.getASTContext(), MR))
930 os << ", which is not a null-terminated string";
931 else
932 os << "not a null-terminated string";
933
934 emitNotCStringBug(C, state, Ex, os.str());
935 }
936 return UndefinedVal();
937 }
938}
939
940const StringLiteral *CStringChecker::getCStringLiteral(CheckerContext &C,
941 ProgramStateRef &state, const Expr *expr, SVal val) const {
942
943 // Get the memory region pointed to by the val.
944 const MemRegion *bufRegion = val.getAsRegion();
945 if (!bufRegion)
946 return nullptr;
947
948 // Strip casts off the memory region.
949 bufRegion = bufRegion->StripCasts();
950
951 // Cast the memory region to a string region.
952 const StringRegion *strRegion= dyn_cast<StringRegion>(bufRegion);
953 if (!strRegion)
954 return nullptr;
955
956 // Return the actual string in the string region.
957 return strRegion->getStringLiteral();
958}
959
960bool CStringChecker::IsFirstBufInBound(CheckerContext &C,
961 ProgramStateRef state,
962 const Expr *FirstBuf,
963 const Expr *Size) {
964 // If we do not know that the buffer is long enough we return 'true'.
965 // Otherwise the parent region of this field region would also get
966 // invalidated, which would lead to warnings based on an unknown state.
967
968 // Originally copied from CheckBufferAccess and CheckLocation.
969 SValBuilder &svalBuilder = C.getSValBuilder();
970 ASTContext &Ctx = svalBuilder.getContext();
971 const LocationContext *LCtx = C.getLocationContext();
972
973 QualType sizeTy = Size->getType();
974 QualType PtrTy = Ctx.getPointerType(Ctx.CharTy);
975 SVal BufVal = state->getSVal(FirstBuf, LCtx);
976
977 SVal LengthVal = state->getSVal(Size, LCtx);
978 Optional<NonLoc> Length = LengthVal.getAs<NonLoc>();
979 if (!Length)
980 return true; // cf top comment.
981
982 // Compute the offset of the last element to be accessed: size-1.
983 NonLoc One = svalBuilder.makeIntVal(1, sizeTy).castAs<NonLoc>();
984 SVal Offset = svalBuilder.evalBinOpNN(state, BO_Sub, *Length, One, sizeTy);
985 if (Offset.isUnknown())
986 return true; // cf top comment
987 NonLoc LastOffset = Offset.castAs<NonLoc>();
988
989 // Check that the first buffer is sufficiently long.
990 SVal BufStart = svalBuilder.evalCast(BufVal, PtrTy, FirstBuf->getType());
991 Optional<Loc> BufLoc = BufStart.getAs<Loc>();
992 if (!BufLoc)
993 return true; // cf top comment.
994
995 SVal BufEnd =
996 svalBuilder.evalBinOpLN(state, BO_Add, *BufLoc, LastOffset, PtrTy);
997
998 // Check for out of bound array element access.
999 const MemRegion *R = BufEnd.getAsRegion();
1000 if (!R)
1001 return true; // cf top comment.
1002
1003 const ElementRegion *ER = dyn_cast<ElementRegion>(R);
1004 if (!ER)
1005 return true; // cf top comment.
1006
1007 // FIXME: Does this crash when a non-standard definition
1008 // of a library function is encountered?
1009 assert(ER->getValueType() == C.getASTContext().CharTy &&(static_cast <bool> (ER->getValueType() == C.getASTContext
().CharTy && "IsFirstBufInBound should only be called with char* ElementRegions"
) ? void (0) : __assert_fail ("ER->getValueType() == C.getASTContext().CharTy && \"IsFirstBufInBound should only be called with char* ElementRegions\""
, "clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp", 1010
, __extension__ __PRETTY_FUNCTION__))
1010 "IsFirstBufInBound should only be called with char* ElementRegions")(static_cast <bool> (ER->getValueType() == C.getASTContext
().CharTy && "IsFirstBufInBound should only be called with char* ElementRegions"
) ? void (0) : __assert_fail ("ER->getValueType() == C.getASTContext().CharTy && \"IsFirstBufInBound should only be called with char* ElementRegions\""
, "clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp", 1010
, __extension__ __PRETTY_FUNCTION__))
;
1011
1012 // Get the size of the array.
1013 const SubRegion *superReg = cast<SubRegion>(ER->getSuperRegion());
1014 DefinedOrUnknownSVal SizeDV = getDynamicExtent(state, superReg, svalBuilder);
1015
1016 // Get the index of the accessed element.
1017 DefinedOrUnknownSVal Idx = ER->getIndex().castAs<DefinedOrUnknownSVal>();
1018
1019 ProgramStateRef StInBound = state->assumeInBound(Idx, SizeDV, true);
1020
1021 return static_cast<bool>(StInBound);
1022}
1023
1024ProgramStateRef CStringChecker::InvalidateBuffer(CheckerContext &C,
1025 ProgramStateRef state,
1026 const Expr *E, SVal V,
1027 bool IsSourceBuffer,
1028 const Expr *Size) {
1029 Optional<Loc> L = V.getAs<Loc>();
1030 if (!L)
1031 return state;
1032
1033 // FIXME: This is a simplified version of what's in CFRefCount.cpp -- it makes
1034 // some assumptions about the value that CFRefCount can't. Even so, it should
1035 // probably be refactored.
1036 if (Optional<loc::MemRegionVal> MR = L->getAs<loc::MemRegionVal>()) {
1037 const MemRegion *R = MR->getRegion()->StripCasts();
1038
1039 // Are we dealing with an ElementRegion? If so, we should be invalidating
1040 // the super-region.
1041 if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
1042 R = ER->getSuperRegion();
1043 // FIXME: What about layers of ElementRegions?
1044 }
1045
1046 // Invalidate this region.
1047 const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
1048
1049 bool CausesPointerEscape = false;
1050 RegionAndSymbolInvalidationTraits ITraits;
1051 // Invalidate and escape only indirect regions accessible through the source
1052 // buffer.
1053 if (IsSourceBuffer) {
1054 ITraits.setTrait(R->getBaseRegion(),
1055 RegionAndSymbolInvalidationTraits::TK_PreserveContents);
1056 ITraits.setTrait(R, RegionAndSymbolInvalidationTraits::TK_SuppressEscape);
1057 CausesPointerEscape = true;
1058 } else {
1059 const MemRegion::Kind& K = R->getKind();
1060 if (K == MemRegion::FieldRegionKind)
1061 if (Size && IsFirstBufInBound(C, state, E, Size)) {
1062 // If destination buffer is a field region and access is in bound,
1063 // do not invalidate its super region.
1064 ITraits.setTrait(
1065 R,
1066 RegionAndSymbolInvalidationTraits::TK_DoNotInvalidateSuperRegion);
1067 }
1068 }
1069
1070 return state->invalidateRegions(R, E, C.blockCount(), LCtx,
1071 CausesPointerEscape, nullptr, nullptr,
1072 &ITraits);
1073 }
1074
1075 // If we have a non-region value by chance, just remove the binding.
1076 // FIXME: is this necessary or correct? This handles the non-Region
1077 // cases. Is it ever valid to store to these?
1078 return state->killBinding(*L);
1079}
1080
1081bool CStringChecker::SummarizeRegion(raw_ostream &os, ASTContext &Ctx,
1082 const MemRegion *MR) {
1083 switch (MR->getKind()) {
1084 case MemRegion::FunctionCodeRegionKind: {
1085 if (const auto *FD = cast<FunctionCodeRegion>(MR)->getDecl())
1086 os << "the address of the function '" << *FD << '\'';
1087 else
1088 os << "the address of a function";
1089 return true;
1090 }
1091 case MemRegion::BlockCodeRegionKind:
1092 os << "block text";
1093 return true;
1094 case MemRegion::BlockDataRegionKind:
1095 os << "a block";
1096 return true;
1097 case MemRegion::CXXThisRegionKind:
1098 case MemRegion::CXXTempObjectRegionKind:
1099 os << "a C++ temp object of type "
1100 << cast<TypedValueRegion>(MR)->getValueType();
1101 return true;
1102 case MemRegion::NonParamVarRegionKind:
1103 os << "a variable of type" << cast<TypedValueRegion>(MR)->getValueType();
1104 return true;
1105 case MemRegion::ParamVarRegionKind:
1106 os << "a parameter of type" << cast<TypedValueRegion>(MR)->getValueType();
1107 return true;
1108 case MemRegion::FieldRegionKind:
1109 os << "a field of type " << cast<TypedValueRegion>(MR)->getValueType();
1110 return true;
1111 case MemRegion::ObjCIvarRegionKind:
1112 os << "an instance variable of type "
1113 << cast<TypedValueRegion>(MR)->getValueType();
1114 return true;
1115 default:
1116 return false;
1117 }
1118}
1119
1120bool CStringChecker::memsetAux(const Expr *DstBuffer, SVal CharVal,
1121 const Expr *Size, CheckerContext &C,
1122 ProgramStateRef &State) {
1123 SVal MemVal = C.getSVal(DstBuffer);
1124 SVal SizeVal = C.getSVal(Size);
1125 const MemRegion *MR = MemVal.getAsRegion();
1126 if (!MR)
1127 return false;
1128
1129 // We're about to model memset by producing a "default binding" in the Store.
1130 // Our current implementation - RegionStore - doesn't support default bindings
1131 // that don't cover the whole base region. So we should first get the offset
1132 // and the base region to figure out whether the offset of buffer is 0.
1133 RegionOffset Offset = MR->getAsOffset();
1134 const MemRegion *BR = Offset.getRegion();
1135
1136 Optional<NonLoc> SizeNL = SizeVal.getAs<NonLoc>();
1137 if (!SizeNL)
1138 return false;
1139
1140 SValBuilder &svalBuilder = C.getSValBuilder();
1141 ASTContext &Ctx = C.getASTContext();
1142
1143 // void *memset(void *dest, int ch, size_t count);
1144 // For now we can only handle the case of offset is 0 and concrete char value.
1145 if (Offset.isValid() && !Offset.hasSymbolicOffset() &&
1146 Offset.getOffset() == 0) {
1147 // Get the base region's size.
1148 DefinedOrUnknownSVal SizeDV = getDynamicExtent(State, BR, svalBuilder);
1149
1150 ProgramStateRef StateWholeReg, StateNotWholeReg;
1151 std::tie(StateWholeReg, StateNotWholeReg) =
1152 State->assume(svalBuilder.evalEQ(State, SizeDV, *SizeNL));
1153
1154 // With the semantic of 'memset()', we should convert the CharVal to
1155 // unsigned char.
1156 CharVal = svalBuilder.evalCast(CharVal, Ctx.UnsignedCharTy, Ctx.IntTy);
1157
1158 ProgramStateRef StateNullChar, StateNonNullChar;
1159 std::tie(StateNullChar, StateNonNullChar) =
1160 assumeZero(C, State, CharVal, Ctx.UnsignedCharTy);
1161
1162 if (StateWholeReg && !StateNotWholeReg && StateNullChar &&
1163 !StateNonNullChar) {
1164 // If the 'memset()' acts on the whole region of destination buffer and
1165 // the value of the second argument of 'memset()' is zero, bind the second
1166 // argument's value to the destination buffer with 'default binding'.
1167 // FIXME: Since there is no perfect way to bind the non-zero character, we
1168 // can only deal with zero value here. In the future, we need to deal with
1169 // the binding of non-zero value in the case of whole region.
1170 State = State->bindDefaultZero(svalBuilder.makeLoc(BR),
1171 C.getLocationContext());
1172 } else {
1173 // If the destination buffer's extent is not equal to the value of
1174 // third argument, just invalidate buffer.
1175 State = InvalidateBuffer(C, State, DstBuffer, MemVal,
1176 /*IsSourceBuffer*/ false, Size);
1177 }
1178
1179 if (StateNullChar && !StateNonNullChar) {
1180 // If the value of the second argument of 'memset()' is zero, set the
1181 // string length of destination buffer to 0 directly.
1182 State = setCStringLength(State, MR,
1183 svalBuilder.makeZeroVal(Ctx.getSizeType()));
1184 } else if (!StateNullChar && StateNonNullChar) {
1185 SVal NewStrLen = svalBuilder.getMetadataSymbolVal(
1186 CStringChecker::getTag(), MR, DstBuffer, Ctx.getSizeType(),
1187 C.getLocationContext(), C.blockCount());
1188
1189 // If the value of second argument is not zero, then the string length
1190 // is at least the size argument.
1191 SVal NewStrLenGESize = svalBuilder.evalBinOp(
1192 State, BO_GE, NewStrLen, SizeVal, svalBuilder.getConditionType());
1193
1194 State = setCStringLength(
1195 State->assume(NewStrLenGESize.castAs<DefinedOrUnknownSVal>(), true),
1196 MR, NewStrLen);
1197 }
1198 } else {
1199 // If the offset is not zero and char value is not concrete, we can do
1200 // nothing but invalidate the buffer.
1201 State = InvalidateBuffer(C, State, DstBuffer, MemVal,
1202 /*IsSourceBuffer*/ false, Size);
1203 }
1204 return true;
1205}
1206
1207//===----------------------------------------------------------------------===//
1208// evaluation of individual function calls.
1209//===----------------------------------------------------------------------===//
1210
1211void CStringChecker::evalCopyCommon(CheckerContext &C, const CallExpr *CE,
1212 ProgramStateRef state, SizeArgExpr Size,
1213 DestinationArgExpr Dest,
1214 SourceArgExpr Source, bool Restricted,
1215 bool IsMempcpy, CharKind CK) const {
1216 CurrentFunctionDescription = "memory copy function";
1217
1218 // See if the size argument is zero.
1219 const LocationContext *LCtx = C.getLocationContext();
1220 SVal sizeVal = state->getSVal(Size.Expression, LCtx);
1221 QualType sizeTy = Size.Expression->getType();
1222
1223 ProgramStateRef stateZeroSize, stateNonZeroSize;
1224 std::tie(stateZeroSize, stateNonZeroSize) =
1225 assumeZero(C, state, sizeVal, sizeTy);
1226
1227 // Get the value of the Dest.
1228 SVal destVal = state->getSVal(Dest.Expression, LCtx);
1229
1230 // If the size is zero, there won't be any actual memory access, so
1231 // just bind the return value to the destination buffer and return.
1232 if (stateZeroSize && !stateNonZeroSize) {
1233 stateZeroSize = stateZeroSize->BindExpr(CE, LCtx, destVal);
1234 C.addTransition(stateZeroSize);
1235 return;
1236 }
1237
1238 // If the size can be nonzero, we have to check the other arguments.
1239 if (stateNonZeroSize) {
1240 state = stateNonZeroSize;
1241
1242 // Ensure the destination is not null. If it is NULL there will be a
1243 // NULL pointer dereference.
1244 state = checkNonNull(C, state, Dest, destVal);
1245 if (!state)
1246 return;
1247
1248 // Get the value of the Src.
1249 SVal srcVal = state->getSVal(Source.Expression, LCtx);
1250
1251 // Ensure the source is not null. If it is NULL there will be a
1252 // NULL pointer dereference.
1253 state = checkNonNull(C, state, Source, srcVal);
1254 if (!state)
1255 return;
1256
1257 // Ensure the accesses are valid and that the buffers do not overlap.
1258 state = CheckBufferAccess(C, state, Dest, Size, AccessKind::write, CK);
1259 state = CheckBufferAccess(C, state, Source, Size, AccessKind::read, CK);
1260
1261 if (Restricted)
1262 state = CheckOverlap(C, state, Size, Dest, Source, CK);
1263
1264 if (!state)
1265 return;
1266
1267 // If this is mempcpy, get the byte after the last byte copied and
1268 // bind the expr.
1269 if (IsMempcpy) {
1270 // Get the byte after the last byte copied.
1271 SValBuilder &SvalBuilder = C.getSValBuilder();
1272 ASTContext &Ctx = SvalBuilder.getContext();
1273 QualType CharPtrTy = getCharPtrType(Ctx, CK);
1274 SVal DestRegCharVal =
1275 SvalBuilder.evalCast(destVal, CharPtrTy, Dest.Expression->getType());
1276 SVal lastElement = C.getSValBuilder().evalBinOp(
1277 state, BO_Add, DestRegCharVal, sizeVal, Dest.Expression->getType());
1278 // If we don't know how much we copied, we can at least
1279 // conjure a return value for later.
1280 if (lastElement.isUnknown())
1281 lastElement = C.getSValBuilder().conjureSymbolVal(nullptr, CE, LCtx,
1282 C.blockCount());
1283
1284 // The byte after the last byte copied is the return value.
1285 state = state->BindExpr(CE, LCtx, lastElement);
1286 } else {
1287 // All other copies return the destination buffer.
1288 // (Well, bcopy() has a void return type, but this won't hurt.)
1289 state = state->BindExpr(CE, LCtx, destVal);
1290 }
1291
1292 // Invalidate the destination (regular invalidation without pointer-escaping
1293 // the address of the top-level region).
1294 // FIXME: Even if we can't perfectly model the copy, we should see if we
1295 // can use LazyCompoundVals to copy the source values into the destination.
1296 // This would probably remove any existing bindings past the end of the
1297 // copied region, but that's still an improvement over blank invalidation.
1298 state =
1299 InvalidateBuffer(C, state, Dest.Expression, C.getSVal(Dest.Expression),
1300 /*IsSourceBuffer*/ false, Size.Expression);
1301
1302 // Invalidate the source (const-invalidation without const-pointer-escaping
1303 // the address of the top-level region).
1304 state = InvalidateBuffer(C, state, Source.Expression,
1305 C.getSVal(Source.Expression),
1306 /*IsSourceBuffer*/ true, nullptr);
1307
1308 C.addTransition(state);
1309 }
1310}
1311
1312void CStringChecker::evalMemcpy(CheckerContext &C, const CallExpr *CE,
1313 CharKind CK) const {
1314 // void *memcpy(void *restrict dst, const void *restrict src, size_t n);
1315 // The return value is the address of the destination buffer.
1316 DestinationArgExpr Dest = {CE->getArg(0), 0};
1317 SourceArgExpr Src = {CE->getArg(1), 1};
1318 SizeArgExpr Size = {CE->getArg(2), 2};
1319
1320 ProgramStateRef State = C.getState();
1321
1322 constexpr bool IsRestricted = true;
1323 constexpr bool IsMempcpy = false;
1324 evalCopyCommon(C, CE, State, Size, Dest, Src, IsRestricted, IsMempcpy, CK);
1325}
1326
1327void CStringChecker::evalMempcpy(CheckerContext &C, const CallExpr *CE,
1328 CharKind CK) const {
1329 // void *mempcpy(void *restrict dst, const void *restrict src, size_t n);
1330 // The return value is a pointer to the byte following the last written byte.
1331 DestinationArgExpr Dest = {CE->getArg(0), 0};
1332 SourceArgExpr Src = {CE->getArg(1), 1};
1333 SizeArgExpr Size = {CE->getArg(2), 2};
1334
1335 constexpr bool IsRestricted = true;
1336 constexpr bool IsMempcpy = true;
1337 evalCopyCommon(C, CE, C.getState(), Size, Dest, Src, IsRestricted, IsMempcpy,
1338 CK);
1339}
1340
1341void CStringChecker::evalMemmove(CheckerContext &C, const CallExpr *CE,
1342 CharKind CK) const {
1343 // void *memmove(void *dst, const void *src, size_t n);
1344 // The return value is the address of the destination buffer.
1345 DestinationArgExpr Dest = {CE->getArg(0), 0};
1346 SourceArgExpr Src = {CE->getArg(1), 1};
1347 SizeArgExpr Size = {CE->getArg(2), 2};
1348
1349 constexpr bool IsRestricted = false;
1350 constexpr bool IsMempcpy = false;
1351 evalCopyCommon(C, CE, C.getState(), Size, Dest, Src, IsRestricted, IsMempcpy,
1352 CK);
1353}
1354
1355void CStringChecker::evalBcopy(CheckerContext &C, const CallExpr *CE) const {
1356 // void bcopy(const void *src, void *dst, size_t n);
1357 SourceArgExpr Src(CE->getArg(0), 0);
1358 DestinationArgExpr Dest = {CE->getArg(1), 1};
1359 SizeArgExpr Size = {CE->getArg(2), 2};
1360
1361 constexpr bool IsRestricted = false;
1362 constexpr bool IsMempcpy = false;
1363 evalCopyCommon(C, CE, C.getState(), Size, Dest, Src, IsRestricted, IsMempcpy,
1364 CharKind::Regular);
1365}
1366
1367void CStringChecker::evalMemcmp(CheckerContext &C, const CallExpr *CE,
1368 CharKind CK) const {
1369 // int memcmp(const void *s1, const void *s2, size_t n);
1370 CurrentFunctionDescription = "memory comparison function";
1371
1372 AnyArgExpr Left = {CE->getArg(0), 0};
1373 AnyArgExpr Right = {CE->getArg(1), 1};
1374 SizeArgExpr Size = {CE->getArg(2), 2};
1375
1376 ProgramStateRef State = C.getState();
1377 SValBuilder &Builder = C.getSValBuilder();
1378 const LocationContext *LCtx = C.getLocationContext();
1379
1380 // See if the size argument is zero.
1381 SVal sizeVal = State->getSVal(Size.Expression, LCtx);
1382 QualType sizeTy = Size.Expression->getType();
1383
1384 ProgramStateRef stateZeroSize, stateNonZeroSize;
1385 std::tie(stateZeroSize, stateNonZeroSize) =
1386 assumeZero(C, State, sizeVal, sizeTy);
1387
1388 // If the size can be zero, the result will be 0 in that case, and we don't
1389 // have to check either of the buffers.
1390 if (stateZeroSize) {
1391 State = stateZeroSize;
1392 State = State->BindExpr(CE, LCtx, Builder.makeZeroVal(CE->getType()));
1393 C.addTransition(State);
1394 }
1395
1396 // If the size can be nonzero, we have to check the other arguments.
1397 if (stateNonZeroSize) {
1398 State = stateNonZeroSize;
1399 // If we know the two buffers are the same, we know the result is 0.
1400 // First, get the two buffers' addresses. Another checker will have already
1401 // made sure they're not undefined.
1402 DefinedOrUnknownSVal LV =
1403 State->getSVal(Left.Expression, LCtx).castAs<DefinedOrUnknownSVal>();
1404 DefinedOrUnknownSVal RV =
1405 State->getSVal(Right.Expression, LCtx).castAs<DefinedOrUnknownSVal>();
1406
1407 // See if they are the same.
1408 ProgramStateRef SameBuffer, NotSameBuffer;
1409 std::tie(SameBuffer, NotSameBuffer) =
1410 State->assume(Builder.evalEQ(State, LV, RV));
1411
1412 // If the two arguments are the same buffer, we know the result is 0,
1413 // and we only need to check one size.
1414 if (SameBuffer && !NotSameBuffer) {
1415 State = SameBuffer;
1416 State = CheckBufferAccess(C, State, Left, Size, AccessKind::read);
1417 if (State) {
1418 State =
1419 SameBuffer->BindExpr(CE, LCtx, Builder.makeZeroVal(CE->getType()));
1420 C.addTransition(State);
1421 }
1422 return;
1423 }
1424
1425 // If the two arguments might be different buffers, we have to check
1426 // the size of both of them.
1427 assert(NotSameBuffer)(static_cast <bool> (NotSameBuffer) ? void (0) : __assert_fail
("NotSameBuffer", "clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp"
, 1427, __extension__ __PRETTY_FUNCTION__))
;
1428 State = CheckBufferAccess(C, State, Right, Size, AccessKind::read, CK);
1429 State = CheckBufferAccess(C, State, Left, Size, AccessKind::read, CK);
1430 if (State) {
1431 // The return value is the comparison result, which we don't know.
1432 SVal CmpV = Builder.conjureSymbolVal(nullptr, CE, LCtx, C.blockCount());
1433 State = State->BindExpr(CE, LCtx, CmpV);
1434 C.addTransition(State);
1435 }
1436 }
1437}
1438
1439void CStringChecker::evalstrLength(CheckerContext &C,
1440 const CallExpr *CE) const {
1441 // size_t strlen(const char *s);
1442 evalstrLengthCommon(C, CE, /* IsStrnlen = */ false);
1443}
1444
1445void CStringChecker::evalstrnLength(CheckerContext &C,
1446 const CallExpr *CE) const {
1447 // size_t strnlen(const char *s, size_t maxlen);
1448 evalstrLengthCommon(C, CE, /* IsStrnlen = */ true);
1
Calling 'CStringChecker::evalstrLengthCommon'
1449}
1450
1451void CStringChecker::evalstrLengthCommon(CheckerContext &C, const CallExpr *CE,
1452 bool IsStrnlen) const {
1453 CurrentFunctionDescription = "string length function";
1454 ProgramStateRef state = C.getState();
1455 const LocationContext *LCtx = C.getLocationContext();
1456
1457 if (IsStrnlen
1.1
'IsStrnlen' is true
1.1
'IsStrnlen' is true
1.1
'IsStrnlen' is true
) {
2
Taking true branch
1458 const Expr *maxlenExpr = CE->getArg(1);
1459 SVal maxlenVal = state->getSVal(maxlenExpr, LCtx);
1460
1461 ProgramStateRef stateZeroSize, stateNonZeroSize;
1462 std::tie(stateZeroSize, stateNonZeroSize) =
1463 assumeZero(C, state, maxlenVal, maxlenExpr->getType());
1464
1465 // If the size can be zero, the result will be 0 in that case, and we don't
1466 // have to check the string itself.
1467 if (stateZeroSize) {
3
Assuming the condition is false
4
Taking false branch
1468 SVal zero = C.getSValBuilder().makeZeroVal(CE->getType());
1469 stateZeroSize = stateZeroSize->BindExpr(CE, LCtx, zero);
1470 C.addTransition(stateZeroSize);
1471 }
1472
1473 // If the size is GUARANTEED to be zero, we're done!
1474 if (!stateNonZeroSize)
5
Assuming the condition is false
6
Taking false branch
1475 return;
1476
1477 // Otherwise, record the assumption that the size is nonzero.
1478 state = stateNonZeroSize;
1479 }
1480
1481 // Check that the string argument is non-null.
1482 AnyArgExpr Arg = {CE->getArg(0), 0};
1483 SVal ArgVal = state->getSVal(Arg.Expression, LCtx);
1484 state = checkNonNull(C, state, Arg, ArgVal);
1485
1486 if (!state)
7
Assuming the condition is false
8
Taking false branch
1487 return;
1488
1489 SVal strLength = getCStringLength(C, state, Arg.Expression, ArgVal);
1490
1491 // If the argument isn't a valid C string, there's no valid state to
1492 // transition to.
1493 if (strLength.isUndef())
9
Taking false branch
1494 return;
1495
1496 DefinedOrUnknownSVal result = UnknownVal();
1497
1498 // If the check is for strnlen() then bind the return value to no more than
1499 // the maxlen value.
1500 if (IsStrnlen
9.1
'IsStrnlen' is true
9.1
'IsStrnlen' is true
9.1
'IsStrnlen' is true
) {
10
Taking true branch
1501 QualType cmpTy = C.getSValBuilder().getConditionType();
1502
1503 // It's a little unfortunate to be getting this again,
1504 // but it's not that expensive...
1505 const Expr *maxlenExpr = CE->getArg(1);
1506 SVal maxlenVal = state->getSVal(maxlenExpr, LCtx);
1507
1508 Optional<NonLoc> strLengthNL = strLength.getAs<NonLoc>();
1509 Optional<NonLoc> maxlenValNL = maxlenVal.getAs<NonLoc>();
1510
1511 if (strLengthNL && maxlenValNL) {
11
Assuming the condition is true
12
Assuming the condition is true
13
Taking true branch
1512 ProgramStateRef stateStringTooLong, stateStringNotTooLong;
1513
1514 // Check if the strLength is greater than the maxlen.
1515 std::tie(stateStringTooLong, stateStringNotTooLong) = state->assume(
1516 C.getSValBuilder()
1517 .evalBinOpNN(state, BO_GT, *strLengthNL, *maxlenValNL, cmpTy)
1518 .castAs<DefinedOrUnknownSVal>());
1519
1520 if (stateStringTooLong && !stateStringNotTooLong) {
14
Assuming the condition is false
1521 // If the string is longer than maxlen, return maxlen.
1522 result = *maxlenValNL;
1523 } else if (stateStringNotTooLong && !stateStringTooLong) {
15
Assuming the condition is false
1524 // If the string is shorter than maxlen, return its length.
1525 result = *strLengthNL;
1526 }
1527 }
1528
1529 if (result.isUnknown()) {
16
Taking true branch
1530 // If we don't have enough information for a comparison, there's
1531 // no guarantee the full string length will actually be returned.
1532 // All we know is the return value is the min of the string length
1533 // and the limit. This is better than nothing.
1534 result = C.getSValBuilder().conjureSymbolVal(nullptr, CE, LCtx,
1535 C.blockCount());
1536 NonLoc resultNL = result.castAs<NonLoc>();
1537
1538 if (strLengthNL) {
17
Taking true branch
1539 state = state->assume(C.getSValBuilder().evalBinOpNN(
18
Calling 'ProgramState::assume'
21
Returning from 'ProgramState::assume'
22
Calling copy assignment operator for 'IntrusiveRefCntPtr<const clang::ento::ProgramState>'
27
Returning from copy assignment operator for 'IntrusiveRefCntPtr<const clang::ento::ProgramState>'
1540 state, BO_LE, resultNL, *strLengthNL, cmpTy)
1541 .castAs<DefinedOrUnknownSVal>(), true);
1542 }
1543
1544 if (maxlenValNL) {
28
Taking true branch
1545 state = state->assume(C.getSValBuilder().evalBinOpNN(
29
Called C++ object pointer is null
1546 state, BO_LE, resultNL, *maxlenValNL, cmpTy)
1547 .castAs<DefinedOrUnknownSVal>(), true);
1548 }
1549 }
1550
1551 } else {
1552 // This is a plain strlen(), not strnlen().
1553 result = strLength.castAs<DefinedOrUnknownSVal>();
1554
1555 // If we don't know the length of the string, conjure a return
1556 // value, so it can be used in constraints, at least.
1557 if (result.isUnknown()) {
1558 result = C.getSValBuilder().conjureSymbolVal(nullptr, CE, LCtx,
1559 C.blockCount());
1560 }
1561 }
1562
1563 // Bind the return value.
1564 assert(!result.isUnknown() && "Should have conjured a value by now")(static_cast <bool> (!result.isUnknown() && "Should have conjured a value by now"
) ? void (0) : __assert_fail ("!result.isUnknown() && \"Should have conjured a value by now\""
, "clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp", 1564
, __extension__ __PRETTY_FUNCTION__))
;
1565 state = state->BindExpr(CE, LCtx, result);
1566 C.addTransition(state);
1567}
1568
1569void CStringChecker::evalStrcpy(CheckerContext &C, const CallExpr *CE) const {
1570 // char *strcpy(char *restrict dst, const char *restrict src);
1571 evalStrcpyCommon(C, CE,
1572 /* ReturnEnd = */ false,
1573 /* IsBounded = */ false,
1574 /* appendK = */ ConcatFnKind::none);
1575}
1576
1577void CStringChecker::evalStrncpy(CheckerContext &C, const CallExpr *CE) const {
1578 // char *strncpy(char *restrict dst, const char *restrict src, size_t n);
1579 evalStrcpyCommon(C, CE,
1580 /* ReturnEnd = */ false,
1581 /* IsBounded = */ true,
1582 /* appendK = */ ConcatFnKind::none);
1583}
1584
1585void CStringChecker::evalStpcpy(CheckerContext &C, const CallExpr *CE) const {
1586 // char *stpcpy(char *restrict dst, const char *restrict src);
1587 evalStrcpyCommon(C, CE,
1588 /* ReturnEnd = */ true,
1589 /* IsBounded = */ false,
1590 /* appendK = */ ConcatFnKind::none);
1591}
1592
1593void CStringChecker::evalStrlcpy(CheckerContext &C, const CallExpr *CE) const {
1594 // size_t strlcpy(char *dest, const char *src, size_t size);
1595 evalStrcpyCommon(C, CE,
1596 /* ReturnEnd = */ true,
1597 /* IsBounded = */ true,
1598 /* appendK = */ ConcatFnKind::none,
1599 /* returnPtr = */ false);
1600}
1601
1602void CStringChecker::evalStrcat(CheckerContext &C, const CallExpr *CE) const {
1603 // char *strcat(char *restrict s1, const char *restrict s2);
1604 evalStrcpyCommon(C, CE,
1605 /* ReturnEnd = */ false,
1606 /* IsBounded = */ false,
1607 /* appendK = */ ConcatFnKind::strcat);
1608}
1609
1610void CStringChecker::evalStrncat(CheckerContext &C, const CallExpr *CE) const {
1611 // char *strncat(char *restrict s1, const char *restrict s2, size_t n);
1612 evalStrcpyCommon(C, CE,
1613 /* ReturnEnd = */ false,
1614 /* IsBounded = */ true,
1615 /* appendK = */ ConcatFnKind::strcat);
1616}
1617
1618void CStringChecker::evalStrlcat(CheckerContext &C, const CallExpr *CE) const {
1619 // size_t strlcat(char *dst, const char *src, size_t size);
1620 // It will append at most size - strlen(dst) - 1 bytes,
1621 // NULL-terminating the result.
1622 evalStrcpyCommon(C, CE,
1623 /* ReturnEnd = */ false,
1624 /* IsBounded = */ true,
1625 /* appendK = */ ConcatFnKind::strlcat,
1626 /* returnPtr = */ false);
1627}
1628
1629void CStringChecker::evalStrcpyCommon(CheckerContext &C, const CallExpr *CE,
1630 bool ReturnEnd, bool IsBounded,
1631 ConcatFnKind appendK,
1632 bool returnPtr) const {
1633 if (appendK == ConcatFnKind::none)
1634 CurrentFunctionDescription = "string copy function";
1635 else
1636 CurrentFunctionDescription = "string concatenation function";
1637
1638 ProgramStateRef state = C.getState();
1639 const LocationContext *LCtx = C.getLocationContext();
1640
1641 // Check that the destination is non-null.
1642 DestinationArgExpr Dst = {CE->getArg(0), 0};
1643 SVal DstVal = state->getSVal(Dst.Expression, LCtx);
1644 state = checkNonNull(C, state, Dst, DstVal);
1645 if (!state)
1646 return;
1647
1648 // Check that the source is non-null.
1649 SourceArgExpr srcExpr = {CE->getArg(1), 1};
1650 SVal srcVal = state->getSVal(srcExpr.Expression, LCtx);
1651 state = checkNonNull(C, state, srcExpr, srcVal);
1652 if (!state)
1653 return;
1654
1655 // Get the string length of the source.
1656 SVal strLength = getCStringLength(C, state, srcExpr.Expression, srcVal);
1657 Optional<NonLoc> strLengthNL = strLength.getAs<NonLoc>();
1658
1659 // Get the string length of the destination buffer.
1660 SVal dstStrLength = getCStringLength(C, state, Dst.Expression, DstVal);
1661 Optional<NonLoc> dstStrLengthNL = dstStrLength.getAs<NonLoc>();
1662
1663 // If the source isn't a valid C string, give up.
1664 if (strLength.isUndef())
1665 return;
1666
1667 SValBuilder &svalBuilder = C.getSValBuilder();
1668 QualType cmpTy = svalBuilder.getConditionType();
1669 QualType sizeTy = svalBuilder.getContext().getSizeType();
1670
1671 // These two values allow checking two kinds of errors:
1672 // - actual overflows caused by a source that doesn't fit in the destination
1673 // - potential overflows caused by a bound that could exceed the destination
1674 SVal amountCopied = UnknownVal();
1675 SVal maxLastElementIndex = UnknownVal();
1676 const char *boundWarning = nullptr;
1677
1678 // FIXME: Why do we choose the srcExpr if the access has no size?
1679 // Note that the 3rd argument of the call would be the size parameter.
1680 SizeArgExpr SrcExprAsSizeDummy = {srcExpr.Expression, srcExpr.ArgumentIndex};
1681 state = CheckOverlap(
1682 C, state,
1683 (IsBounded ? SizeArgExpr{CE->getArg(2), 2} : SrcExprAsSizeDummy), Dst,
1684 srcExpr);
1685
1686 if (!state)
1687 return;
1688
1689 // If the function is strncpy, strncat, etc... it is bounded.
1690 if (IsBounded) {
1691 // Get the max number of characters to copy.
1692 SizeArgExpr lenExpr = {CE->getArg(2), 2};
1693 SVal lenVal = state->getSVal(lenExpr.Expression, LCtx);
1694
1695 // Protect against misdeclared strncpy().
1696 lenVal =
1697 svalBuilder.evalCast(lenVal, sizeTy, lenExpr.Expression->getType());
1698
1699 Optional<NonLoc> lenValNL = lenVal.getAs<NonLoc>();
1700
1701 // If we know both values, we might be able to figure out how much
1702 // we're copying.
1703 if (strLengthNL && lenValNL) {
1704 switch (appendK) {
1705 case ConcatFnKind::none:
1706 case ConcatFnKind::strcat: {
1707 ProgramStateRef stateSourceTooLong, stateSourceNotTooLong;
1708 // Check if the max number to copy is less than the length of the src.
1709 // If the bound is equal to the source length, strncpy won't null-
1710 // terminate the result!
1711 std::tie(stateSourceTooLong, stateSourceNotTooLong) = state->assume(
1712 svalBuilder
1713 .evalBinOpNN(state, BO_GE, *strLengthNL, *lenValNL, cmpTy)
1714 .castAs<DefinedOrUnknownSVal>());
1715
1716 if (stateSourceTooLong && !stateSourceNotTooLong) {
1717 // Max number to copy is less than the length of the src, so the
1718 // actual strLength copied is the max number arg.
1719 state = stateSourceTooLong;
1720 amountCopied = lenVal;
1721
1722 } else if (!stateSourceTooLong && stateSourceNotTooLong) {
1723 // The source buffer entirely fits in the bound.
1724 state = stateSourceNotTooLong;
1725 amountCopied = strLength;
1726 }
1727 break;
1728 }
1729 case ConcatFnKind::strlcat:
1730 if (!dstStrLengthNL)
1731 return;
1732
1733 // amountCopied = min (size - dstLen - 1 , srcLen)
1734 SVal freeSpace = svalBuilder.evalBinOpNN(state, BO_Sub, *lenValNL,
1735 *dstStrLengthNL, sizeTy);
1736 if (!isa<NonLoc>(freeSpace))
1737 return;
1738 freeSpace =
1739 svalBuilder.evalBinOp(state, BO_Sub, freeSpace,
1740 svalBuilder.makeIntVal(1, sizeTy), sizeTy);
1741 Optional<NonLoc> freeSpaceNL = freeSpace.getAs<NonLoc>();
1742
1743 // While unlikely, it is possible that the subtraction is
1744 // too complex to compute, let's check whether it succeeded.
1745 if (!freeSpaceNL)
1746 return;
1747 SVal hasEnoughSpace = svalBuilder.evalBinOpNN(
1748 state, BO_LE, *strLengthNL, *freeSpaceNL, cmpTy);
1749
1750 ProgramStateRef TrueState, FalseState;
1751 std::tie(TrueState, FalseState) =
1752 state->assume(hasEnoughSpace.castAs<DefinedOrUnknownSVal>());
1753
1754 // srcStrLength <= size - dstStrLength -1
1755 if (TrueState && !FalseState) {
1756 amountCopied = strLength;
1757 }
1758
1759 // srcStrLength > size - dstStrLength -1
1760 if (!TrueState && FalseState) {
1761 amountCopied = freeSpace;
1762 }
1763
1764 if (TrueState && FalseState)
1765 amountCopied = UnknownVal();
1766 break;
1767 }
1768 }
1769 // We still want to know if the bound is known to be too large.
1770 if (lenValNL) {
1771 switch (appendK) {
1772 case ConcatFnKind::strcat:
1773 // For strncat, the check is strlen(dst) + lenVal < sizeof(dst)
1774
1775 // Get the string length of the destination. If the destination is
1776 // memory that can't have a string length, we shouldn't be copying
1777 // into it anyway.
1778 if (dstStrLength.isUndef())
1779 return;
1780
1781 if (dstStrLengthNL) {
1782 maxLastElementIndex = svalBuilder.evalBinOpNN(
1783 state, BO_Add, *lenValNL, *dstStrLengthNL, sizeTy);
1784
1785 boundWarning = "Size argument is greater than the free space in the "
1786 "destination buffer";
1787 }
1788 break;
1789 case ConcatFnKind::none:
1790 case ConcatFnKind::strlcat:
1791 // For strncpy and strlcat, this is just checking
1792 // that lenVal <= sizeof(dst).
1793 // (Yes, strncpy and strncat differ in how they treat termination.
1794 // strncat ALWAYS terminates, but strncpy doesn't.)
1795
1796 // We need a special case for when the copy size is zero, in which
1797 // case strncpy will do no work at all. Our bounds check uses n-1
1798 // as the last element accessed, so n == 0 is problematic.
1799 ProgramStateRef StateZeroSize, StateNonZeroSize;
1800 std::tie(StateZeroSize, StateNonZeroSize) =
1801 assumeZero(C, state, *lenValNL, sizeTy);
1802
1803 // If the size is known to be zero, we're done.
1804 if (StateZeroSize && !StateNonZeroSize) {
1805 if (returnPtr) {
1806 StateZeroSize = StateZeroSize->BindExpr(CE, LCtx, DstVal);
1807 } else {
1808 if (appendK == ConcatFnKind::none) {
1809 // strlcpy returns strlen(src)
1810 StateZeroSize = StateZeroSize->BindExpr(CE, LCtx, strLength);
1811 } else {
1812 // strlcat returns strlen(src) + strlen(dst)
1813 SVal retSize = svalBuilder.evalBinOp(
1814 state, BO_Add, strLength, dstStrLength, sizeTy);
1815 StateZeroSize = StateZeroSize->BindExpr(CE, LCtx, retSize);
1816 }
1817 }
1818 C.addTransition(StateZeroSize);
1819 return;
1820 }
1821
1822 // Otherwise, go ahead and figure out the last element we'll touch.
1823 // We don't record the non-zero assumption here because we can't
1824 // be sure. We won't warn on a possible zero.
1825 NonLoc one = svalBuilder.makeIntVal(1, sizeTy).castAs<NonLoc>();
1826 maxLastElementIndex =
1827 svalBuilder.evalBinOpNN(state, BO_Sub, *lenValNL, one, sizeTy);
1828 boundWarning = "Size argument is greater than the length of the "
1829 "destination buffer";
1830 break;
1831 }
1832 }
1833 } else {
1834 // The function isn't bounded. The amount copied should match the length
1835 // of the source buffer.
1836 amountCopied = strLength;
1837 }
1838
1839 assert(state)(static_cast <bool> (state) ? void (0) : __assert_fail (
"state", "clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp"
, 1839, __extension__ __PRETTY_FUNCTION__))
;
1840
1841 // This represents the number of characters copied into the destination
1842 // buffer. (It may not actually be the strlen if the destination buffer
1843 // is not terminated.)
1844 SVal finalStrLength = UnknownVal();
1845 SVal strlRetVal = UnknownVal();
1846
1847 if (appendK == ConcatFnKind::none && !returnPtr) {
1848 // strlcpy returns the sizeof(src)
1849 strlRetVal = strLength;
1850 }
1851
1852 // If this is an appending function (strcat, strncat...) then set the
1853 // string length to strlen(src) + strlen(dst) since the buffer will
1854 // ultimately contain both.
1855 if (appendK != ConcatFnKind::none) {
1856 // Get the string length of the destination. If the destination is memory
1857 // that can't have a string length, we shouldn't be copying into it anyway.
1858 if (dstStrLength.isUndef())
1859 return;
1860
1861 if (appendK == ConcatFnKind::strlcat && dstStrLengthNL && strLengthNL) {
1862 strlRetVal = svalBuilder.evalBinOpNN(state, BO_Add, *strLengthNL,
1863 *dstStrLengthNL, sizeTy);
1864 }
1865
1866 Optional<NonLoc> amountCopiedNL = amountCopied.getAs<NonLoc>();
1867
1868 // If we know both string lengths, we might know the final string length.
1869 if (amountCopiedNL && dstStrLengthNL) {
1870 // Make sure the two lengths together don't overflow a size_t.
1871 state = checkAdditionOverflow(C, state, *amountCopiedNL, *dstStrLengthNL);
1872 if (!state)
1873 return;
1874
1875 finalStrLength = svalBuilder.evalBinOpNN(state, BO_Add, *amountCopiedNL,
1876 *dstStrLengthNL, sizeTy);
1877 }
1878
1879 // If we couldn't get a single value for the final string length,
1880 // we can at least bound it by the individual lengths.
1881 if (finalStrLength.isUnknown()) {
1882 // Try to get a "hypothetical" string length symbol, which we can later
1883 // set as a real value if that turns out to be the case.
1884 finalStrLength = getCStringLength(C, state, CE, DstVal, true);
1885 assert(!finalStrLength.isUndef())(static_cast <bool> (!finalStrLength.isUndef()) ? void (
0) : __assert_fail ("!finalStrLength.isUndef()", "clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp"
, 1885, __extension__ __PRETTY_FUNCTION__))
;
1886
1887 if (Optional<NonLoc> finalStrLengthNL = finalStrLength.getAs<NonLoc>()) {
1888 if (amountCopiedNL && appendK == ConcatFnKind::none) {
1889 // we overwrite dst string with the src
1890 // finalStrLength >= srcStrLength
1891 SVal sourceInResult = svalBuilder.evalBinOpNN(
1892 state, BO_GE, *finalStrLengthNL, *amountCopiedNL, cmpTy);
1893 state = state->assume(sourceInResult.castAs<DefinedOrUnknownSVal>(),
1894 true);
1895 if (!state)
1896 return;
1897 }
1898
1899 if (dstStrLengthNL && appendK != ConcatFnKind::none) {
1900 // we extend the dst string with the src
1901 // finalStrLength >= dstStrLength
1902 SVal destInResult = svalBuilder.evalBinOpNN(state, BO_GE,
1903 *finalStrLengthNL,
1904 *dstStrLengthNL,
1905 cmpTy);
1906 state =
1907 state->assume(destInResult.castAs<DefinedOrUnknownSVal>(), true);
1908 if (!state)
1909 return;
1910 }
1911 }
1912 }
1913
1914 } else {
1915 // Otherwise, this is a copy-over function (strcpy, strncpy, ...), and
1916 // the final string length will match the input string length.
1917 finalStrLength = amountCopied;
1918 }
1919
1920 SVal Result;
1921
1922 if (returnPtr) {
1923 // The final result of the function will either be a pointer past the last
1924 // copied element, or a pointer to the start of the destination buffer.
1925 Result = (ReturnEnd ? UnknownVal() : DstVal);
1926 } else {
1927 if (appendK == ConcatFnKind::strlcat || appendK == ConcatFnKind::none)
1928 //strlcpy, strlcat
1929 Result = strlRetVal;
1930 else
1931 Result = finalStrLength;
1932 }
1933
1934 assert(state)(static_cast <bool> (state) ? void (0) : __assert_fail (
"state", "clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp"
, 1934, __extension__ __PRETTY_FUNCTION__))
;
1935
1936 // If the destination is a MemRegion, try to check for a buffer overflow and
1937 // record the new string length.
1938 if (Optional<loc::MemRegionVal> dstRegVal =
1939 DstVal.getAs<loc::MemRegionVal>()) {
1940 QualType ptrTy = Dst.Expression->getType();
1941
1942 // If we have an exact value on a bounded copy, use that to check for
1943 // overflows, rather than our estimate about how much is actually copied.
1944 if (Optional<NonLoc> maxLastNL = maxLastElementIndex.getAs<NonLoc>()) {
1945 SVal maxLastElement =
1946 svalBuilder.evalBinOpLN(state, BO_Add, *dstRegVal, *maxLastNL, ptrTy);
1947
1948 state = CheckLocation(C, state, Dst, maxLastElement, AccessKind::write);
1949 if (!state)
1950 return;
1951 }
1952
1953 // Then, if the final length is known...
1954 if (Optional<NonLoc> knownStrLength = finalStrLength.getAs<NonLoc>()) {
1955 SVal lastElement = svalBuilder.evalBinOpLN(state, BO_Add, *dstRegVal,
1956 *knownStrLength, ptrTy);
1957
1958 // ...and we haven't checked the bound, we'll check the actual copy.
1959 if (!boundWarning) {
1960 state = CheckLocation(C, state, Dst, lastElement, AccessKind::write);
1961 if (!state)
1962 return;
1963 }
1964
1965 // If this is a stpcpy-style copy, the last element is the return value.
1966 if (returnPtr && ReturnEnd)
1967 Result = lastElement;
1968 }
1969
1970 // Invalidate the destination (regular invalidation without pointer-escaping
1971 // the address of the top-level region). This must happen before we set the
1972 // C string length because invalidation will clear the length.
1973 // FIXME: Even if we can't perfectly model the copy, we should see if we
1974 // can use LazyCompoundVals to copy the source values into the destination.
1975 // This would probably remove any existing bindings past the end of the
1976 // string, but that's still an improvement over blank invalidation.
1977 state = InvalidateBuffer(C, state, Dst.Expression, *dstRegVal,
1978 /*IsSourceBuffer*/ false, nullptr);
1979
1980 // Invalidate the source (const-invalidation without const-pointer-escaping
1981 // the address of the top-level region).
1982 state = InvalidateBuffer(C, state, srcExpr.Expression, srcVal,
1983 /*IsSourceBuffer*/ true, nullptr);
1984
1985 // Set the C string length of the destination, if we know it.
1986 if (IsBounded && (appendK == ConcatFnKind::none)) {
1987 // strncpy is annoying in that it doesn't guarantee to null-terminate
1988 // the result string. If the original string didn't fit entirely inside
1989 // the bound (including the null-terminator), we don't know how long the
1990 // result is.
1991 if (amountCopied != strLength)
1992 finalStrLength = UnknownVal();
1993 }
1994 state = setCStringLength(state, dstRegVal->getRegion(), finalStrLength);
1995 }
1996
1997 assert(state)(static_cast <bool> (state) ? void (0) : __assert_fail (
"state", "clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp"
, 1997, __extension__ __PRETTY_FUNCTION__))
;
1998
1999 if (returnPtr) {
2000 // If this is a stpcpy-style copy, but we were unable to check for a buffer
2001 // overflow, we still need a result. Conjure a return value.
2002 if (ReturnEnd && Result.isUnknown()) {
2003 Result = svalBuilder.conjureSymbolVal(nullptr, CE, LCtx, C.blockCount());
2004 }
2005 }
2006 // Set the return value.
2007 state = state->BindExpr(CE, LCtx, Result);
2008 C.addTransition(state);
2009}
2010
2011void CStringChecker::evalStrcmp(CheckerContext &C, const CallExpr *CE) const {
2012 //int strcmp(const char *s1, const char *s2);
2013 evalStrcmpCommon(C, CE, /* IsBounded = */ false, /* IgnoreCase = */ false);
2014}
2015
2016void CStringChecker::evalStrncmp(CheckerContext &C, const CallExpr *CE) const {
2017 //int strncmp(const char *s1, const char *s2, size_t n);
2018 evalStrcmpCommon(C, CE, /* IsBounded = */ true, /* IgnoreCase = */ false);
2019}
2020
2021void CStringChecker::evalStrcasecmp(CheckerContext &C,
2022 const CallExpr *CE) const {
2023 //int strcasecmp(const char *s1, const char *s2);
2024 evalStrcmpCommon(C, CE, /* IsBounded = */ false, /* IgnoreCase = */ true);
2025}
2026
2027void CStringChecker::evalStrncasecmp(CheckerContext &C,
2028 const CallExpr *CE) const {
2029 //int strncasecmp(const char *s1, const char *s2, size_t n);
2030 evalStrcmpCommon(C, CE, /* IsBounded = */ true, /* IgnoreCase = */ true);
2031}
2032
2033void CStringChecker::evalStrcmpCommon(CheckerContext &C, const CallExpr *CE,
2034 bool IsBounded, bool IgnoreCase) const {
2035 CurrentFunctionDescription = "string comparison function";
2036 ProgramStateRef state = C.getState();
2037 const LocationContext *LCtx = C.getLocationContext();
2038
2039 // Check that the first string is non-null
2040 AnyArgExpr Left = {CE->getArg(0), 0};
2041 SVal LeftVal = state->getSVal(Left.Expression, LCtx);
2042 state = checkNonNull(C, state, Left, LeftVal);
2043 if (!state)
2044 return;
2045
2046 // Check that the second string is non-null.
2047 AnyArgExpr Right = {CE->getArg(1), 1};
2048 SVal RightVal = state->getSVal(Right.Expression, LCtx);
2049 state = checkNonNull(C, state, Right, RightVal);
2050 if (!state)
2051 return;
2052
2053 // Get the string length of the first string or give up.
2054 SVal LeftLength = getCStringLength(C, state, Left.Expression, LeftVal);
2055 if (LeftLength.isUndef())
2056 return;
2057
2058 // Get the string length of the second string or give up.
2059 SVal RightLength = getCStringLength(C, state, Right.Expression, RightVal);
2060 if (RightLength.isUndef())
2061 return;
2062
2063 // If we know the two buffers are the same, we know the result is 0.
2064 // First, get the two buffers' addresses. Another checker will have already
2065 // made sure they're not undefined.
2066 DefinedOrUnknownSVal LV = LeftVal.castAs<DefinedOrUnknownSVal>();
2067 DefinedOrUnknownSVal RV = RightVal.castAs<DefinedOrUnknownSVal>();
2068
2069 // See if they are the same.
2070 SValBuilder &svalBuilder = C.getSValBuilder();
2071 DefinedOrUnknownSVal SameBuf = svalBuilder.evalEQ(state, LV, RV);
2072 ProgramStateRef StSameBuf, StNotSameBuf;
2073 std::tie(StSameBuf, StNotSameBuf) = state->assume(SameBuf);
2074
2075 // If the two arguments might be the same buffer, we know the result is 0,
2076 // and we only need to check one size.
2077 if (StSameBuf) {
2078 StSameBuf = StSameBuf->BindExpr(CE, LCtx,
2079 svalBuilder.makeZeroVal(CE->getType()));
2080 C.addTransition(StSameBuf);
2081
2082 // If the two arguments are GUARANTEED to be the same, we're done!
2083 if (!StNotSameBuf)
2084 return;
2085 }
2086
2087 assert(StNotSameBuf)(static_cast <bool> (StNotSameBuf) ? void (0) : __assert_fail
("StNotSameBuf", "clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp"
, 2087, __extension__ __PRETTY_FUNCTION__))
;
2088 state = StNotSameBuf;
2089
2090 // At this point we can go about comparing the two buffers.
2091 // For now, we only do this if they're both known string literals.
2092
2093 // Attempt to extract string literals from both expressions.
2094 const StringLiteral *LeftStrLiteral =
2095 getCStringLiteral(C, state, Left.Expression, LeftVal);
2096 const StringLiteral *RightStrLiteral =
2097 getCStringLiteral(C, state, Right.Expression, RightVal);
2098 bool canComputeResult = false;
2099 SVal resultVal = svalBuilder.conjureSymbolVal(nullptr, CE, LCtx,
2100 C.blockCount());
2101
2102 if (LeftStrLiteral && RightStrLiteral) {
2103 StringRef LeftStrRef = LeftStrLiteral->getString();
2104 StringRef RightStrRef = RightStrLiteral->getString();
2105
2106 if (IsBounded) {
2107 // Get the max number of characters to compare.
2108 const Expr *lenExpr = CE->getArg(2);
2109 SVal lenVal = state->getSVal(lenExpr, LCtx);
2110
2111 // If the length is known, we can get the right substrings.
2112 if (const llvm::APSInt *len = svalBuilder.getKnownValue(state, lenVal)) {
2113 // Create substrings of each to compare the prefix.
2114 LeftStrRef = LeftStrRef.substr(0, (size_t)len->getZExtValue());
2115 RightStrRef = RightStrRef.substr(0, (size_t)len->getZExtValue());
2116 canComputeResult = true;
2117 }
2118 } else {
2119 // This is a normal, unbounded strcmp.
2120 canComputeResult = true;
2121 }
2122
2123 if (canComputeResult) {
2124 // Real strcmp stops at null characters.
2125 size_t s1Term = LeftStrRef.find('\0');
2126 if (s1Term != StringRef::npos)
2127 LeftStrRef = LeftStrRef.substr(0, s1Term);
2128
2129 size_t s2Term = RightStrRef.find('\0');
2130 if (s2Term != StringRef::npos)
2131 RightStrRef = RightStrRef.substr(0, s2Term);
2132
2133 // Use StringRef's comparison methods to compute the actual result.
2134 int compareRes = IgnoreCase ? LeftStrRef.compare_insensitive(RightStrRef)
2135 : LeftStrRef.compare(RightStrRef);
2136
2137 // The strcmp function returns an integer greater than, equal to, or less
2138 // than zero, [c11, p7.24.4.2].
2139 if (compareRes == 0) {
2140 resultVal = svalBuilder.makeIntVal(compareRes, CE->getType());
2141 }
2142 else {
2143 DefinedSVal zeroVal = svalBuilder.makeIntVal(0, CE->getType());
2144 // Constrain strcmp's result range based on the result of StringRef's
2145 // comparison methods.
2146 BinaryOperatorKind op = (compareRes == 1) ? BO_GT : BO_LT;
2147 SVal compareWithZero =
2148 svalBuilder.evalBinOp(state, op, resultVal, zeroVal,
2149 svalBuilder.getConditionType());
2150 DefinedSVal compareWithZeroVal = compareWithZero.castAs<DefinedSVal>();
2151 state = state->assume(compareWithZeroVal, true);
2152 }
2153 }
2154 }
2155
2156 state = state->BindExpr(CE, LCtx, resultVal);
2157
2158 // Record this as a possible path.
2159 C.addTransition(state);
2160}
2161
2162void CStringChecker::evalStrsep(CheckerContext &C, const CallExpr *CE) const {
2163 // char *strsep(char **stringp, const char *delim);
2164 // Verify whether the search string parameter matches the return type.
2165 SourceArgExpr SearchStrPtr = {CE->getArg(0), 0};
2166
2167 QualType CharPtrTy = SearchStrPtr.Expression->getType()->getPointeeType();
2168 if (CharPtrTy.isNull() ||
2169 CE->getType().getUnqualifiedType() != CharPtrTy.getUnqualifiedType())
2170 return;
2171
2172 CurrentFunctionDescription = "strsep()";
2173 ProgramStateRef State = C.getState();
2174 const LocationContext *LCtx = C.getLocationContext();
2175
2176 // Check that the search string pointer is non-null (though it may point to
2177 // a null string).
2178 SVal SearchStrVal = State->getSVal(SearchStrPtr.Expression, LCtx);
2179 State = checkNonNull(C, State, SearchStrPtr, SearchStrVal);
2180 if (!State)
2181 return;
2182
2183 // Check that the delimiter string is non-null.
2184 AnyArgExpr DelimStr = {CE->getArg(1), 1};
2185 SVal DelimStrVal = State->getSVal(DelimStr.Expression, LCtx);
2186 State = checkNonNull(C, State, DelimStr, DelimStrVal);
2187 if (!State)
2188 return;
2189
2190 SValBuilder &SVB = C.getSValBuilder();
2191 SVal Result;
2192 if (Optional<Loc> SearchStrLoc = SearchStrVal.getAs<Loc>()) {
2193 // Get the current value of the search string pointer, as a char*.
2194 Result = State->getSVal(*SearchStrLoc, CharPtrTy);
2195
2196 // Invalidate the search string, representing the change of one delimiter
2197 // character to NUL.
2198 State = InvalidateBuffer(C, State, SearchStrPtr.Expression, Result,
2199 /*IsSourceBuffer*/ false, nullptr);
2200
2201 // Overwrite the search string pointer. The new value is either an address
2202 // further along in the same string, or NULL if there are no more tokens.
2203 State = State->bindLoc(*SearchStrLoc,
2204 SVB.conjureSymbolVal(getTag(),
2205 CE,
2206 LCtx,
2207 CharPtrTy,
2208 C.blockCount()),
2209 LCtx);
2210 } else {
2211 assert(SearchStrVal.isUnknown())(static_cast <bool> (SearchStrVal.isUnknown()) ? void (
0) : __assert_fail ("SearchStrVal.isUnknown()", "clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp"
, 2211, __extension__ __PRETTY_FUNCTION__))
;
2212 // Conjure a symbolic value. It's the best we can do.
2213 Result = SVB.conjureSymbolVal(nullptr, CE, LCtx, C.blockCount());
2214 }
2215
2216 // Set the return value, and finish.
2217 State = State->BindExpr(CE, LCtx, Result);
2218 C.addTransition(State);
2219}
2220
2221// These should probably be moved into a C++ standard library checker.
2222void CStringChecker::evalStdCopy(CheckerContext &C, const CallExpr *CE) const {
2223 evalStdCopyCommon(C, CE);
2224}
2225
2226void CStringChecker::evalStdCopyBackward(CheckerContext &C,
2227 const CallExpr *CE) const {
2228 evalStdCopyCommon(C, CE);
2229}
2230
2231void CStringChecker::evalStdCopyCommon(CheckerContext &C,
2232 const CallExpr *CE) const {
2233 if (!CE->getArg(2)->getType()->isPointerType())
2234 return;
2235
2236 ProgramStateRef State = C.getState();
2237
2238 const LocationContext *LCtx = C.getLocationContext();
2239
2240 // template <class _InputIterator, class _OutputIterator>
2241 // _OutputIterator
2242 // copy(_InputIterator __first, _InputIterator __last,
2243 // _OutputIterator __result)
2244
2245 // Invalidate the destination buffer
2246 const Expr *Dst = CE->getArg(2);
2247 SVal DstVal = State->getSVal(Dst, LCtx);
2248 State = InvalidateBuffer(C, State, Dst, DstVal, /*IsSource=*/false,
2249 /*Size=*/nullptr);
2250
2251 SValBuilder &SVB = C.getSValBuilder();
2252
2253 SVal ResultVal = SVB.conjureSymbolVal(nullptr, CE, LCtx, C.blockCount());
2254 State = State->BindExpr(CE, LCtx, ResultVal);
2255
2256 C.addTransition(State);
2257}
2258
2259void CStringChecker::evalMemset(CheckerContext &C, const CallExpr *CE) const {
2260 // void *memset(void *s, int c, size_t n);
2261 CurrentFunctionDescription = "memory set function";
2262
2263 DestinationArgExpr Buffer = {CE->getArg(0), 0};
2264 AnyArgExpr CharE = {CE->getArg(1), 1};
2265 SizeArgExpr Size = {CE->getArg(2), 2};
2266
2267 ProgramStateRef State = C.getState();
2268
2269 // See if the size argument is zero.
2270 const LocationContext *LCtx = C.getLocationContext();
2271 SVal SizeVal = C.getSVal(Size.Expression);
2272 QualType SizeTy = Size.Expression->getType();
2273
2274 ProgramStateRef ZeroSize, NonZeroSize;
2275 std::tie(ZeroSize, NonZeroSize) = assumeZero(C, State, SizeVal, SizeTy);
2276
2277 // Get the value of the memory area.
2278 SVal BufferPtrVal = C.getSVal(Buffer.Expression);
2279
2280 // If the size is zero, there won't be any actual memory access, so
2281 // just bind the return value to the buffer and return.
2282 if (ZeroSize && !NonZeroSize) {
2283 ZeroSize = ZeroSize->BindExpr(CE, LCtx, BufferPtrVal);
2284 C.addTransition(ZeroSize);
2285 return;
2286 }
2287
2288 // Ensure the memory area is not null.
2289 // If it is NULL there will be a NULL pointer dereference.
2290 State = checkNonNull(C, NonZeroSize, Buffer, BufferPtrVal);
2291 if (!State)
2292 return;
2293
2294 State = CheckBufferAccess(C, State, Buffer, Size, AccessKind::write);
2295 if (!State)
2296 return;
2297
2298 // According to the values of the arguments, bind the value of the second
2299 // argument to the destination buffer and set string length, or just
2300 // invalidate the destination buffer.
2301 if (!memsetAux(Buffer.Expression, C.getSVal(CharE.Expression),
2302 Size.Expression, C, State))
2303 return;
2304
2305 State = State->BindExpr(CE, LCtx, BufferPtrVal);
2306 C.addTransition(State);
2307}
2308
2309void CStringChecker::evalBzero(CheckerContext &C, const CallExpr *CE) const {
2310 CurrentFunctionDescription = "memory clearance function";
2311
2312 DestinationArgExpr Buffer = {CE->getArg(0), 0};
2313 SizeArgExpr Size = {CE->getArg(1), 1};
2314 SVal Zero = C.getSValBuilder().makeZeroVal(C.getASTContext().IntTy);
2315
2316 ProgramStateRef State = C.getState();
2317
2318 // See if the size argument is zero.
2319 SVal SizeVal = C.getSVal(Size.Expression);
2320 QualType SizeTy = Size.Expression->getType();
2321
2322 ProgramStateRef StateZeroSize, StateNonZeroSize;
2323 std::tie(StateZeroSize, StateNonZeroSize) =
2324 assumeZero(C, State, SizeVal, SizeTy);
2325
2326 // If the size is zero, there won't be any actual memory access,
2327 // In this case we just return.
2328 if (StateZeroSize && !StateNonZeroSize) {
2329 C.addTransition(StateZeroSize);
2330 return;
2331 }
2332
2333 // Get the value of the memory area.
2334 SVal MemVal = C.getSVal(Buffer.Expression);
2335
2336 // Ensure the memory area is not null.
2337 // If it is NULL there will be a NULL pointer dereference.
2338 State = checkNonNull(C, StateNonZeroSize, Buffer, MemVal);
2339 if (!State)
2340 return;
2341
2342 State = CheckBufferAccess(C, State, Buffer, Size, AccessKind::write);
2343 if (!State)
2344 return;
2345
2346 if (!memsetAux(Buffer.Expression, Zero, Size.Expression, C, State))
2347 return;
2348
2349 C.addTransition(State);
2350}
2351
2352//===----------------------------------------------------------------------===//
2353// The driver method, and other Checker callbacks.
2354//===----------------------------------------------------------------------===//
2355
2356CStringChecker::FnCheck CStringChecker::identifyCall(const CallEvent &Call,
2357 CheckerContext &C) const {
2358 const auto *CE = dyn_cast_or_null<CallExpr>(Call.getOriginExpr());
2359 if (!CE)
2360 return nullptr;
2361
2362 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Call.getDecl());
2363 if (!FD)
2364 return nullptr;
2365
2366 if (StdCopy.matches(Call))
2367 return &CStringChecker::evalStdCopy;
2368 if (StdCopyBackward.matches(Call))
2369 return &CStringChecker::evalStdCopyBackward;
2370
2371 // Pro-actively check that argument types are safe to do arithmetic upon.
2372 // We do not want to crash if someone accidentally passes a structure
2373 // into, say, a C++ overload of any of these functions. We could not check
2374 // that for std::copy because they may have arguments of other types.
2375 for (auto I : CE->arguments()) {
2376 QualType T = I->getType();
2377 if (!T->isIntegralOrEnumerationType() && !T->isPointerType())
2378 return nullptr;
2379 }
2380
2381 const FnCheck *Callback = Callbacks.lookup(Call);
2382 if (Callback)
2383 return *Callback;
2384
2385 return nullptr;
2386}
2387
2388bool CStringChecker::evalCall(const CallEvent &Call, CheckerContext &C) const {
2389 FnCheck Callback = identifyCall(Call, C);
2390
2391 // If the callee isn't a string function, let another checker handle it.
2392 if (!Callback)
2393 return false;
2394
2395 // Check and evaluate the call.
2396 const auto *CE = cast<CallExpr>(Call.getOriginExpr());
2397 Callback(this, C, CE);
2398
2399 // If the evaluate call resulted in no change, chain to the next eval call
2400 // handler.
2401 // Note, the custom CString evaluation calls assume that basic safety
2402 // properties are held. However, if the user chooses to turn off some of these
2403 // checks, we ignore the issues and leave the call evaluation to a generic
2404 // handler.
2405 return C.isDifferent();
2406}
2407
2408void CStringChecker::checkPreStmt(const DeclStmt *DS, CheckerContext &C) const {
2409 // Record string length for char a[] = "abc";
2410 ProgramStateRef state = C.getState();
2411
2412 for (const auto *I : DS->decls()) {
2413 const VarDecl *D = dyn_cast<VarDecl>(I);
2414 if (!D)
2415 continue;
2416
2417 // FIXME: Handle array fields of structs.
2418 if (!D->getType()->isArrayType())
2419 continue;
2420
2421 const Expr *Init = D->getInit();
2422 if (!Init)
2423 continue;
2424 if (!isa<StringLiteral>(Init))
2425 continue;
2426
2427 Loc VarLoc = state->getLValue(D, C.getLocationContext());
2428 const MemRegion *MR = VarLoc.getAsRegion();
2429 if (!MR)
2430 continue;
2431
2432 SVal StrVal = C.getSVal(Init);
2433 assert(StrVal.isValid() && "Initializer string is unknown or undefined")(static_cast <bool> (StrVal.isValid() && "Initializer string is unknown or undefined"
) ? void (0) : __assert_fail ("StrVal.isValid() && \"Initializer string is unknown or undefined\""
, "clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp", 2433
, __extension__ __PRETTY_FUNCTION__))
;
2434 DefinedOrUnknownSVal strLength =
2435 getCStringLength(C, state, Init, StrVal).castAs<DefinedOrUnknownSVal>();
2436
2437 state = state->set<CStringLength>(MR, strLength);
2438 }
2439
2440 C.addTransition(state);
2441}
2442
2443ProgramStateRef
2444CStringChecker::checkRegionChanges(ProgramStateRef state,
2445 const InvalidatedSymbols *,
2446 ArrayRef<const MemRegion *> ExplicitRegions,
2447 ArrayRef<const MemRegion *> Regions,
2448 const LocationContext *LCtx,
2449 const CallEvent *Call) const {
2450 CStringLengthTy Entries = state->get<CStringLength>();
2451 if (Entries.isEmpty())
2452 return state;
2453
2454 llvm::SmallPtrSet<const MemRegion *, 8> Invalidated;
2455 llvm::SmallPtrSet<const MemRegion *, 32> SuperRegions;
2456
2457 // First build sets for the changed regions and their super-regions.
2458 for (ArrayRef<const MemRegion *>::iterator
2459 I = Regions.begin(), E = Regions.end(); I != E; ++I) {
2460 const MemRegion *MR = *I;
2461 Invalidated.insert(MR);
2462
2463 SuperRegions.insert(MR);
2464 while (const SubRegion *SR = dyn_cast<SubRegion>(MR)) {
2465 MR = SR->getSuperRegion();
2466 SuperRegions.insert(MR);
2467 }
2468 }
2469
2470 CStringLengthTy::Factory &F = state->get_context<CStringLength>();
2471
2472 // Then loop over the entries in the current state.
2473 for (CStringLengthTy::iterator I = Entries.begin(),
2474 E = Entries.end(); I != E; ++I) {
2475 const MemRegion *MR = I.getKey();
2476
2477 // Is this entry for a super-region of a changed region?
2478 if (SuperRegions.count(MR)) {
2479 Entries = F.remove(Entries, MR);
2480 continue;
2481 }
2482
2483 // Is this entry for a sub-region of a changed region?
2484 const MemRegion *Super = MR;
2485 while (const SubRegion *SR = dyn_cast<SubRegion>(Super)) {
2486 Super = SR->getSuperRegion();
2487 if (Invalidated.count(Super)) {
2488 Entries = F.remove(Entries, MR);
2489 break;
2490 }
2491 }
2492 }
2493
2494 return state->set<CStringLength>(Entries);
2495}
2496
2497void CStringChecker::checkLiveSymbols(ProgramStateRef state,
2498 SymbolReaper &SR) const {
2499 // Mark all symbols in our string length map as valid.
2500 CStringLengthTy Entries = state->get<CStringLength>();
2501
2502 for (CStringLengthTy::iterator I = Entries.begin(), E = Entries.end();
2503 I != E; ++I) {
2504 SVal Len = I.getData();
2505
2506 for (SymExpr::symbol_iterator si = Len.symbol_begin(),
2507 se = Len.symbol_end(); si != se; ++si)
2508 SR.markInUse(*si);
2509 }
2510}
2511
2512void CStringChecker::checkDeadSymbols(SymbolReaper &SR,
2513 CheckerContext &C) const {
2514 ProgramStateRef state = C.getState();
2515 CStringLengthTy Entries = state->get<CStringLength>();
2516 if (Entries.isEmpty())
2517 return;
2518
2519 CStringLengthTy::Factory &F = state->get_context<CStringLength>();
2520 for (CStringLengthTy::iterator I = Entries.begin(), E = Entries.end();
2521 I != E; ++I) {
2522 SVal Len = I.getData();
2523 if (SymbolRef Sym = Len.getAsSymbol()) {
2524 if (SR.isDead(Sym))
2525 Entries = F.remove(Entries, I.getKey());
2526 }
2527 }
2528
2529 state = state->set<CStringLength>(Entries);
2530 C.addTransition(state);
2531}
2532
2533void ento::registerCStringModeling(CheckerManager &Mgr) {
2534 Mgr.registerChecker<CStringChecker>();
2535}
2536
2537bool ento::shouldRegisterCStringModeling(const CheckerManager &mgr) {
2538 return true;
2539}
2540
2541#define REGISTER_CHECKER(name)void ento::registername(CheckerManager &mgr) { CStringChecker
*checker = mgr.getChecker<CStringChecker>(); checker->
Filter.Checkname = true; checker->Filter.CheckNamename = mgr
.getCurrentCheckerName(); } bool ento::shouldRegistername(const
CheckerManager &mgr) { return true; }
\
2542 void ento::register##name(CheckerManager &mgr) { \
2543 CStringChecker *checker = mgr.getChecker<CStringChecker>(); \
2544 checker->Filter.Check##name = true; \
2545 checker->Filter.CheckName##name = mgr.getCurrentCheckerName(); \
2546 } \
2547 \
2548 bool ento::shouldRegister##name(const CheckerManager &mgr) { return true; }
2549
2550REGISTER_CHECKER(CStringNullArg)void ento::registerCStringNullArg(CheckerManager &mgr) { CStringChecker
*checker = mgr.getChecker<CStringChecker>(); checker->
Filter.CheckCStringNullArg = true; checker->Filter.CheckNameCStringNullArg
= mgr.getCurrentCheckerName(); } bool ento::shouldRegisterCStringNullArg
(const CheckerManager &mgr) { return true; }
2551REGISTER_CHECKER(CStringOutOfBounds)void ento::registerCStringOutOfBounds(CheckerManager &mgr
) { CStringChecker *checker = mgr.getChecker<CStringChecker
>(); checker->Filter.CheckCStringOutOfBounds = true; checker
->Filter.CheckNameCStringOutOfBounds = mgr.getCurrentCheckerName
(); } bool ento::shouldRegisterCStringOutOfBounds(const CheckerManager
&mgr) { return true; }
2552REGISTER_CHECKER(CStringBufferOverlap)void ento::registerCStringBufferOverlap(CheckerManager &mgr
) { CStringChecker *checker = mgr.getChecker<CStringChecker
>(); checker->Filter.CheckCStringBufferOverlap = true; checker
->Filter.CheckNameCStringBufferOverlap = mgr.getCurrentCheckerName
(); } bool ento::shouldRegisterCStringBufferOverlap(const CheckerManager
&mgr) { return true; }
2553REGISTER_CHECKER(CStringNotNullTerm)void ento::registerCStringNotNullTerm(CheckerManager &mgr
) { CStringChecker *checker = mgr.getChecker<CStringChecker
>(); checker->Filter.CheckCStringNotNullTerm = true; checker
->Filter.CheckNameCStringNotNullTerm = mgr.getCurrentCheckerName
(); } bool ento::shouldRegisterCStringNotNullTerm(const CheckerManager
&mgr) { return true; }
2554REGISTER_CHECKER(CStringUninitializedRead)void ento::registerCStringUninitializedRead(CheckerManager &
mgr) { CStringChecker *checker = mgr.getChecker<CStringChecker
>(); checker->Filter.CheckCStringUninitializedRead = true
; checker->Filter.CheckNameCStringUninitializedRead = mgr.
getCurrentCheckerName(); } bool ento::shouldRegisterCStringUninitializedRead
(const CheckerManager &mgr) { return true; }

/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h

1//== ProgramState.h - Path-sensitive "State" for tracking values -*- C++ -*--=//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the state of the program along the analysisa path.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_PROGRAMSTATE_H
14#define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_PROGRAMSTATE_H
15
16#include "clang/Basic/LLVM.h"
17#include "clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h"
18#include "clang/StaticAnalyzer/Core/PathSensitive/DynamicTypeInfo.h"
19#include "clang/StaticAnalyzer/Core/PathSensitive/Environment.h"
20#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h"
21#include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h"
22#include "clang/StaticAnalyzer/Core/PathSensitive/Store.h"
23#include "llvm/ADT/FoldingSet.h"
24#include "llvm/ADT/ImmutableMap.h"
25#include "llvm/Support/Allocator.h"
26#include <utility>
27
28namespace llvm {
29class APSInt;
30}
31
32namespace clang {
33class ASTContext;
34
35namespace ento {
36
37class AnalysisManager;
38class CallEvent;
39class CallEventManager;
40
41typedef std::unique_ptr<ConstraintManager>(*ConstraintManagerCreator)(
42 ProgramStateManager &, ExprEngine *);
43typedef std::unique_ptr<StoreManager>(*StoreManagerCreator)(
44 ProgramStateManager &);
45
46//===----------------------------------------------------------------------===//
47// ProgramStateTrait - Traits used by the Generic Data Map of a ProgramState.
48//===----------------------------------------------------------------------===//
49
50template <typename T> struct ProgramStateTrait {
51 typedef typename T::data_type data_type;
52 static inline void *MakeVoidPtr(data_type D) { return (void*) D; }
53 static inline data_type MakeData(void *const* P) {
54 return P ? (data_type) *P : (data_type) 0;
55 }
56};
57
58/// \class ProgramState
59/// ProgramState - This class encapsulates:
60///
61/// 1. A mapping from expressions to values (Environment)
62/// 2. A mapping from locations to values (Store)
63/// 3. Constraints on symbolic values (GenericDataMap)
64///
65/// Together these represent the "abstract state" of a program.
66///
67/// ProgramState is intended to be used as a functional object; that is,
68/// once it is created and made "persistent" in a FoldingSet, its
69/// values will never change.
70class ProgramState : public llvm::FoldingSetNode {
71public:
72 typedef llvm::ImmutableSet<llvm::APSInt*> IntSetTy;
73 typedef llvm::ImmutableMap<void*, void*> GenericDataMap;
74
75private:
76 void operator=(const ProgramState& R) = delete;
77
78 friend class ProgramStateManager;
79 friend class ExplodedGraph;
80 friend class ExplodedNode;
81 friend class NodeBuilder;
82
83 ProgramStateManager *stateMgr;
84 Environment Env; // Maps a Stmt to its current SVal.
85 Store store; // Maps a location to its current value.
86 GenericDataMap GDM; // Custom data stored by a client of this class.
87
88 // A state is infeasible if there is a contradiction among the constraints.
89 // An infeasible state is represented by a `nullptr`.
90 // In the sense of `assumeDual`, a state can have two children by adding a
91 // new constraint and the negation of that new constraint. A parent state is
92 // over-constrained if both of its children are infeasible. In the
93 // mathematical sense, it means that the parent is infeasible and we should
94 // have realized that at the moment when we have created it. However, we
95 // could not recognize that because of the imperfection of the underlying
96 // constraint solver. We say it is posteriorly over-constrained because we
97 // recognize that a parent is infeasible only *after* a new and more specific
98 // constraint and its negation are evaluated.
99 //
100 // Example:
101 //
102 // x * x = 4 and x is in the range [0, 1]
103 // This is an already infeasible state, but the constraint solver is not
104 // capable of handling sqrt, thus we don't know it yet.
105 //
106 // Then a new constraint `x = 0` is added. At this moment the constraint
107 // solver re-evaluates the existing constraints and realizes the
108 // contradiction `0 * 0 = 4`.
109 // We also evaluate the negated constraint `x != 0`; the constraint solver
110 // deduces `x = 1` and then realizes the contradiction `1 * 1 = 4`.
111 // Both children are infeasible, thus the parent state is marked as
112 // posteriorly over-constrained. These parents are handled with special care:
113 // we do not allow transitions to exploded nodes with such states.
114 bool PosteriorlyOverconstrained = false;
115 // Make internal constraint solver entities friends so they can access the
116 // overconstrained-related functions. We want to keep this API inaccessible
117 // for Checkers.
118 friend class ConstraintManager;
119 bool isPosteriorlyOverconstrained() const {
120 return PosteriorlyOverconstrained;
121 }
122 ProgramStateRef cloneAsPosteriorlyOverconstrained() const;
123
124 unsigned refCount;
125
126 /// makeWithStore - Return a ProgramState with the same values as the current
127 /// state with the exception of using the specified Store.
128 ProgramStateRef makeWithStore(const StoreRef &store) const;
129
130 void setStore(const StoreRef &storeRef);
131
132public:
133 /// This ctor is used when creating the first ProgramState object.
134 ProgramState(ProgramStateManager *mgr, const Environment& env,
135 StoreRef st, GenericDataMap gdm);
136
137 /// Copy ctor - We must explicitly define this or else the "Next" ptr
138 /// in FoldingSetNode will also get copied.
139 ProgramState(const ProgramState &RHS);
140
141 ~ProgramState();
142
143 int64_t getID() const;
144
145 /// Return the ProgramStateManager associated with this state.
146 ProgramStateManager &getStateManager() const {
147 return *stateMgr;
148 }
149
150 AnalysisManager &getAnalysisManager() const;
151
152 /// Return the ConstraintManager.
153 ConstraintManager &getConstraintManager() const;
154
155 /// getEnvironment - Return the environment associated with this state.
156 /// The environment is the mapping from expressions to values.
157 const Environment& getEnvironment() const { return Env; }
158
159 /// Return the store associated with this state. The store
160 /// is a mapping from locations to values.
161 Store getStore() const { return store; }
162
163
164 /// getGDM - Return the generic data map associated with this state.
165 GenericDataMap getGDM() const { return GDM; }
166
167 void setGDM(GenericDataMap gdm) { GDM = gdm; }
168
169 /// Profile - Profile the contents of a ProgramState object for use in a
170 /// FoldingSet. Two ProgramState objects are considered equal if they
171 /// have the same Environment, Store, and GenericDataMap.
172 static void Profile(llvm::FoldingSetNodeID& ID, const ProgramState *V) {
173 V->Env.Profile(ID);
174 ID.AddPointer(V->store);
175 V->GDM.Profile(ID);
176 ID.AddBoolean(V->PosteriorlyOverconstrained);
177 }
178
179 /// Profile - Used to profile the contents of this object for inclusion
180 /// in a FoldingSet.
181 void Profile(llvm::FoldingSetNodeID& ID) const {
182 Profile(ID, this);
183 }
184
185 BasicValueFactory &getBasicVals() const;
186 SymbolManager &getSymbolManager() const;
187
188 //==---------------------------------------------------------------------==//
189 // Constraints on values.
190 //==---------------------------------------------------------------------==//
191 //
192 // Each ProgramState records constraints on symbolic values. These constraints
193 // are managed using the ConstraintManager associated with a ProgramStateManager.
194 // As constraints gradually accrue on symbolic values, added constraints
195 // may conflict and indicate that a state is infeasible (as no real values
196 // could satisfy all the constraints). This is the principal mechanism
197 // for modeling path-sensitivity in ExprEngine/ProgramState.
198 //
199 // Various "assume" methods form the interface for adding constraints to
200 // symbolic values. A call to 'assume' indicates an assumption being placed
201 // on one or symbolic values. 'assume' methods take the following inputs:
202 //
203 // (1) A ProgramState object representing the current state.
204 //
205 // (2) The assumed constraint (which is specific to a given "assume" method).
206 //
207 // (3) A binary value "Assumption" that indicates whether the constraint is
208 // assumed to be true or false.
209 //
210 // The output of "assume*" is a new ProgramState object with the added constraints.
211 // If no new state is feasible, NULL is returned.
212 //
213
214 /// Assumes that the value of \p cond is zero (if \p assumption is "false")
215 /// or non-zero (if \p assumption is "true").
216 ///
217 /// This returns a new state with the added constraint on \p cond.
218 /// If no new state is feasible, NULL is returned.
219 [[nodiscard]] ProgramStateRef assume(DefinedOrUnknownSVal cond,
220 bool assumption) const;
221
222 /// Assumes both "true" and "false" for \p cond, and returns both
223 /// corresponding states (respectively).
224 ///
225 /// This is more efficient than calling assume() twice. Note that one (but not
226 /// both) of the returned states may be NULL.
227 [[nodiscard]] std::pair<ProgramStateRef, ProgramStateRef>
228 assume(DefinedOrUnknownSVal cond) const;
229
230 [[nodiscard]] std::pair<ProgramStateRef, ProgramStateRef>
231 assumeInBoundDual(DefinedOrUnknownSVal idx, DefinedOrUnknownSVal upperBound,
232 QualType IndexType = QualType()) const;
233
234 [[nodiscard]] ProgramStateRef
235 assumeInBound(DefinedOrUnknownSVal idx, DefinedOrUnknownSVal upperBound,
236 bool assumption, QualType IndexType = QualType()) const;
237
238 /// Assumes that the value of \p Val is bounded with [\p From; \p To]
239 /// (if \p assumption is "true") or it is fully out of this range
240 /// (if \p assumption is "false").
241 ///
242 /// This returns a new state with the added constraint on \p cond.
243 /// If no new state is feasible, NULL is returned.
244 [[nodiscard]] ProgramStateRef assumeInclusiveRange(DefinedOrUnknownSVal Val,
245 const llvm::APSInt &From,
246 const llvm::APSInt &To,
247 bool assumption) const;
248
249 /// Assumes given range both "true" and "false" for \p Val, and returns both
250 /// corresponding states (respectively).
251 ///
252 /// This is more efficient than calling assume() twice. Note that one (but not
253 /// both) of the returned states may be NULL.
254 [[nodiscard]] std::pair<ProgramStateRef, ProgramStateRef>
255 assumeInclusiveRange(DefinedOrUnknownSVal Val, const llvm::APSInt &From,
256 const llvm::APSInt &To) const;
257
258 /// Check if the given SVal is not constrained to zero and is not
259 /// a zero constant.
260 ConditionTruthVal isNonNull(SVal V) const;
261
262 /// Check if the given SVal is constrained to zero or is a zero
263 /// constant.
264 ConditionTruthVal isNull(SVal V) const;
265
266 /// \return Whether values \p Lhs and \p Rhs are equal.
267 ConditionTruthVal areEqual(SVal Lhs, SVal Rhs) const;
268
269 /// Utility method for getting regions.
270 LLVM_ATTRIBUTE_RETURNS_NONNULL__attribute__((returns_nonnull))
271 const VarRegion* getRegion(const VarDecl *D, const LocationContext *LC) const;
272
273 //==---------------------------------------------------------------------==//
274 // Binding and retrieving values to/from the environment and symbolic store.
275 //==---------------------------------------------------------------------==//
276
277 /// Create a new state by binding the value 'V' to the statement 'S' in the
278 /// state's environment.
279 [[nodiscard]] ProgramStateRef BindExpr(const Stmt *S,
280 const LocationContext *LCtx, SVal V,
281 bool Invalidate = true) const;
282
283 [[nodiscard]] ProgramStateRef bindLoc(Loc location, SVal V,
284 const LocationContext *LCtx,
285 bool notifyChanges = true) const;
286
287 [[nodiscard]] ProgramStateRef bindLoc(SVal location, SVal V,
288 const LocationContext *LCtx) const;
289
290 /// Initializes the region of memory represented by \p loc with an initial
291 /// value. Once initialized, all values loaded from any sub-regions of that
292 /// region will be equal to \p V, unless overwritten later by the program.
293 /// This method should not be used on regions that are already initialized.
294 /// If you need to indicate that memory contents have suddenly become unknown
295 /// within a certain region of memory, consider invalidateRegions().
296 [[nodiscard]] ProgramStateRef
297 bindDefaultInitial(SVal loc, SVal V, const LocationContext *LCtx) const;
298
299 /// Performs C++ zero-initialization procedure on the region of memory
300 /// represented by \p loc.
301 [[nodiscard]] ProgramStateRef
302 bindDefaultZero(SVal loc, const LocationContext *LCtx) const;
303
304 [[nodiscard]] ProgramStateRef killBinding(Loc LV) const;
305
306 /// Returns the state with bindings for the given regions
307 /// cleared from the store.
308 ///
309 /// Optionally invalidates global regions as well.
310 ///
311 /// \param Regions the set of regions to be invalidated.
312 /// \param E the expression that caused the invalidation.
313 /// \param BlockCount The number of times the current basic block has been
314 // visited.
315 /// \param CausesPointerEscape the flag is set to true when
316 /// the invalidation entails escape of a symbol (representing a
317 /// pointer). For example, due to it being passed as an argument in a
318 /// call.
319 /// \param IS the set of invalidated symbols.
320 /// \param Call if non-null, the invalidated regions represent parameters to
321 /// the call and should be considered directly invalidated.
322 /// \param ITraits information about special handling for a particular
323 /// region/symbol.
324 [[nodiscard]] ProgramStateRef
325 invalidateRegions(ArrayRef<const MemRegion *> Regions, const Expr *E,
326 unsigned BlockCount, const LocationContext *LCtx,
327 bool CausesPointerEscape, InvalidatedSymbols *IS = nullptr,
328 const CallEvent *Call = nullptr,
329 RegionAndSymbolInvalidationTraits *ITraits = nullptr) const;
330
331 [[nodiscard]] ProgramStateRef
332 invalidateRegions(ArrayRef<SVal> Regions, const Expr *E, unsigned BlockCount,
333 const LocationContext *LCtx, bool CausesPointerEscape,
334 InvalidatedSymbols *IS = nullptr,
335 const CallEvent *Call = nullptr,
336 RegionAndSymbolInvalidationTraits *ITraits = nullptr) const;
337
338 /// enterStackFrame - Returns the state for entry to the given stack frame,
339 /// preserving the current state.
340 [[nodiscard]] ProgramStateRef
341 enterStackFrame(const CallEvent &Call,
342 const StackFrameContext *CalleeCtx) const;
343
344 /// Return the value of 'self' if available in the given context.
345 SVal getSelfSVal(const LocationContext *LC) const;
346
347 /// Get the lvalue for a base class object reference.
348 Loc getLValue(const CXXBaseSpecifier &BaseSpec, const SubRegion *Super) const;
349
350 /// Get the lvalue for a base class object reference.
351 Loc getLValue(const CXXRecordDecl *BaseClass, const SubRegion *Super,
352 bool IsVirtual) const;
353
354 /// Get the lvalue for a variable reference.
355 Loc getLValue(const VarDecl *D, const LocationContext *LC) const;
356
357 Loc getLValue(const CompoundLiteralExpr *literal,
358 const LocationContext *LC) const;
359
360 /// Get the lvalue for an ivar reference.
361 SVal getLValue(const ObjCIvarDecl *decl, SVal base) const;
362
363 /// Get the lvalue for a field reference.
364 SVal getLValue(const FieldDecl *decl, SVal Base) const;
365
366 /// Get the lvalue for an indirect field reference.
367 SVal getLValue(const IndirectFieldDecl *decl, SVal Base) const;
368
369 /// Get the lvalue for an array index.
370 SVal getLValue(QualType ElementType, SVal Idx, SVal Base) const;
371
372 /// Returns the SVal bound to the statement 'S' in the state's environment.
373 SVal getSVal(const Stmt *S, const LocationContext *LCtx) const;
374
375 SVal getSValAsScalarOrLoc(const Stmt *Ex, const LocationContext *LCtx) const;
376
377 /// Return the value bound to the specified location.
378 /// Returns UnknownVal() if none found.
379 SVal getSVal(Loc LV, QualType T = QualType()) const;
380
381 /// Returns the "raw" SVal bound to LV before any value simplfication.
382 SVal getRawSVal(Loc LV, QualType T= QualType()) const;
383
384 /// Return the value bound to the specified location.
385 /// Returns UnknownVal() if none found.
386 SVal getSVal(const MemRegion* R, QualType T = QualType()) const;
387
388 /// Return the value bound to the specified location, assuming
389 /// that the value is a scalar integer or an enumeration or a pointer.
390 /// Returns UnknownVal() if none found or the region is not known to hold
391 /// a value of such type.
392 SVal getSValAsScalarOrLoc(const MemRegion *R) const;
393
394 using region_iterator = const MemRegion **;
395
396 /// Visits the symbols reachable from the given SVal using the provided
397 /// SymbolVisitor.
398 ///
399 /// This is a convenience API. Consider using ScanReachableSymbols class
400 /// directly when making multiple scans on the same state with the same
401 /// visitor to avoid repeated initialization cost.
402 /// \sa ScanReachableSymbols
403 bool scanReachableSymbols(SVal val, SymbolVisitor& visitor) const;
404
405 /// Visits the symbols reachable from the regions in the given
406 /// MemRegions range using the provided SymbolVisitor.
407 bool scanReachableSymbols(llvm::iterator_range<region_iterator> Reachable,
408 SymbolVisitor &visitor) const;
409
410 template <typename CB> CB scanReachableSymbols(SVal val) const;
411 template <typename CB> CB
412 scanReachableSymbols(llvm::iterator_range<region_iterator> Reachable) const;
413
414 //==---------------------------------------------------------------------==//
415 // Accessing the Generic Data Map (GDM).
416 //==---------------------------------------------------------------------==//
417
418 void *const* FindGDM(void *K) const;
419
420 template <typename T>
421 [[nodiscard]] ProgramStateRef
422 add(typename ProgramStateTrait<T>::key_type K) const;
423
424 template <typename T>
425 typename ProgramStateTrait<T>::data_type
426 get() const {
427 return ProgramStateTrait<T>::MakeData(FindGDM(ProgramStateTrait<T>::GDMIndex()));
428 }
429
430 template<typename T>
431 typename ProgramStateTrait<T>::lookup_type
432 get(typename ProgramStateTrait<T>::key_type key) const {
433 void *const* d = FindGDM(ProgramStateTrait<T>::GDMIndex());
434 return ProgramStateTrait<T>::Lookup(ProgramStateTrait<T>::MakeData(d), key);
435 }
436
437 template <typename T>
438 typename ProgramStateTrait<T>::context_type get_context() const;
439
440 template <typename T>
441 [[nodiscard]] ProgramStateRef
442 remove(typename ProgramStateTrait<T>::key_type K) const;
443
444 template <typename T>
445 [[nodiscard]] ProgramStateRef
446 remove(typename ProgramStateTrait<T>::key_type K,
447 typename ProgramStateTrait<T>::context_type C) const;
448
449 template <typename T> [[nodiscard]] ProgramStateRef remove() const;
450
451 template <typename T>
452 [[nodiscard]] ProgramStateRef
453 set(typename ProgramStateTrait<T>::data_type D) const;
454
455 template <typename T>
456 [[nodiscard]] ProgramStateRef
457 set(typename ProgramStateTrait<T>::key_type K,
458 typename ProgramStateTrait<T>::value_type E) const;
459
460 template <typename T>
461 [[nodiscard]] ProgramStateRef
462 set(typename ProgramStateTrait<T>::key_type K,
463 typename ProgramStateTrait<T>::value_type E,
464 typename ProgramStateTrait<T>::context_type C) const;
465
466 template<typename T>
467 bool contains(typename ProgramStateTrait<T>::key_type key) const {
468 void *const* d = FindGDM(ProgramStateTrait<T>::GDMIndex());
469 return ProgramStateTrait<T>::Contains(ProgramStateTrait<T>::MakeData(d), key);
470 }
471
472 // Pretty-printing.
473 void printJson(raw_ostream &Out, const LocationContext *LCtx = nullptr,
474 const char *NL = "\n", unsigned int Space = 0,
475 bool IsDot = false) const;
476
477 void printDOT(raw_ostream &Out, const LocationContext *LCtx = nullptr,
478 unsigned int Space = 0) const;
479
480 void dump() const;
481
482private:
483 friend void ProgramStateRetain(const ProgramState *state);
484 friend void ProgramStateRelease(const ProgramState *state);
485
486 /// \sa invalidateValues()
487 /// \sa invalidateRegions()
488 ProgramStateRef
489 invalidateRegionsImpl(ArrayRef<SVal> Values,
490 const Expr *E, unsigned BlockCount,
491 const LocationContext *LCtx,
492 bool ResultsInSymbolEscape,
493 InvalidatedSymbols *IS,
494 RegionAndSymbolInvalidationTraits *HTraits,
495 const CallEvent *Call) const;
496};
497
498//===----------------------------------------------------------------------===//
499// ProgramStateManager - Factory object for ProgramStates.
500//===----------------------------------------------------------------------===//
501
502class ProgramStateManager {
503 friend class ProgramState;
504 friend void ProgramStateRelease(const ProgramState *state);
505private:
506 /// Eng - The ExprEngine that owns this state manager.
507 ExprEngine *Eng; /* Can be null. */
508
509 EnvironmentManager EnvMgr;
510 std::unique_ptr<StoreManager> StoreMgr;
511 std::unique_ptr<ConstraintManager> ConstraintMgr;
512
513 ProgramState::GenericDataMap::Factory GDMFactory;
514
515 typedef llvm::DenseMap<void*,std::pair<void*,void (*)(void*)> > GDMContextsTy;
516 GDMContextsTy GDMContexts;
517
518 /// StateSet - FoldingSet containing all the states created for analyzing
519 /// a particular function. This is used to unique states.
520 llvm::FoldingSet<ProgramState> StateSet;
521
522 /// Object that manages the data for all created SVals.
523 std::unique_ptr<SValBuilder> svalBuilder;
524
525 /// Manages memory for created CallEvents.
526 std::unique_ptr<CallEventManager> CallEventMgr;
527
528 /// A BumpPtrAllocator to allocate states.
529 llvm::BumpPtrAllocator &Alloc;
530
531 /// A vector of ProgramStates that we can reuse.
532 std::vector<ProgramState *> freeStates;
533
534public:
535 ProgramStateManager(ASTContext &Ctx,
536 StoreManagerCreator CreateStoreManager,
537 ConstraintManagerCreator CreateConstraintManager,
538 llvm::BumpPtrAllocator& alloc,
539 ExprEngine *expreng);
540
541 ~ProgramStateManager();
542
543 ProgramStateRef getInitialState(const LocationContext *InitLoc);
544
545 ASTContext &getContext() { return svalBuilder->getContext(); }
546 const ASTContext &getContext() const { return svalBuilder->getContext(); }
547
548 BasicValueFactory &getBasicVals() {
549 return svalBuilder->getBasicValueFactory();
550 }
551
552 SValBuilder &getSValBuilder() {
553 return *svalBuilder;
554 }
555
556 const SValBuilder &getSValBuilder() const {
557 return *svalBuilder;
558 }
559
560 SymbolManager &getSymbolManager() {
561 return svalBuilder->getSymbolManager();
562 }
563 const SymbolManager &getSymbolManager() const {
564 return svalBuilder->getSymbolManager();
565 }
566
567 llvm::BumpPtrAllocator& getAllocator() { return Alloc; }
568
569 MemRegionManager& getRegionManager() {
570 return svalBuilder->getRegionManager();
571 }
572 const MemRegionManager &getRegionManager() const {
573 return svalBuilder->getRegionManager();
574 }
575
576 CallEventManager &getCallEventManager() { return *CallEventMgr; }
577
578 StoreManager &getStoreManager() { return *StoreMgr; }
579 ConstraintManager &getConstraintManager() { return *ConstraintMgr; }
580 ExprEngine &getOwningEngine() { return *Eng; }
581
582 ProgramStateRef
583 removeDeadBindingsFromEnvironmentAndStore(ProgramStateRef St,
584 const StackFrameContext *LCtx,
585 SymbolReaper &SymReaper);
586
587public:
588
589 SVal ArrayToPointer(Loc Array, QualType ElementTy) {
590 return StoreMgr->ArrayToPointer(Array, ElementTy);
591 }
592
593 // Methods that manipulate the GDM.
594 ProgramStateRef addGDM(ProgramStateRef St, void *Key, void *Data);
595 ProgramStateRef removeGDM(ProgramStateRef state, void *Key);
596
597 // Methods that query & manipulate the Store.
598
599 void iterBindings(ProgramStateRef state, StoreManager::BindingsHandler& F) {
600 StoreMgr->iterBindings(state->getStore(), F);
601 }
602
603 ProgramStateRef getPersistentState(ProgramState &Impl);
604 ProgramStateRef getPersistentStateWithGDM(ProgramStateRef FromState,
605 ProgramStateRef GDMState);
606
607 bool haveEqualConstraints(ProgramStateRef S1, ProgramStateRef S2) const {
608 return ConstraintMgr->haveEqualConstraints(S1, S2);
609 }
610
611 bool haveEqualEnvironments(ProgramStateRef S1, ProgramStateRef S2) const {
612 return S1->Env == S2->Env;
613 }
614
615 bool haveEqualStores(ProgramStateRef S1, ProgramStateRef S2) const {
616 return S1->store == S2->store;
617 }
618
619 //==---------------------------------------------------------------------==//
620 // Generic Data Map methods.
621 //==---------------------------------------------------------------------==//
622 //
623 // ProgramStateManager and ProgramState support a "generic data map" that allows
624 // different clients of ProgramState objects to embed arbitrary data within a
625 // ProgramState object. The generic data map is essentially an immutable map
626 // from a "tag" (that acts as the "key" for a client) and opaque values.
627 // Tags/keys and values are simply void* values. The typical way that clients
628 // generate unique tags are by taking the address of a static variable.
629 // Clients are responsible for ensuring that data values referred to by a
630 // the data pointer are immutable (and thus are essentially purely functional
631 // data).
632 //
633 // The templated methods below use the ProgramStateTrait<T> class
634 // to resolve keys into the GDM and to return data values to clients.
635 //
636
637 // Trait based GDM dispatch.
638 template <typename T>
639 ProgramStateRef set(ProgramStateRef st, typename ProgramStateTrait<T>::data_type D) {
640 return addGDM(st, ProgramStateTrait<T>::GDMIndex(),
641 ProgramStateTrait<T>::MakeVoidPtr(D));
642 }
643
644 template<typename T>
645 ProgramStateRef set(ProgramStateRef st,
646 typename ProgramStateTrait<T>::key_type K,
647 typename ProgramStateTrait<T>::value_type V,
648 typename ProgramStateTrait<T>::context_type C) {
649
650 return addGDM(st, ProgramStateTrait<T>::GDMIndex(),
651 ProgramStateTrait<T>::MakeVoidPtr(ProgramStateTrait<T>::Set(st->get<T>(), K, V, C)));
652 }
653
654 template <typename T>
655 ProgramStateRef add(ProgramStateRef st,
656 typename ProgramStateTrait<T>::key_type K,
657 typename ProgramStateTrait<T>::context_type C) {
658 return addGDM(st, ProgramStateTrait<T>::GDMIndex(),
659 ProgramStateTrait<T>::MakeVoidPtr(ProgramStateTrait<T>::Add(st->get<T>(), K, C)));
660 }
661
662 template <typename T>
663 ProgramStateRef remove(ProgramStateRef st,
664 typename ProgramStateTrait<T>::key_type K,
665 typename ProgramStateTrait<T>::context_type C) {
666
667 return addGDM(st, ProgramStateTrait<T>::GDMIndex(),
668 ProgramStateTrait<T>::MakeVoidPtr(ProgramStateTrait<T>::Remove(st->get<T>(), K, C)));
669 }
670
671 template <typename T>
672 ProgramStateRef remove(ProgramStateRef st) {
673 return removeGDM(st, ProgramStateTrait<T>::GDMIndex());
674 }
675
676 void *FindGDMContext(void *index,
677 void *(*CreateContext)(llvm::BumpPtrAllocator&),
678 void (*DeleteContext)(void*));
679
680 template <typename T>
681 typename ProgramStateTrait<T>::context_type get_context() {
682 void *p = FindGDMContext(ProgramStateTrait<T>::GDMIndex(),
683 ProgramStateTrait<T>::CreateContext,
684 ProgramStateTrait<T>::DeleteContext);
685
686 return ProgramStateTrait<T>::MakeContext(p);
687 }
688};
689
690
691//===----------------------------------------------------------------------===//
692// Out-of-line method definitions for ProgramState.
693//===----------------------------------------------------------------------===//
694
695inline ConstraintManager &ProgramState::getConstraintManager() const {
696 return stateMgr->getConstraintManager();
697}
698
699inline const VarRegion* ProgramState::getRegion(const VarDecl *D,
700 const LocationContext *LC) const
701{
702 return getStateManager().getRegionManager().getVarRegion(D, LC);
703}
704
705inline ProgramStateRef ProgramState::assume(DefinedOrUnknownSVal Cond,
706 bool Assumption) const {
707 if (Cond.isUnknown())
19
Taking false branch
708 return this;
709
710 return getStateManager().ConstraintMgr
20
Value assigned to 'S.Obj'
711 ->assume(this, Cond.castAs<DefinedSVal>(), Assumption);
712}
713
714inline std::pair<ProgramStateRef , ProgramStateRef >
715ProgramState::assume(DefinedOrUnknownSVal Cond) const {
716 if (Cond.isUnknown())
717 return std::make_pair(this, this);
718
719 return getStateManager().ConstraintMgr
720 ->assumeDual(this, Cond.castAs<DefinedSVal>());
721}
722
723inline ProgramStateRef ProgramState::assumeInclusiveRange(
724 DefinedOrUnknownSVal Val, const llvm::APSInt &From, const llvm::APSInt &To,
725 bool Assumption) const {
726 if (Val.isUnknown())
727 return this;
728
729 assert(isa<NonLoc>(Val) && "Only NonLocs are supported!")(static_cast <bool> (isa<NonLoc>(Val) && "Only NonLocs are supported!"
) ? void (0) : __assert_fail ("isa<NonLoc>(Val) && \"Only NonLocs are supported!\""
, "clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
, 729, __extension__ __PRETTY_FUNCTION__))
;
730
731 return getStateManager().ConstraintMgr->assumeInclusiveRange(
732 this, Val.castAs<NonLoc>(), From, To, Assumption);
733}
734
735inline std::pair<ProgramStateRef, ProgramStateRef>
736ProgramState::assumeInclusiveRange(DefinedOrUnknownSVal Val,
737 const llvm::APSInt &From,
738 const llvm::APSInt &To) const {
739 if (Val.isUnknown())
740 return std::make_pair(this, this);
741
742 assert(isa<NonLoc>(Val) && "Only NonLocs are supported!")(static_cast <bool> (isa<NonLoc>(Val) && "Only NonLocs are supported!"
) ? void (0) : __assert_fail ("isa<NonLoc>(Val) && \"Only NonLocs are supported!\""
, "clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
, 742, __extension__ __PRETTY_FUNCTION__))
;
743
744 return getStateManager().ConstraintMgr->assumeInclusiveRangeDual(
745 this, Val.castAs<NonLoc>(), From, To);
746}
747
748inline ProgramStateRef ProgramState::bindLoc(SVal LV, SVal V, const LocationContext *LCtx) const {
749 if (Optional<Loc> L = LV.getAs<Loc>())
750 return bindLoc(*L, V, LCtx);
751 return this;
752}
753
754inline Loc ProgramState::getLValue(const CXXBaseSpecifier &BaseSpec,
755 const SubRegion *Super) const {
756 const auto *Base = BaseSpec.getType()->getAsCXXRecordDecl();
757 return loc::MemRegionVal(
758 getStateManager().getRegionManager().getCXXBaseObjectRegion(
759 Base, Super, BaseSpec.isVirtual()));
760}
761
762inline Loc ProgramState::getLValue(const CXXRecordDecl *BaseClass,
763 const SubRegion *Super,
764 bool IsVirtual) const {
765 return loc::MemRegionVal(
766 getStateManager().getRegionManager().getCXXBaseObjectRegion(
767 BaseClass, Super, IsVirtual));
768}
769
770inline Loc ProgramState::getLValue(const VarDecl *VD,
771 const LocationContext *LC) const {
772 return getStateManager().StoreMgr->getLValueVar(VD, LC);
773}
774
775inline Loc ProgramState::getLValue(const CompoundLiteralExpr *literal,
776 const LocationContext *LC) const {
777 return getStateManager().StoreMgr->getLValueCompoundLiteral(literal, LC);
778}
779
780inline SVal ProgramState::getLValue(const ObjCIvarDecl *D, SVal Base) const {
781 return getStateManager().StoreMgr->getLValueIvar(D, Base);
782}
783
784inline SVal ProgramState::getLValue(const FieldDecl *D, SVal Base) const {
785 return getStateManager().StoreMgr->getLValueField(D, Base);
786}
787
788inline SVal ProgramState::getLValue(const IndirectFieldDecl *D,
789 SVal Base) const {
790 StoreManager &SM = *getStateManager().StoreMgr;
791 for (const auto *I : D->chain()) {
792 Base = SM.getLValueField(cast<FieldDecl>(I), Base);
793 }
794
795 return Base;
796}
797
798inline SVal ProgramState::getLValue(QualType ElementType, SVal Idx, SVal Base) const{
799 if (Optional<NonLoc> N = Idx.getAs<NonLoc>())
800 return getStateManager().StoreMgr->getLValueElement(ElementType, *N, Base);
801 return UnknownVal();
802}
803
804inline SVal ProgramState::getSVal(const Stmt *Ex,
805 const LocationContext *LCtx) const{
806 return Env.getSVal(EnvironmentEntry(Ex, LCtx),
807 *getStateManager().svalBuilder);
808}
809
810inline SVal
811ProgramState::getSValAsScalarOrLoc(const Stmt *S,
812 const LocationContext *LCtx) const {
813 if (const Expr *Ex = dyn_cast<Expr>(S)) {
814 QualType T = Ex->getType();
815 if (Ex->isGLValue() || Loc::isLocType(T) ||
816 T->isIntegralOrEnumerationType())
817 return getSVal(S, LCtx);
818 }
819
820 return UnknownVal();
821}
822
823inline SVal ProgramState::getRawSVal(Loc LV, QualType T) const {
824 return getStateManager().StoreMgr->getBinding(getStore(), LV, T);
825}
826
827inline SVal ProgramState::getSVal(const MemRegion* R, QualType T) const {
828 return getStateManager().StoreMgr->getBinding(getStore(),
829 loc::MemRegionVal(R),
830 T);
831}
832
833inline BasicValueFactory &ProgramState::getBasicVals() const {
834 return getStateManager().getBasicVals();
835}
836
837inline SymbolManager &ProgramState::getSymbolManager() const {
838 return getStateManager().getSymbolManager();
839}
840
841template<typename T>
842ProgramStateRef ProgramState::add(typename ProgramStateTrait<T>::key_type K) const {
843 return getStateManager().add<T>(this, K, get_context<T>());
844}
845
846template <typename T>
847typename ProgramStateTrait<T>::context_type ProgramState::get_context() const {
848 return getStateManager().get_context<T>();
849}
850
851template<typename T>
852ProgramStateRef ProgramState::remove(typename ProgramStateTrait<T>::key_type K) const {
853 return getStateManager().remove<T>(this, K, get_context<T>());
854}
855
856template<typename T>
857ProgramStateRef ProgramState::remove(typename ProgramStateTrait<T>::key_type K,
858 typename ProgramStateTrait<T>::context_type C) const {
859 return getStateManager().remove<T>(this, K, C);
860}
861
862template <typename T>
863ProgramStateRef ProgramState::remove() const {
864 return getStateManager().remove<T>(this);
865}
866
867template<typename T>
868ProgramStateRef ProgramState::set(typename ProgramStateTrait<T>::data_type D) const {
869 return getStateManager().set<T>(this, D);
870}
871
872template<typename T>
873ProgramStateRef ProgramState::set(typename ProgramStateTrait<T>::key_type K,
874 typename ProgramStateTrait<T>::value_type E) const {
875 return getStateManager().set<T>(this, K, E, get_context<T>());
876}
877
878template<typename T>
879ProgramStateRef ProgramState::set(typename ProgramStateTrait<T>::key_type K,
880 typename ProgramStateTrait<T>::value_type E,
881 typename ProgramStateTrait<T>::context_type C) const {
882 return getStateManager().set<T>(this, K, E, C);
883}
884
885template <typename CB>
886CB ProgramState::scanReachableSymbols(SVal val) const {
887 CB cb(this);
888 scanReachableSymbols(val, cb);
889 return cb;
890}
891
892template <typename CB>
893CB ProgramState::scanReachableSymbols(
894 llvm::iterator_range<region_iterator> Reachable) const {
895 CB cb(this);
896 scanReachableSymbols(Reachable, cb);
897 return cb;
898}
899
900/// \class ScanReachableSymbols
901/// A utility class that visits the reachable symbols using a custom
902/// SymbolVisitor. Terminates recursive traversal when the visitor function
903/// returns false.
904class ScanReachableSymbols {
905 typedef llvm::DenseSet<const void*> VisitedItems;
906
907 VisitedItems visited;
908 ProgramStateRef state;
909 SymbolVisitor &visitor;
910public:
911 ScanReachableSymbols(ProgramStateRef st, SymbolVisitor &v)
912 : state(std::move(st)), visitor(v) {}
913
914 bool scan(nonloc::LazyCompoundVal val);
915 bool scan(nonloc::CompoundVal val);
916 bool scan(SVal val);
917 bool scan(const MemRegion *R);
918 bool scan(const SymExpr *sym);
919};
920
921} // end ento namespace
922
923} // end clang namespace
924
925#endif

/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/llvm/include/llvm/ADT/IntrusiveRefCntPtr.h

1//==- llvm/ADT/IntrusiveRefCntPtr.h - Smart Refcounting Pointer --*- C++ -*-==//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8///
9/// \file
10/// This file defines the RefCountedBase, ThreadSafeRefCountedBase, and
11/// IntrusiveRefCntPtr classes.
12///
13/// IntrusiveRefCntPtr is a smart pointer to an object which maintains a
14/// reference count. (ThreadSafe)RefCountedBase is a mixin class that adds a
15/// refcount member variable and methods for updating the refcount. An object
16/// that inherits from (ThreadSafe)RefCountedBase deletes itself when its
17/// refcount hits zero.
18///
19/// For example:
20///
21/// ```
22/// class MyClass : public RefCountedBase<MyClass> {};
23///
24/// void foo() {
25/// // Constructing an IntrusiveRefCntPtr increases the pointee's refcount
26/// // by 1 (from 0 in this case).
27/// IntrusiveRefCntPtr<MyClass> Ptr1(new MyClass());
28///
29/// // Copying an IntrusiveRefCntPtr increases the pointee's refcount by 1.
30/// IntrusiveRefCntPtr<MyClass> Ptr2(Ptr1);
31///
32/// // Constructing an IntrusiveRefCntPtr has no effect on the object's
33/// // refcount. After a move, the moved-from pointer is null.
34/// IntrusiveRefCntPtr<MyClass> Ptr3(std::move(Ptr1));
35/// assert(Ptr1 == nullptr);
36///
37/// // Clearing an IntrusiveRefCntPtr decreases the pointee's refcount by 1.
38/// Ptr2.reset();
39///
40/// // The object deletes itself when we return from the function, because
41/// // Ptr3's destructor decrements its refcount to 0.
42/// }
43/// ```
44///
45/// You can use IntrusiveRefCntPtr with isa<T>(), dyn_cast<T>(), etc.:
46///
47/// ```
48/// IntrusiveRefCntPtr<MyClass> Ptr(new MyClass());
49/// OtherClass *Other = dyn_cast<OtherClass>(Ptr); // Ptr.get() not required
50/// ```
51///
52/// IntrusiveRefCntPtr works with any class that
53///
54/// - inherits from (ThreadSafe)RefCountedBase,
55/// - has Retain() and Release() methods, or
56/// - specializes IntrusiveRefCntPtrInfo.
57///
58//===----------------------------------------------------------------------===//
59
60#ifndef LLVM_ADT_INTRUSIVEREFCNTPTR_H
61#define LLVM_ADT_INTRUSIVEREFCNTPTR_H
62
63#include <atomic>
64#include <cassert>
65#include <cstddef>
66#include <memory>
67
68namespace llvm {
69
70/// A CRTP mixin class that adds reference counting to a type.
71///
72/// The lifetime of an object which inherits from RefCountedBase is managed by
73/// calls to Release() and Retain(), which increment and decrement the object's
74/// refcount, respectively. When a Release() call decrements the refcount to 0,
75/// the object deletes itself.
76template <class Derived> class RefCountedBase {
77 mutable unsigned RefCount = 0;
78
79protected:
80 RefCountedBase() = default;
81 RefCountedBase(const RefCountedBase &) {}
82 RefCountedBase &operator=(const RefCountedBase &) = delete;
83
84#ifndef NDEBUG
85 ~RefCountedBase() {
86 assert(RefCount == 0 &&(static_cast <bool> (RefCount == 0 && "Destruction occurred when there are still references to this."
) ? void (0) : __assert_fail ("RefCount == 0 && \"Destruction occurred when there are still references to this.\""
, "llvm/include/llvm/ADT/IntrusiveRefCntPtr.h", 87, __extension__
__PRETTY_FUNCTION__))
87 "Destruction occurred when there are still references to this.")(static_cast <bool> (RefCount == 0 && "Destruction occurred when there are still references to this."
) ? void (0) : __assert_fail ("RefCount == 0 && \"Destruction occurred when there are still references to this.\""
, "llvm/include/llvm/ADT/IntrusiveRefCntPtr.h", 87, __extension__
__PRETTY_FUNCTION__))
;
88 }
89#else
90 // Default the destructor in release builds, A trivial destructor may enable
91 // better codegen.
92 ~RefCountedBase() = default;
93#endif
94
95public:
96 void Retain() const { ++RefCount; }
97
98 void Release() const {
99 assert(RefCount > 0 && "Reference count is already zero.")(static_cast <bool> (RefCount > 0 && "Reference count is already zero."
) ? void (0) : __assert_fail ("RefCount > 0 && \"Reference count is already zero.\""
, "llvm/include/llvm/ADT/IntrusiveRefCntPtr.h", 99, __extension__
__PRETTY_FUNCTION__))
;
100 if (--RefCount == 0)
101 delete static_cast<const Derived *>(this);
102 }
103};
104
105/// A thread-safe version of \c RefCountedBase.
106template <class Derived> class ThreadSafeRefCountedBase {
107 mutable std::atomic<int> RefCount{0};
108
109protected:
110 ThreadSafeRefCountedBase() = default;
111 ThreadSafeRefCountedBase(const ThreadSafeRefCountedBase &) {}
112 ThreadSafeRefCountedBase &
113 operator=(const ThreadSafeRefCountedBase &) = delete;
114
115#ifndef NDEBUG
116 ~ThreadSafeRefCountedBase() {
117 assert(RefCount == 0 &&(static_cast <bool> (RefCount == 0 && "Destruction occurred when there are still references to this."
) ? void (0) : __assert_fail ("RefCount == 0 && \"Destruction occurred when there are still references to this.\""
, "llvm/include/llvm/ADT/IntrusiveRefCntPtr.h", 118, __extension__
__PRETTY_FUNCTION__))
118 "Destruction occurred when there are still references to this.")(static_cast <bool> (RefCount == 0 && "Destruction occurred when there are still references to this."
) ? void (0) : __assert_fail ("RefCount == 0 && \"Destruction occurred when there are still references to this.\""
, "llvm/include/llvm/ADT/IntrusiveRefCntPtr.h", 118, __extension__
__PRETTY_FUNCTION__))
;
119 }
120#else
121 // Default the destructor in release builds, A trivial destructor may enable
122 // better codegen.
123 ~ThreadSafeRefCountedBase() = default;
124#endif
125
126public:
127 void Retain() const { RefCount.fetch_add(1, std::memory_order_relaxed); }
128
129 void Release() const {
130 int NewRefCount = RefCount.fetch_sub(1, std::memory_order_acq_rel) - 1;
131 assert(NewRefCount >= 0 && "Reference count was already zero.")(static_cast <bool> (NewRefCount >= 0 && "Reference count was already zero."
) ? void (0) : __assert_fail ("NewRefCount >= 0 && \"Reference count was already zero.\""
, "llvm/include/llvm/ADT/IntrusiveRefCntPtr.h", 131, __extension__
__PRETTY_FUNCTION__))
;
132 if (NewRefCount == 0)
133 delete static_cast<const Derived *>(this);
134 }
135};
136
137/// Class you can specialize to provide custom retain/release functionality for
138/// a type.
139///
140/// Usually specializing this class is not necessary, as IntrusiveRefCntPtr
141/// works with any type which defines Retain() and Release() functions -- you
142/// can define those functions yourself if RefCountedBase doesn't work for you.
143///
144/// One case when you might want to specialize this type is if you have
145/// - Foo.h defines type Foo and includes Bar.h, and
146/// - Bar.h uses IntrusiveRefCntPtr<Foo> in inline functions.
147///
148/// Because Foo.h includes Bar.h, Bar.h can't include Foo.h in order to pull in
149/// the declaration of Foo. Without the declaration of Foo, normally Bar.h
150/// wouldn't be able to use IntrusiveRefCntPtr<Foo>, which wants to call
151/// T::Retain and T::Release.
152///
153/// To resolve this, Bar.h could include a third header, FooFwd.h, which
154/// forward-declares Foo and specializes IntrusiveRefCntPtrInfo<Foo>. Then
155/// Bar.h could use IntrusiveRefCntPtr<Foo>, although it still couldn't call any
156/// functions on Foo itself, because Foo would be an incomplete type.
157template <typename T> struct IntrusiveRefCntPtrInfo {
158 static void retain(T *obj) { obj->Retain(); }
159 static void release(T *obj) { obj->Release(); }
160};
161
162/// A smart pointer to a reference-counted object that inherits from
163/// RefCountedBase or ThreadSafeRefCountedBase.
164///
165/// This class increments its pointee's reference count when it is created, and
166/// decrements its refcount when it's destroyed (or is changed to point to a
167/// different object).
168template <typename T> class IntrusiveRefCntPtr {
169 T *Obj = nullptr;
170
171public:
172 using element_type = T;
173
174 explicit IntrusiveRefCntPtr() = default;
175 IntrusiveRefCntPtr(T *obj) : Obj(obj) { retain(); }
176 IntrusiveRefCntPtr(const IntrusiveRefCntPtr &S) : Obj(S.Obj) { retain(); }
177 IntrusiveRefCntPtr(IntrusiveRefCntPtr &&S) : Obj(S.Obj) { S.Obj = nullptr; }
178
179 template <class X,
180 std::enable_if_t<std::is_convertible<X *, T *>::value, bool> = true>
181 IntrusiveRefCntPtr(IntrusiveRefCntPtr<X> S) : Obj(S.get()) {
182 S.Obj = nullptr;
183 }
184
185 template <class X,
186 std::enable_if_t<std::is_convertible<X *, T *>::value, bool> = true>
187 IntrusiveRefCntPtr(std::unique_ptr<X> S) : Obj(S.release()) {
188 retain();
189 }
190
191 ~IntrusiveRefCntPtr() { release(); }
192
193 IntrusiveRefCntPtr &operator=(IntrusiveRefCntPtr S) {
194 swap(S);
23
Calling 'IntrusiveRefCntPtr::swap'
26
Returning from 'IntrusiveRefCntPtr::swap'
195 return *this;
196 }
197
198 T &operator*() const { return *Obj; }
199 T *operator->() const { return Obj; }
200 T *get() const { return Obj; }
201 explicit operator bool() const { return Obj; }
202
203 void swap(IntrusiveRefCntPtr &other) {
204 T *tmp = other.Obj;
24
'tmp' initialized here
205 other.Obj = Obj;
206 Obj = tmp;
25
The value of 'tmp' is assigned to 'state.Obj'
207 }
208
209 void reset() {
210 release();
211 Obj = nullptr;
212 }
213
214 void resetWithoutRelease() { Obj = nullptr; }
215
216private:
217 void retain() {
218 if (Obj)
219 IntrusiveRefCntPtrInfo<T>::retain(Obj);
220 }
221
222 void release() {
223 if (Obj)
224 IntrusiveRefCntPtrInfo<T>::release(Obj);
225 }
226
227 template <typename X> friend class IntrusiveRefCntPtr;
228};
229
230template <class T, class U>
231inline bool operator==(const IntrusiveRefCntPtr<T> &A,
232 const IntrusiveRefCntPtr<U> &B) {
233 return A.get() == B.get();
234}
235
236template <class T, class U>
237inline bool operator!=(const IntrusiveRefCntPtr<T> &A,
238 const IntrusiveRefCntPtr<U> &B) {
239 return A.get() != B.get();
240}
241
242template <class T, class U>
243inline bool operator==(const IntrusiveRefCntPtr<T> &A, U *B) {
244 return A.get() == B;
245}
246
247template <class T, class U>
248inline bool operator!=(const IntrusiveRefCntPtr<T> &A, U *B) {
249 return A.get() != B;
250}
251
252template <class T, class U>
253inline bool operator==(T *A, const IntrusiveRefCntPtr<U> &B) {
254 return A == B.get();
255}
256
257template <class T, class U>
258inline bool operator!=(T *A, const IntrusiveRefCntPtr<U> &B) {
259 return A != B.get();
260}
261
262template <class T>
263bool operator==(std::nullptr_t, const IntrusiveRefCntPtr<T> &B) {
264 return !B;
265}
266
267template <class T>
268bool operator==(const IntrusiveRefCntPtr<T> &A, std::nullptr_t B) {
269 return B == A;
270}
271
272template <class T>
273bool operator!=(std::nullptr_t A, const IntrusiveRefCntPtr<T> &B) {
274 return !(A == B);
275}
276
277template <class T>
278bool operator!=(const IntrusiveRefCntPtr<T> &A, std::nullptr_t B) {
279 return !(A == B);
280}
281
282// Make IntrusiveRefCntPtr work with dyn_cast, isa, and the other idioms from
283// Casting.h.
284template <typename From> struct simplify_type;
285
286template <class T> struct simplify_type<IntrusiveRefCntPtr<T>> {
287 using SimpleType = T *;
288
289 static SimpleType getSimplifiedValue(IntrusiveRefCntPtr<T> &Val) {
290 return Val.get();
291 }
292};
293
294template <class T> struct simplify_type<const IntrusiveRefCntPtr<T>> {
295 using SimpleType = /*const*/ T *;
296
297 static SimpleType getSimplifiedValue(const IntrusiveRefCntPtr<T> &Val) {
298 return Val.get();
299 }
300};
301
302/// Factory function for creating intrusive ref counted pointers.
303template <typename T, typename... Args>
304IntrusiveRefCntPtr<T> makeIntrusiveRefCnt(Args &&...A) {
305 return IntrusiveRefCntPtr<T>(new T(std::forward<Args>(A)...));
306}
307
308} // end namespace llvm
309
310#endif // LLVM_ADT_INTRUSIVEREFCNTPTR_H