Bug Summary

File:clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
Warning:line 1454, 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-store=region -analyzer-opt-analyze-nested-blocks -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-14~++20220118101002+ec47dba1c8a2/build-llvm -resource-dir /usr/lib/llvm-14/lib/clang/14.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-14~++20220118101002+ec47dba1c8a2/clang/lib/StaticAnalyzer/Checkers -I /build/llvm-toolchain-snapshot-14~++20220118101002+ec47dba1c8a2/clang/include -I tools/clang/include -I include -I /build/llvm-toolchain-snapshot-14~++20220118101002+ec47dba1c8a2/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-14/lib/clang/14.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-14~++20220118101002+ec47dba1c8a2/build-llvm=build-llvm -fmacro-prefix-map=/build/llvm-toolchain-snapshot-14~++20220118101002+ec47dba1c8a2/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-14~++20220118101002+ec47dba1c8a2/build-llvm=build-llvm -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-14~++20220118101002+ec47dba1c8a2/= -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 -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-14~++20220118101002+ec47dba1c8a2/build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20220118101002+ec47dba1c8a2/build-llvm=build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20220118101002+ec47dba1c8a2/= -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-01-19-001817-16337-1 -x c++ /build/llvm-toolchain-snapshot-14~++20220118101002+ec47dba1c8a2/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp

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

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

/usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/tuple

1// <tuple> -*- C++ -*-
2
3// Copyright (C) 2007-2020 Free Software Foundation, Inc.
4//
5// This file is part of the GNU ISO C++ Library. This library is free
6// software; you can redistribute it and/or modify it under the
7// terms of the GNU General Public License as published by the
8// Free Software Foundation; either version 3, or (at your option)
9// any later version.
10
11// This library is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14// GNU General Public License for more details.
15
16// Under Section 7 of GPL version 3, you are granted additional
17// permissions described in the GCC Runtime Library Exception, version
18// 3.1, as published by the Free Software Foundation.
19
20// You should have received a copy of the GNU General Public License and
21// a copy of the GCC Runtime Library Exception along with this program;
22// see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
23// <http://www.gnu.org/licenses/>.
24
25/** @file include/tuple
26 * This is a Standard C++ Library header.
27 */
28
29#ifndef _GLIBCXX_TUPLE1
30#define _GLIBCXX_TUPLE1 1
31
32#pragma GCC system_header
33
34#if __cplusplus201402L < 201103L
35# include <bits/c++0x_warning.h>
36#else
37
38#include <utility>
39#include <array>
40#include <bits/uses_allocator.h>
41#include <bits/invoke.h>
42#if __cplusplus201402L > 201703L
43# include <compare>
44# define __cpp_lib_constexpr_tuple 201811L
45#endif
46
47namespace std _GLIBCXX_VISIBILITY(default)__attribute__ ((__visibility__ ("default")))
48{
49_GLIBCXX_BEGIN_NAMESPACE_VERSION
50
51 /**
52 * @addtogroup utilities
53 * @{
54 */
55
56 template<typename... _Elements>
57 class tuple;
58
59 template<typename _Tp>
60 struct __is_empty_non_tuple : is_empty<_Tp> { };
61
62 // Using EBO for elements that are tuples causes ambiguous base errors.
63 template<typename _El0, typename... _El>
64 struct __is_empty_non_tuple<tuple<_El0, _El...>> : false_type { };
65
66 // Use the Empty Base-class Optimization for empty, non-final types.
67 template<typename _Tp>
68 using __empty_not_final
69 = typename conditional<__is_final(_Tp), false_type,
70 __is_empty_non_tuple<_Tp>>::type;
71
72 template<std::size_t _Idx, typename _Head,
73 bool = __empty_not_final<_Head>::value>
74 struct _Head_base;
75
76 template<std::size_t _Idx, typename _Head>
77 struct _Head_base<_Idx, _Head, true>
78 : public _Head
79 {
80 constexpr _Head_base()
81 : _Head() { }
82
83 constexpr _Head_base(const _Head& __h)
84 : _Head(__h) { }
85
86 constexpr _Head_base(const _Head_base&) = default;
87 constexpr _Head_base(_Head_base&&) = default;
88
89 template<typename _UHead>
90 constexpr _Head_base(_UHead&& __h)
91 : _Head(std::forward<_UHead>(__h)) { }
92
93 _Head_base(allocator_arg_t, __uses_alloc0)
94 : _Head() { }
95
96 template<typename _Alloc>
97 _Head_base(allocator_arg_t, __uses_alloc1<_Alloc> __a)
98 : _Head(allocator_arg, *__a._M_a) { }
99
100 template<typename _Alloc>
101 _Head_base(allocator_arg_t, __uses_alloc2<_Alloc> __a)
102 : _Head(*__a._M_a) { }
103
104 template<typename _UHead>
105 _Head_base(__uses_alloc0, _UHead&& __uhead)
106 : _Head(std::forward<_UHead>(__uhead)) { }
107
108 template<typename _Alloc, typename _UHead>
109 _Head_base(__uses_alloc1<_Alloc> __a, _UHead&& __uhead)
110 : _Head(allocator_arg, *__a._M_a, std::forward<_UHead>(__uhead)) { }
111
112 template<typename _Alloc, typename _UHead>
113 _Head_base(__uses_alloc2<_Alloc> __a, _UHead&& __uhead)
114 : _Head(std::forward<_UHead>(__uhead), *__a._M_a) { }
115
116 static constexpr _Head&
117 _M_head(_Head_base& __b) noexcept { return __b; }
118
119 static constexpr const _Head&
120 _M_head(const _Head_base& __b) noexcept { return __b; }
121 };
122
123 template<std::size_t _Idx, typename _Head>
124 struct _Head_base<_Idx, _Head, false>
125 {
126 constexpr _Head_base()
127 : _M_head_impl() { }
128
129 constexpr _Head_base(const _Head& __h)
130 : _M_head_impl(__h) { }
131
132 constexpr _Head_base(const _Head_base&) = default;
133 constexpr _Head_base(_Head_base&&) = default;
134
135 template<typename _UHead>
136 constexpr _Head_base(_UHead&& __h)
137 : _M_head_impl(std::forward<_UHead>(__h)) { }
138
139 _GLIBCXX20_CONSTEXPR
140 _Head_base(allocator_arg_t, __uses_alloc0)
141 : _M_head_impl() { }
142
143 template<typename _Alloc>
144 _Head_base(allocator_arg_t, __uses_alloc1<_Alloc> __a)
145 : _M_head_impl(allocator_arg, *__a._M_a) { }
146
147 template<typename _Alloc>
148 _Head_base(allocator_arg_t, __uses_alloc2<_Alloc> __a)
149 : _M_head_impl(*__a._M_a) { }
150
151 template<typename _UHead>
152 _GLIBCXX20_CONSTEXPR
153 _Head_base(__uses_alloc0, _UHead&& __uhead)
154 : _M_head_impl(std::forward<_UHead>(__uhead)) { }
155
156 template<typename _Alloc, typename _UHead>
157 _Head_base(__uses_alloc1<_Alloc> __a, _UHead&& __uhead)
158 : _M_head_impl(allocator_arg, *__a._M_a, std::forward<_UHead>(__uhead))
159 { }
160
161 template<typename _Alloc, typename _UHead>
162 _Head_base(__uses_alloc2<_Alloc> __a, _UHead&& __uhead)
163 : _M_head_impl(std::forward<_UHead>(__uhead), *__a._M_a) { }
164
165 static constexpr _Head&
166 _M_head(_Head_base& __b) noexcept { return __b._M_head_impl; }
167
168 static constexpr const _Head&
169 _M_head(const _Head_base& __b) noexcept { return __b._M_head_impl; }
170
171 _Head _M_head_impl;
172 };
173
174 /**
175 * Contains the actual implementation of the @c tuple template, stored
176 * as a recursive inheritance hierarchy from the first element (most
177 * derived class) to the last (least derived class). The @c Idx
178 * parameter gives the 0-based index of the element stored at this
179 * point in the hierarchy; we use it to implement a constant-time
180 * get() operation.
181 */
182 template<std::size_t _Idx, typename... _Elements>
183 struct _Tuple_impl;
184
185 /**
186 * Recursive tuple implementation. Here we store the @c Head element
187 * and derive from a @c Tuple_impl containing the remaining elements
188 * (which contains the @c Tail).
189 */
190 template<std::size_t _Idx, typename _Head, typename... _Tail>
191 struct _Tuple_impl<_Idx, _Head, _Tail...>
192 : public _Tuple_impl<_Idx + 1, _Tail...>,
193 private _Head_base<_Idx, _Head>
194 {
195 template<std::size_t, typename...> friend class _Tuple_impl;
196
197 typedef _Tuple_impl<_Idx + 1, _Tail...> _Inherited;
198 typedef _Head_base<_Idx, _Head> _Base;
199
200 static constexpr _Head&
201 _M_head(_Tuple_impl& __t) noexcept { return _Base::_M_head(__t); }
202
203 static constexpr const _Head&
204 _M_head(const _Tuple_impl& __t) noexcept { return _Base::_M_head(__t); }
205
206 static constexpr _Inherited&
207 _M_tail(_Tuple_impl& __t) noexcept { return __t; }
208
209 static constexpr const _Inherited&
210 _M_tail(const _Tuple_impl& __t) noexcept { return __t; }
211
212 constexpr _Tuple_impl()
213 : _Inherited(), _Base() { }
214
215 explicit
216 constexpr _Tuple_impl(const _Head& __head, const _Tail&... __tail)
217 : _Inherited(__tail...), _Base(__head) { }
12
Calling constructor for '_Tuple_impl<1UL, llvm::IntrusiveRefCntPtr<const clang::ento::ProgramState> &>'
15
Returning from constructor for '_Tuple_impl<1UL, llvm::IntrusiveRefCntPtr<const clang::ento::ProgramState> &>'
218
219 template<typename _UHead, typename... _UTail, typename = typename
220 enable_if<sizeof...(_Tail) == sizeof...(_UTail)>::type>
221 explicit
222 constexpr _Tuple_impl(_UHead&& __head, _UTail&&... __tail)
223 : _Inherited(std::forward<_UTail>(__tail)...),
224 _Base(std::forward<_UHead>(__head)) { }
225
226 constexpr _Tuple_impl(const _Tuple_impl&) = default;
227
228 // _GLIBCXX_RESOLVE_LIB_DEFECTS
229 // 2729. Missing SFINAE on std::pair::operator=
230 _Tuple_impl& operator=(const _Tuple_impl&) = delete;
231
232 constexpr
233 _Tuple_impl(_Tuple_impl&& __in)
234 noexcept(__and_<is_nothrow_move_constructible<_Head>,
235 is_nothrow_move_constructible<_Inherited>>::value)
236 : _Inherited(std::move(_M_tail(__in))),
237 _Base(std::forward<_Head>(_M_head(__in))) { }
238
239 template<typename... _UElements>
240 constexpr _Tuple_impl(const _Tuple_impl<_Idx, _UElements...>& __in)
241 : _Inherited(_Tuple_impl<_Idx, _UElements...>::_M_tail(__in)),
242 _Base(_Tuple_impl<_Idx, _UElements...>::_M_head(__in)) { }
243
244 template<typename _UHead, typename... _UTails>
245 constexpr _Tuple_impl(_Tuple_impl<_Idx, _UHead, _UTails...>&& __in)
246 : _Inherited(std::move
247 (_Tuple_impl<_Idx, _UHead, _UTails...>::_M_tail(__in))),
248 _Base(std::forward<_UHead>
249 (_Tuple_impl<_Idx, _UHead, _UTails...>::_M_head(__in))) { }
250
251 template<typename _Alloc>
252 _GLIBCXX20_CONSTEXPR
253 _Tuple_impl(allocator_arg_t __tag, const _Alloc& __a)
254 : _Inherited(__tag, __a),
255 _Base(__tag, __use_alloc<_Head>(__a)) { }
256
257 template<typename _Alloc>
258 _Tuple_impl(allocator_arg_t __tag, const _Alloc& __a,
259 const _Head& __head, const _Tail&... __tail)
260 : _Inherited(__tag, __a, __tail...),
261 _Base(__use_alloc<_Head, _Alloc, _Head>(__a), __head) { }
262
263 template<typename _Alloc, typename _UHead, typename... _UTail,
264 typename = typename enable_if<sizeof...(_Tail)
265 == sizeof...(_UTail)>::type>
266 _GLIBCXX20_CONSTEXPR
267 _Tuple_impl(allocator_arg_t __tag, const _Alloc& __a,
268 _UHead&& __head, _UTail&&... __tail)
269 : _Inherited(__tag, __a, std::forward<_UTail>(__tail)...),
270 _Base(__use_alloc<_Head, _Alloc, _UHead>(__a),
271 std::forward<_UHead>(__head)) { }
272
273 template<typename _Alloc>
274 _GLIBCXX20_CONSTEXPR
275 _Tuple_impl(allocator_arg_t __tag, const _Alloc& __a,
276 const _Tuple_impl& __in)
277 : _Inherited(__tag, __a, _M_tail(__in)),
278 _Base(__use_alloc<_Head, _Alloc, _Head>(__a), _M_head(__in)) { }
279
280 template<typename _Alloc>
281 _GLIBCXX20_CONSTEXPR
282 _Tuple_impl(allocator_arg_t __tag, const _Alloc& __a,
283 _Tuple_impl&& __in)
284 : _Inherited(__tag, __a, std::move(_M_tail(__in))),
285 _Base(__use_alloc<_Head, _Alloc, _Head>(__a),
286 std::forward<_Head>(_M_head(__in))) { }
287
288 template<typename _Alloc, typename _UHead, typename... _UTails>
289 _GLIBCXX20_CONSTEXPR
290 _Tuple_impl(allocator_arg_t __tag, const _Alloc& __a,
291 const _Tuple_impl<_Idx, _UHead, _UTails...>& __in)
292 : _Inherited(__tag, __a,
293 _Tuple_impl<_Idx, _UHead, _UTails...>::_M_tail(__in)),
294 _Base(__use_alloc<_Head, _Alloc, const _UHead&>(__a),
295 _Tuple_impl<_Idx, _UHead, _UTails...>::_M_head(__in)) { }
296
297 template<typename _Alloc, typename _UHead, typename... _UTails>
298 _GLIBCXX20_CONSTEXPR
299 _Tuple_impl(allocator_arg_t __tag, const _Alloc& __a,
300 _Tuple_impl<_Idx, _UHead, _UTails...>&& __in)
301 : _Inherited(__tag, __a, std::move
302 (_Tuple_impl<_Idx, _UHead, _UTails...>::_M_tail(__in))),
303 _Base(__use_alloc<_Head, _Alloc, _UHead>(__a),
304 std::forward<_UHead>
305 (_Tuple_impl<_Idx, _UHead, _UTails...>::_M_head(__in))) { }
306
307 template<typename... _UElements>
308 _GLIBCXX20_CONSTEXPR
309 void
310 _M_assign(const _Tuple_impl<_Idx, _UElements...>& __in)
311 {
312 _M_head(*this) = _Tuple_impl<_Idx, _UElements...>::_M_head(__in);
313 _M_tail(*this)._M_assign(
314 _Tuple_impl<_Idx, _UElements...>::_M_tail(__in));
315 }
316
317 template<typename _UHead, typename... _UTails>
318 _GLIBCXX20_CONSTEXPR
319 void
320 _M_assign(_Tuple_impl<_Idx, _UHead, _UTails...>&& __in)
321 {
322 _M_head(*this) = std::forward<_UHead>
323 (_Tuple_impl<_Idx, _UHead, _UTails...>::_M_head(__in));
324 _M_tail(*this)._M_assign(
325 std::move(_Tuple_impl<_Idx, _UHead, _UTails...>::_M_tail(__in)));
326 }
327
328 protected:
329 _GLIBCXX20_CONSTEXPR
330 void
331 _M_swap(_Tuple_impl& __in)
332 {
333 using std::swap;
334 swap(_M_head(*this), _M_head(__in));
335 _Inherited::_M_swap(_M_tail(__in));
336 }
337 };
338
339 // Basis case of inheritance recursion.
340 template<std::size_t _Idx, typename _Head>
341 struct _Tuple_impl<_Idx, _Head>
342 : private _Head_base<_Idx, _Head>
343 {
344 template<std::size_t, typename...> friend class _Tuple_impl;
345
346 typedef _Head_base<_Idx, _Head> _Base;
347
348 static constexpr _Head&
349 _M_head(_Tuple_impl& __t) noexcept { return _Base::_M_head(__t); }
350
351 static constexpr const _Head&
352 _M_head(const _Tuple_impl& __t) noexcept { return _Base::_M_head(__t); }
353
354 constexpr _Tuple_impl()
355 : _Base() { }
356
357 explicit
358 constexpr _Tuple_impl(const _Head& __head)
359 : _Base(__head) { }
13
Calling constructor for '_Head_base<1UL, llvm::IntrusiveRefCntPtr<const clang::ento::ProgramState> &, false>'
14
Returning from constructor for '_Head_base<1UL, llvm::IntrusiveRefCntPtr<const clang::ento::ProgramState> &, false>'
360
361 template<typename _UHead>
362 explicit
363 constexpr _Tuple_impl(_UHead&& __head)
364 : _Base(std::forward<_UHead>(__head)) { }
365
366 constexpr _Tuple_impl(const _Tuple_impl&) = default;
367
368 // _GLIBCXX_RESOLVE_LIB_DEFECTS
369 // 2729. Missing SFINAE on std::pair::operator=
370 _Tuple_impl& operator=(const _Tuple_impl&) = delete;
371
372 constexpr
373 _Tuple_impl(_Tuple_impl&& __in)
374 noexcept(is_nothrow_move_constructible<_Head>::value)
375 : _Base(std::forward<_Head>(_M_head(__in))) { }
376
377 template<typename _UHead>
378 constexpr _Tuple_impl(const _Tuple_impl<_Idx, _UHead>& __in)
379 : _Base(_Tuple_impl<_Idx, _UHead>::_M_head(__in)) { }
380
381 template<typename _UHead>
382 constexpr _Tuple_impl(_Tuple_impl<_Idx, _UHead>&& __in)
383 : _Base(std::forward<_UHead>(_Tuple_impl<_Idx, _UHead>::_M_head(__in)))
384 { }
385
386 template<typename _Alloc>
387 _GLIBCXX20_CONSTEXPR
388 _Tuple_impl(allocator_arg_t __tag, const _Alloc& __a)
389 : _Base(__tag, __use_alloc<_Head>(__a)) { }
390
391 template<typename _Alloc>
392 _Tuple_impl(allocator_arg_t __tag, const _Alloc& __a,
393 const _Head& __head)
394 : _Base(__use_alloc<_Head, _Alloc, _Head>(__a), __head) { }
395
396 template<typename _Alloc, typename _UHead>
397 _GLIBCXX20_CONSTEXPR
398 _Tuple_impl(allocator_arg_t __tag, const _Alloc& __a,
399 _UHead&& __head)
400 : _Base(__use_alloc<_Head, _Alloc, _UHead>(__a),
401 std::forward<_UHead>(__head)) { }
402
403 template<typename _Alloc>
404 _GLIBCXX20_CONSTEXPR
405 _Tuple_impl(allocator_arg_t __tag, const _Alloc& __a,
406 const _Tuple_impl& __in)
407 : _Base(__use_alloc<_Head, _Alloc, _Head>(__a), _M_head(__in)) { }
408
409 template<typename _Alloc>
410 _GLIBCXX20_CONSTEXPR
411 _Tuple_impl(allocator_arg_t __tag, const _Alloc& __a,
412 _Tuple_impl&& __in)
413 : _Base(__use_alloc<_Head, _Alloc, _Head>(__a),
414 std::forward<_Head>(_M_head(__in))) { }
415
416 template<typename _Alloc, typename _UHead>
417 _GLIBCXX20_CONSTEXPR
418 _Tuple_impl(allocator_arg_t __tag, const _Alloc& __a,
419 const _Tuple_impl<_Idx, _UHead>& __in)
420 : _Base(__use_alloc<_Head, _Alloc, const _UHead&>(__a),
421 _Tuple_impl<_Idx, _UHead>::_M_head(__in)) { }
422
423 template<typename _Alloc, typename _UHead>
424 _GLIBCXX20_CONSTEXPR
425 _Tuple_impl(allocator_arg_t __tag, const _Alloc& __a,
426 _Tuple_impl<_Idx, _UHead>&& __in)
427 : _Base(__use_alloc<_Head, _Alloc, _UHead>(__a),
428 std::forward<_UHead>(_Tuple_impl<_Idx, _UHead>::_M_head(__in)))
429 { }
430
431 template<typename _UHead>
432 _GLIBCXX20_CONSTEXPR
433 void
434 _M_assign(const _Tuple_impl<_Idx, _UHead>& __in)
435 {
436 _M_head(*this) = _Tuple_impl<_Idx, _UHead>::_M_head(__in);
437 }
438
439 template<typename _UHead>
440 _GLIBCXX20_CONSTEXPR
441 void
442 _M_assign(_Tuple_impl<_Idx, _UHead>&& __in)
443 {
444 _M_head(*this)
445 = std::forward<_UHead>(_Tuple_impl<_Idx, _UHead>::_M_head(__in));
446 }
447
448 protected:
449 _GLIBCXX20_CONSTEXPR
450 void
451 _M_swap(_Tuple_impl& __in)
452 {
453 using std::swap;
454 swap(_M_head(*this), _M_head(__in));
455 }
456 };
457
458 // Concept utility functions, reused in conditionally-explicit
459 // constructors.
460 template<bool, typename... _Types>
461 struct _TupleConstraints
462 {
463 // Constraint for a non-explicit constructor.
464 // True iff each Ti in _Types... can be constructed from Ui in _UTypes...
465 // and every Ui is implicitly convertible to Ti.
466 template<typename... _UTypes>
467 static constexpr bool __is_implicitly_constructible()
468 {
469 return __and_<is_constructible<_Types, _UTypes>...,
470 is_convertible<_UTypes, _Types>...
471 >::value;
472 }
473
474 // Constraint for a non-explicit constructor.
475 // True iff each Ti in _Types... can be constructed from Ui in _UTypes...
476 // but not every Ui is implicitly convertible to Ti.
477 template<typename... _UTypes>
478 static constexpr bool __is_explicitly_constructible()
479 {
480 return __and_<is_constructible<_Types, _UTypes>...,
481 __not_<__and_<is_convertible<_UTypes, _Types>...>>
482 >::value;
483 }
484
485 static constexpr bool __is_implicitly_default_constructible()
486 {
487 return __and_<std::__is_implicitly_default_constructible<_Types>...
488 >::value;
489 }
490
491 static constexpr bool __is_explicitly_default_constructible()
492 {
493 return __and_<is_default_constructible<_Types>...,
494 __not_<__and_<
495 std::__is_implicitly_default_constructible<_Types>...>
496 >>::value;
497 }
498 };
499
500 // Partial specialization used when a required precondition isn't met,
501 // e.g. when sizeof...(_Types) != sizeof...(_UTypes).
502 template<typename... _Types>
503 struct _TupleConstraints<false, _Types...>
504 {
505 template<typename... _UTypes>
506 static constexpr bool __is_implicitly_constructible()
507 { return false; }
508
509 template<typename... _UTypes>
510 static constexpr bool __is_explicitly_constructible()
511 { return false; }
512 };
513
514 /// Primary class template, tuple
515 template<typename... _Elements>
516 class tuple : public _Tuple_impl<0, _Elements...>
517 {
518 typedef _Tuple_impl<0, _Elements...> _Inherited;
519
520 template<bool _Cond>
521 using _TCC = _TupleConstraints<_Cond, _Elements...>;
522
523 // Constraint for non-explicit default constructor
524 template<bool _Dummy>
525 using _ImplicitDefaultCtor = __enable_if_t<
526 _TCC<_Dummy>::__is_implicitly_default_constructible(),
527 bool>;
528
529 // Constraint for explicit default constructor
530 template<bool _Dummy>
531 using _ExplicitDefaultCtor = __enable_if_t<
532 _TCC<_Dummy>::__is_explicitly_default_constructible(),
533 bool>;
534
535 // Constraint for non-explicit constructors
536 template<bool _Cond, typename... _Args>
537 using _ImplicitCtor = __enable_if_t<
538 _TCC<_Cond>::template __is_implicitly_constructible<_Args...>(),
539 bool>;
540
541 // Constraint for non-explicit constructors
542 template<bool _Cond, typename... _Args>
543 using _ExplicitCtor = __enable_if_t<
544 _TCC<_Cond>::template __is_explicitly_constructible<_Args...>(),
545 bool>;
546
547 template<typename... _UElements>
548 static constexpr
549 __enable_if_t<sizeof...(_UElements) == sizeof...(_Elements), bool>
550 __assignable()
551 { return __and_<is_assignable<_Elements&, _UElements>...>::value; }
552
553 // Condition for noexcept-specifier of an assignment operator.
554 template<typename... _UElements>
555 static constexpr bool __nothrow_assignable()
556 {
557 return
558 __and_<is_nothrow_assignable<_Elements&, _UElements>...>::value;
559 }
560
561 // Condition for noexcept-specifier of a constructor.
562 template<typename... _UElements>
563 static constexpr bool __nothrow_constructible()
564 {
565 return
566 __and_<is_nothrow_constructible<_Elements, _UElements>...>::value;
567 }
568
569 // Constraint for tuple(_UTypes&&...) where sizeof...(_UTypes) == 1.
570 template<typename _Up>
571 static constexpr bool __valid_args()
572 {
573 return sizeof...(_Elements) == 1
574 && !is_same<tuple, __remove_cvref_t<_Up>>::value;
575 }
576
577 // Constraint for tuple(_UTypes&&...) where sizeof...(_UTypes) > 1.
578 template<typename, typename, typename... _Tail>
579 static constexpr bool __valid_args()
580 { return (sizeof...(_Tail) + 2) == sizeof...(_Elements); }
581
582 /* Constraint for constructors with a tuple<UTypes...> parameter ensures
583 * that the constructor is only viable when it would not interfere with
584 * tuple(UTypes&&...) or tuple(const tuple&) or tuple(tuple&&).
585 * Such constructors are only viable if:
586 * either sizeof...(Types) != 1,
587 * or (when Types... expands to T and UTypes... expands to U)
588 * is_convertible_v<TUPLE, T>, is_constructible_v<T, TUPLE>,
589 * and is_same_v<T, U> are all false.
590 */
591 template<typename _Tuple, typename = tuple,
592 typename = __remove_cvref_t<_Tuple>>
593 struct _UseOtherCtor
594 : false_type
595 { };
596 // If TUPLE is convertible to the single element in *this,
597 // then TUPLE should match tuple(UTypes&&...) instead.
598 template<typename _Tuple, typename _Tp, typename _Up>
599 struct _UseOtherCtor<_Tuple, tuple<_Tp>, tuple<_Up>>
600 : __or_<is_convertible<_Tuple, _Tp>, is_constructible<_Tp, _Tuple>>
601 { };
602 // If TUPLE and *this each have a single element of the same type,
603 // then TUPLE should match a copy/move constructor instead.
604 template<typename _Tuple, typename _Tp>
605 struct _UseOtherCtor<_Tuple, tuple<_Tp>, tuple<_Tp>>
606 : true_type
607 { };
608
609 // Return true iff sizeof...(Types) == 1 && tuple_size_v<TUPLE> == 1
610 // and the single element in Types can be initialized from TUPLE,
611 // or is the same type as tuple_element_t<0, TUPLE>.
612 template<typename _Tuple>
613 static constexpr bool __use_other_ctor()
614 { return _UseOtherCtor<_Tuple>::value; }
615
616 public:
617 template<typename _Dummy = void,
618 _ImplicitDefaultCtor<is_void<_Dummy>::value> = true>
619 constexpr
620 tuple()
621 noexcept(__and_<is_nothrow_default_constructible<_Elements>...>::value)
622 : _Inherited() { }
623
624 template<typename _Dummy = void,
625 _ExplicitDefaultCtor<is_void<_Dummy>::value> = false>
626 explicit constexpr
627 tuple()
628 noexcept(__and_<is_nothrow_default_constructible<_Elements>...>::value)
629 : _Inherited() { }
630
631 template<bool _NotEmpty = (sizeof...(_Elements) >= 1),
632 _ImplicitCtor<_NotEmpty, const _Elements&...> = true>
633 constexpr
634 tuple(const _Elements&... __elements)
635 noexcept(__nothrow_constructible<const _Elements&...>())
636 : _Inherited(__elements...) { }
637
638 template<bool _NotEmpty = (sizeof...(_Elements) >= 1),
639 _ExplicitCtor<_NotEmpty, const _Elements&...> = false>
640 explicit constexpr
641 tuple(const _Elements&... __elements)
642 noexcept(__nothrow_constructible<const _Elements&...>())
643 : _Inherited(__elements...) { }
644
645 template<typename... _UElements,
646 bool _Valid = __valid_args<_UElements...>(),
647 _ImplicitCtor<_Valid, _UElements...> = true>
648 constexpr
649 tuple(_UElements&&... __elements)
650 noexcept(__nothrow_constructible<_UElements...>())
651 : _Inherited(std::forward<_UElements>(__elements)...) { }
652
653 template<typename... _UElements,
654 bool _Valid = __valid_args<_UElements...>(),
655 _ExplicitCtor<_Valid, _UElements...> = false>
656 explicit constexpr
657 tuple(_UElements&&... __elements)
658 noexcept(__nothrow_constructible<_UElements...>())
659 : _Inherited(std::forward<_UElements>(__elements)...) { }
660
661 constexpr tuple(const tuple&) = default;
662
663 constexpr tuple(tuple&&) = default;
664
665 template<typename... _UElements,
666 bool _Valid = (sizeof...(_Elements) == sizeof...(_UElements))
667 && !__use_other_ctor<const tuple<_UElements...>&>(),
668 _ImplicitCtor<_Valid, const _UElements&...> = true>
669 constexpr
670 tuple(const tuple<_UElements...>& __in)
671 noexcept(__nothrow_constructible<const _UElements&...>())
672 : _Inherited(static_cast<const _Tuple_impl<0, _UElements...>&>(__in))
673 { }
674
675 template<typename... _UElements,
676 bool _Valid = (sizeof...(_Elements) == sizeof...(_UElements))
677 && !__use_other_ctor<const tuple<_UElements...>&>(),
678 _ExplicitCtor<_Valid, const _UElements&...> = false>
679 explicit constexpr
680 tuple(const tuple<_UElements...>& __in)
681 noexcept(__nothrow_constructible<const _UElements&...>())
682 : _Inherited(static_cast<const _Tuple_impl<0, _UElements...>&>(__in))
683 { }
684
685 template<typename... _UElements,
686 bool _Valid = (sizeof...(_Elements) == sizeof...(_UElements))
687 && !__use_other_ctor<tuple<_UElements...>&&>(),
688 _ImplicitCtor<_Valid, _UElements...> = true>
689 constexpr
690 tuple(tuple<_UElements...>&& __in)
691 noexcept(__nothrow_constructible<_UElements...>())
692 : _Inherited(static_cast<_Tuple_impl<0, _UElements...>&&>(__in)) { }
693
694 template<typename... _UElements,
695 bool _Valid = (sizeof...(_Elements) == sizeof...(_UElements))
696 && !__use_other_ctor<tuple<_UElements...>&&>(),
697 _ExplicitCtor<_Valid, _UElements...> = false>
698 explicit constexpr
699 tuple(tuple<_UElements...>&& __in)
700 noexcept(__nothrow_constructible<_UElements...>())
701 : _Inherited(static_cast<_Tuple_impl<0, _UElements...>&&>(__in)) { }
702
703 // Allocator-extended constructors.
704
705 template<typename _Alloc,
706 _ImplicitDefaultCtor<is_object<_Alloc>::value> = true>
707 _GLIBCXX20_CONSTEXPR
708 tuple(allocator_arg_t __tag, const _Alloc& __a)
709 : _Inherited(__tag, __a) { }
710
711 template<typename _Alloc, bool _NotEmpty = (sizeof...(_Elements) >= 1),
712 _ImplicitCtor<_NotEmpty, const _Elements&...> = true>
713 _GLIBCXX20_CONSTEXPR
714 tuple(allocator_arg_t __tag, const _Alloc& __a,
715 const _Elements&... __elements)
716 : _Inherited(__tag, __a, __elements...) { }
717
718 template<typename _Alloc, bool _NotEmpty = (sizeof...(_Elements) >= 1),
719 _ExplicitCtor<_NotEmpty, const _Elements&...> = false>
720 _GLIBCXX20_CONSTEXPR
721 explicit
722 tuple(allocator_arg_t __tag, const _Alloc& __a,
723 const _Elements&... __elements)
724 : _Inherited(__tag, __a, __elements...) { }
725
726 template<typename _Alloc, typename... _UElements,
727 bool _Valid = __valid_args<_UElements...>(),
728 _ImplicitCtor<_Valid, _UElements...> = true>
729 _GLIBCXX20_CONSTEXPR
730 tuple(allocator_arg_t __tag, const _Alloc& __a,
731 _UElements&&... __elements)
732 : _Inherited(__tag, __a, std::forward<_UElements>(__elements)...)
733 { }
734
735 template<typename _Alloc, typename... _UElements,
736 bool _Valid = __valid_args<_UElements...>(),
737 _ExplicitCtor<_Valid, _UElements...> = false>
738 _GLIBCXX20_CONSTEXPR
739 explicit
740 tuple(allocator_arg_t __tag, const _Alloc& __a,
741 _UElements&&... __elements)
742 : _Inherited(__tag, __a, std::forward<_UElements>(__elements)...)
743 { }
744
745 template<typename _Alloc>
746 _GLIBCXX20_CONSTEXPR
747 tuple(allocator_arg_t __tag, const _Alloc& __a, const tuple& __in)
748 : _Inherited(__tag, __a, static_cast<const _Inherited&>(__in)) { }
749
750 template<typename _Alloc>
751 _GLIBCXX20_CONSTEXPR
752 tuple(allocator_arg_t __tag, const _Alloc& __a, tuple&& __in)
753 : _Inherited(__tag, __a, static_cast<_Inherited&&>(__in)) { }
754
755 template<typename _Alloc, typename... _UElements,
756 bool _Valid = (sizeof...(_Elements) == sizeof...(_UElements))
757 && !__use_other_ctor<const tuple<_UElements...>&>(),
758 _ImplicitCtor<_Valid, const _UElements&...> = true>
759 _GLIBCXX20_CONSTEXPR
760 tuple(allocator_arg_t __tag, const _Alloc& __a,
761 const tuple<_UElements...>& __in)
762 : _Inherited(__tag, __a,
763 static_cast<const _Tuple_impl<0, _UElements...>&>(__in))
764 { }
765
766 template<typename _Alloc, typename... _UElements,
767 bool _Valid = (sizeof...(_Elements) == sizeof...(_UElements))
768 && !__use_other_ctor<const tuple<_UElements...>&>(),
769 _ExplicitCtor<_Valid, const _UElements&...> = false>
770 _GLIBCXX20_CONSTEXPR
771 explicit
772 tuple(allocator_arg_t __tag, const _Alloc& __a,
773 const tuple<_UElements...>& __in)
774 : _Inherited(__tag, __a,
775 static_cast<const _Tuple_impl<0, _UElements...>&>(__in))
776 { }
777
778 template<typename _Alloc, typename... _UElements,
779 bool _Valid = (sizeof...(_Elements) == sizeof...(_UElements))
780 && !__use_other_ctor<tuple<_UElements...>&&>(),
781 _ImplicitCtor<_Valid, _UElements...> = true>
782 _GLIBCXX20_CONSTEXPR
783 tuple(allocator_arg_t __tag, const _Alloc& __a,
784 tuple<_UElements...>&& __in)
785 : _Inherited(__tag, __a,
786 static_cast<_Tuple_impl<0, _UElements...>&&>(__in))
787 { }
788
789 template<typename _Alloc, typename... _UElements,
790 bool _Valid = (sizeof...(_Elements) == sizeof...(_UElements))
791 && !__use_other_ctor<tuple<_UElements...>&&>(),
792 _ExplicitCtor<_Valid, _UElements...> = false>
793 _GLIBCXX20_CONSTEXPR
794 explicit
795 tuple(allocator_arg_t __tag, const _Alloc& __a,
796 tuple<_UElements...>&& __in)
797 : _Inherited(__tag, __a,
798 static_cast<_Tuple_impl<0, _UElements...>&&>(__in))
799 { }
800
801 // tuple assignment
802
803 _GLIBCXX20_CONSTEXPR
804 tuple&
805 operator=(typename conditional<__assignable<const _Elements&...>(),
806 const tuple&,
807 const __nonesuch&>::type __in)
808 noexcept(__nothrow_assignable<const _Elements&...>())
809 {
810 this->_M_assign(__in);
811 return *this;
812 }
813
814 _GLIBCXX20_CONSTEXPR
815 tuple&
816 operator=(typename conditional<__assignable<_Elements...>(),
817 tuple&&,
818 __nonesuch&&>::type __in)
819 noexcept(__nothrow_assignable<_Elements...>())
820 {
821 this->_M_assign(std::move(__in));
822 return *this;
823 }
824
825 template<typename... _UElements>
826 _GLIBCXX20_CONSTEXPR
827 __enable_if_t<__assignable<const _UElements&...>(), tuple&>
828 operator=(const tuple<_UElements...>& __in)
829 noexcept(__nothrow_assignable<const _UElements&...>())
830 {
831 this->_M_assign(__in);
832 return *this;
833 }
834
835 template<typename... _UElements>
836 _GLIBCXX20_CONSTEXPR
837 __enable_if_t<__assignable<_UElements...>(), tuple&>
838 operator=(tuple<_UElements...>&& __in)
839 noexcept(__nothrow_assignable<_UElements...>())
840 {
841 this->_M_assign(std::move(__in));
842 return *this;
843 }
844
845 // tuple swap
846 _GLIBCXX20_CONSTEXPR
847 void
848 swap(tuple& __in)
849 noexcept(__and_<__is_nothrow_swappable<_Elements>...>::value)
850 { _Inherited::_M_swap(__in); }
851 };
852
853#if __cpp_deduction_guides >= 201606
854 template<typename... _UTypes>
855 tuple(_UTypes...) -> tuple<_UTypes...>;
856 template<typename _T1, typename _T2>
857 tuple(pair<_T1, _T2>) -> tuple<_T1, _T2>;
858 template<typename _Alloc, typename... _UTypes>
859 tuple(allocator_arg_t, _Alloc, _UTypes...) -> tuple<_UTypes...>;
860 template<typename _Alloc, typename _T1, typename _T2>
861 tuple(allocator_arg_t, _Alloc, pair<_T1, _T2>) -> tuple<_T1, _T2>;
862 template<typename _Alloc, typename... _UTypes>
863 tuple(allocator_arg_t, _Alloc, tuple<_UTypes...>) -> tuple<_UTypes...>;
864#endif
865
866 // Explicit specialization, zero-element tuple.
867 template<>
868 class tuple<>
869 {
870 public:
871 void swap(tuple&) noexcept { /* no-op */ }
872 // We need the default since we're going to define no-op
873 // allocator constructors.
874 tuple() = default;
875 // No-op allocator constructors.
876 template<typename _Alloc>
877 _GLIBCXX20_CONSTEXPR
878 tuple(allocator_arg_t, const _Alloc&) noexcept { }
879 template<typename _Alloc>
880 _GLIBCXX20_CONSTEXPR
881 tuple(allocator_arg_t, const _Alloc&, const tuple&) noexcept { }
882 };
883
884 /// Partial specialization, 2-element tuple.
885 /// Includes construction and assignment from a pair.
886 template<typename _T1, typename _T2>
887 class tuple<_T1, _T2> : public _Tuple_impl<0, _T1, _T2>
888 {
889 typedef _Tuple_impl<0, _T1, _T2> _Inherited;
890
891 // Constraint for non-explicit default constructor
892 template<bool _Dummy, typename _U1, typename _U2>
893 using _ImplicitDefaultCtor = __enable_if_t<
894 _TupleConstraints<_Dummy, _U1, _U2>::
895 __is_implicitly_default_constructible(),
896 bool>;
897
898 // Constraint for explicit default constructor
899 template<bool _Dummy, typename _U1, typename _U2>
900 using _ExplicitDefaultCtor = __enable_if_t<
901 _TupleConstraints<_Dummy, _U1, _U2>::
902 __is_explicitly_default_constructible(),
903 bool>;
904
905 template<bool _Dummy>
906 using _TCC = _TupleConstraints<_Dummy, _T1, _T2>;
907
908 // Constraint for non-explicit constructors
909 template<bool _Cond, typename _U1, typename _U2>
910 using _ImplicitCtor = __enable_if_t<
911 _TCC<_Cond>::template __is_implicitly_constructible<_U1, _U2>(),
912 bool>;
913
914 // Constraint for non-explicit constructors
915 template<bool _Cond, typename _U1, typename _U2>
916 using _ExplicitCtor = __enable_if_t<
917 _TCC<_Cond>::template __is_explicitly_constructible<_U1, _U2>(),
918 bool>;
919
920 template<typename _U1, typename _U2>
921 static constexpr bool __assignable()
922 {
923 return __and_<is_assignable<_T1&, _U1>,
924 is_assignable<_T2&, _U2>>::value;
925 }
926
927 template<typename _U1, typename _U2>
928 static constexpr bool __nothrow_assignable()
929 {
930 return __and_<is_nothrow_assignable<_T1&, _U1>,
931 is_nothrow_assignable<_T2&, _U2>>::value;
932 }
933
934 template<typename _U1, typename _U2>
935 static constexpr bool __nothrow_constructible()
936 {
937 return __and_<is_nothrow_constructible<_T1, _U1>,
938 is_nothrow_constructible<_T2, _U2>>::value;
939 }
940
941 static constexpr bool __nothrow_default_constructible()
942 {
943 return __and_<is_nothrow_default_constructible<_T1>,
944 is_nothrow_default_constructible<_T2>>::value;
945 }
946
947 template<typename _U1>
948 static constexpr bool __is_alloc_arg()
949 { return is_same<__remove_cvref_t<_U1>, allocator_arg_t>::value; }
950
951 public:
952 template<bool _Dummy = true,
953 _ImplicitDefaultCtor<_Dummy, _T1, _T2> = true>
954 constexpr
955 tuple()
956 noexcept(__nothrow_default_constructible())
957 : _Inherited() { }
958
959 template<bool _Dummy = true,
960 _ExplicitDefaultCtor<_Dummy, _T1, _T2> = false>
961 explicit constexpr
962 tuple()
963 noexcept(__nothrow_default_constructible())
964 : _Inherited() { }
965
966 template<bool _Dummy = true,
967 _ImplicitCtor<_Dummy, const _T1&, const _T2&> = true>
968 constexpr
969 tuple(const _T1& __a1, const _T2& __a2)
970 noexcept(__nothrow_constructible<const _T1&, const _T2&>())
971 : _Inherited(__a1, __a2) { }
11
Calling constructor for '_Tuple_impl<0UL, llvm::IntrusiveRefCntPtr<const clang::ento::ProgramState> &, llvm::IntrusiveRefCntPtr<const clang::ento::ProgramState> &>'
16
Returning from constructor for '_Tuple_impl<0UL, llvm::IntrusiveRefCntPtr<const clang::ento::ProgramState> &, llvm::IntrusiveRefCntPtr<const clang::ento::ProgramState> &>'
972
973 template<bool _Dummy = true,
974 _ExplicitCtor<_Dummy, const _T1&, const _T2&> = false>
975 explicit constexpr
976 tuple(const _T1& __a1, const _T2& __a2)
977 noexcept(__nothrow_constructible<const _T1&, const _T2&>())
978 : _Inherited(__a1, __a2) { }
979
980 template<typename _U1, typename _U2,
981 _ImplicitCtor<!__is_alloc_arg<_U1>(), _U1, _U2> = true>
982 constexpr
983 tuple(_U1&& __a1, _U2&& __a2)
984 noexcept(__nothrow_constructible<_U1, _U2>())
985 : _Inherited(std::forward<_U1>(__a1), std::forward<_U2>(__a2)) { }
986
987 template<typename _U1, typename _U2,
988 _ExplicitCtor<!__is_alloc_arg<_U1>(), _U1, _U2> = false>
989 explicit constexpr
990 tuple(_U1&& __a1, _U2&& __a2)
991 noexcept(__nothrow_constructible<_U1, _U2>())
992 : _Inherited(std::forward<_U1>(__a1), std::forward<_U2>(__a2)) { }
993
994 constexpr tuple(const tuple&) = default;
995
996 constexpr tuple(tuple&&) = default;
997
998 template<typename _U1, typename _U2,
999 _ImplicitCtor<true, const _U1&, const _U2&> = true>
1000 constexpr
1001 tuple(const tuple<_U1, _U2>& __in)
1002 noexcept(__nothrow_constructible<const _U1&, const _U2&>())
1003 : _Inherited(static_cast<const _Tuple_impl<0, _U1, _U2>&>(__in)) { }
1004
1005 template<typename _U1, typename _U2,
1006 _ExplicitCtor<true, const _U1&, const _U2&> = false>
1007 explicit constexpr
1008 tuple(const tuple<_U1, _U2>& __in)
1009 noexcept(__nothrow_constructible<const _U1&, const _U2&>())
1010 : _Inherited(static_cast<const _Tuple_impl<0, _U1, _U2>&>(__in)) { }
1011
1012 template<typename _U1, typename _U2,
1013 _ImplicitCtor<true, _U1, _U2> = true>
1014 constexpr
1015 tuple(tuple<_U1, _U2>&& __in)
1016 noexcept(__nothrow_constructible<_U1, _U2>())
1017 : _Inherited(static_cast<_Tuple_impl<0, _U1, _U2>&&>(__in)) { }
1018
1019 template<typename _U1, typename _U2,
1020 _ExplicitCtor<true, _U1, _U2> = false>
1021 explicit constexpr
1022 tuple(tuple<_U1, _U2>&& __in)
1023 noexcept(__nothrow_constructible<_U1, _U2>())
1024 : _Inherited(static_cast<_Tuple_impl<0, _U1, _U2>&&>(__in)) { }
1025
1026 template<typename _U1, typename _U2,
1027 _ImplicitCtor<true, const _U1&, const _U2&> = true>
1028 constexpr
1029 tuple(const pair<_U1, _U2>& __in)
1030 noexcept(__nothrow_constructible<const _U1&, const _U2&>())
1031 : _Inherited(__in.first, __in.second) { }
1032
1033 template<typename _U1, typename _U2,
1034 _ExplicitCtor<true, const _U1&, const _U2&> = false>
1035 explicit constexpr
1036 tuple(const pair<_U1, _U2>& __in)
1037 noexcept(__nothrow_constructible<const _U1&, const _U2&>())
1038 : _Inherited(__in.first, __in.second) { }
1039
1040 template<typename _U1, typename _U2,
1041 _ImplicitCtor<true, _U1, _U2> = true>
1042 constexpr
1043 tuple(pair<_U1, _U2>&& __in)
1044 noexcept(__nothrow_constructible<_U1, _U2>())
1045 : _Inherited(std::forward<_U1>(__in.first),
1046 std::forward<_U2>(__in.second)) { }
1047
1048 template<typename _U1, typename _U2,
1049 _ExplicitCtor<true, _U1, _U2> = false>
1050 explicit constexpr
1051 tuple(pair<_U1, _U2>&& __in)
1052 noexcept(__nothrow_constructible<_U1, _U2>())
1053 : _Inherited(std::forward<_U1>(__in.first),
1054 std::forward<_U2>(__in.second)) { }
1055
1056 // Allocator-extended constructors.
1057
1058 template<typename _Alloc,
1059 _ImplicitDefaultCtor<is_object<_Alloc>::value, _T1, _T2> = true>
1060 _GLIBCXX20_CONSTEXPR
1061 tuple(allocator_arg_t __tag, const _Alloc& __a)
1062 : _Inherited(__tag, __a) { }
1063
1064 template<typename _Alloc, bool _Dummy = true,
1065 _ImplicitCtor<_Dummy, const _T1&, const _T2&> = true>
1066 _GLIBCXX20_CONSTEXPR
1067 tuple(allocator_arg_t __tag, const _Alloc& __a,
1068 const _T1& __a1, const _T2& __a2)
1069 : _Inherited(__tag, __a, __a1, __a2) { }
1070
1071 template<typename _Alloc, bool _Dummy = true,
1072 _ExplicitCtor<_Dummy, const _T1&, const _T2&> = false>
1073 explicit
1074 _GLIBCXX20_CONSTEXPR
1075 tuple(allocator_arg_t __tag, const _Alloc& __a,
1076 const _T1& __a1, const _T2& __a2)
1077 : _Inherited(__tag, __a, __a1, __a2) { }
1078
1079 template<typename _Alloc, typename _U1, typename _U2,
1080 _ImplicitCtor<true, _U1, _U2> = true>
1081 _GLIBCXX20_CONSTEXPR
1082 tuple(allocator_arg_t __tag, const _Alloc& __a, _U1&& __a1, _U2&& __a2)
1083 : _Inherited(__tag, __a, std::forward<_U1>(__a1),
1084 std::forward<_U2>(__a2)) { }
1085
1086 template<typename _Alloc, typename _U1, typename _U2,
1087 _ExplicitCtor<true, _U1, _U2> = false>
1088 explicit
1089 _GLIBCXX20_CONSTEXPR
1090 tuple(allocator_arg_t __tag, const _Alloc& __a,
1091 _U1&& __a1, _U2&& __a2)
1092 : _Inherited(__tag, __a, std::forward<_U1>(__a1),
1093 std::forward<_U2>(__a2)) { }
1094
1095 template<typename _Alloc>
1096 _GLIBCXX20_CONSTEXPR
1097 tuple(allocator_arg_t __tag, const _Alloc& __a, const tuple& __in)
1098 : _Inherited(__tag, __a, static_cast<const _Inherited&>(__in)) { }
1099
1100 template<typename _Alloc>
1101 _GLIBCXX20_CONSTEXPR
1102 tuple(allocator_arg_t __tag, const _Alloc& __a, tuple&& __in)
1103 : _Inherited(__tag, __a, static_cast<_Inherited&&>(__in)) { }
1104
1105 template<typename _Alloc, typename _U1, typename _U2,
1106 _ImplicitCtor<true, const _U1&, const _U2&> = true>
1107 _GLIBCXX20_CONSTEXPR
1108 tuple(allocator_arg_t __tag, const _Alloc& __a,
1109 const tuple<_U1, _U2>& __in)
1110 : _Inherited(__tag, __a,
1111 static_cast<const _Tuple_impl<0, _U1, _U2>&>(__in))
1112 { }
1113
1114 template<typename _Alloc, typename _U1, typename _U2,
1115 _ExplicitCtor<true, const _U1&, const _U2&> = false>
1116 explicit
1117 _GLIBCXX20_CONSTEXPR
1118 tuple(allocator_arg_t __tag, const _Alloc& __a,
1119 const tuple<_U1, _U2>& __in)
1120 : _Inherited(__tag, __a,
1121 static_cast<const _Tuple_impl<0, _U1, _U2>&>(__in))
1122 { }
1123
1124 template<typename _Alloc, typename _U1, typename _U2,
1125 _ImplicitCtor<true, _U1, _U2> = true>
1126 _GLIBCXX20_CONSTEXPR
1127 tuple(allocator_arg_t __tag, const _Alloc& __a, tuple<_U1, _U2>&& __in)
1128 : _Inherited(__tag, __a, static_cast<_Tuple_impl<0, _U1, _U2>&&>(__in))
1129 { }
1130
1131 template<typename _Alloc, typename _U1, typename _U2,
1132 _ExplicitCtor<true, _U1, _U2> = false>
1133 explicit
1134 _GLIBCXX20_CONSTEXPR
1135 tuple(allocator_arg_t __tag, const _Alloc& __a, tuple<_U1, _U2>&& __in)
1136 : _Inherited(__tag, __a, static_cast<_Tuple_impl<0, _U1, _U2>&&>(__in))
1137 { }
1138
1139 template<typename _Alloc, typename _U1, typename _U2,
1140 _ImplicitCtor<true, const _U1&, const _U2&> = true>
1141 _GLIBCXX20_CONSTEXPR
1142 tuple(allocator_arg_t __tag, const _Alloc& __a,
1143 const pair<_U1, _U2>& __in)
1144 : _Inherited(__tag, __a, __in.first, __in.second) { }
1145
1146 template<typename _Alloc, typename _U1, typename _U2,
1147 _ExplicitCtor<true, const _U1&, const _U2&> = false>
1148 explicit
1149 _GLIBCXX20_CONSTEXPR
1150 tuple(allocator_arg_t __tag, const _Alloc& __a,
1151 const pair<_U1, _U2>& __in)
1152 : _Inherited(__tag, __a, __in.first, __in.second) { }
1153
1154 template<typename _Alloc, typename _U1, typename _U2,
1155 _ImplicitCtor<true, _U1, _U2> = true>
1156 _GLIBCXX20_CONSTEXPR
1157 tuple(allocator_arg_t __tag, const _Alloc& __a, pair<_U1, _U2>&& __in)
1158 : _Inherited(__tag, __a, std::forward<_U1>(__in.first),
1159 std::forward<_U2>(__in.second)) { }
1160
1161 template<typename _Alloc, typename _U1, typename _U2,
1162 _ExplicitCtor<true, _U1, _U2> = false>
1163 explicit
1164 _GLIBCXX20_CONSTEXPR
1165 tuple(allocator_arg_t __tag, const _Alloc& __a, pair<_U1, _U2>&& __in)
1166 : _Inherited(__tag, __a, std::forward<_U1>(__in.first),
1167 std::forward<_U2>(__in.second)) { }
1168
1169 // Tuple assignment.
1170
1171 _GLIBCXX20_CONSTEXPR
1172 tuple&
1173 operator=(typename conditional<__assignable<const _T1&, const _T2&>(),
1174 const tuple&,
1175 const __nonesuch&>::type __in)
1176 noexcept(__nothrow_assignable<const _T1&, const _T2&>())
1177 {
1178 this->_M_assign(__in);
1179 return *this;
1180 }
1181
1182 _GLIBCXX20_CONSTEXPR
1183 tuple&
1184 operator=(typename conditional<__assignable<_T1, _T2>(),
1185 tuple&&,
1186 __nonesuch&&>::type __in)
1187 noexcept(__nothrow_assignable<_T1, _T2>())
1188 {
1189 this->_M_assign(std::move(__in));
1190 return *this;
1191 }
1192
1193 template<typename _U1, typename _U2>
1194 _GLIBCXX20_CONSTEXPR
1195 __enable_if_t<__assignable<const _U1&, const _U2&>(), tuple&>
1196 operator=(const tuple<_U1, _U2>& __in)
1197 noexcept(__nothrow_assignable<const _U1&, const _U2&>())
1198 {
1199 this->_M_assign(__in);
1200 return *this;
1201 }
1202
1203 template<typename _U1, typename _U2>
1204 _GLIBCXX20_CONSTEXPR
1205 __enable_if_t<__assignable<_U1, _U2>(), tuple&>
1206 operator=(tuple<_U1, _U2>&& __in)
1207 noexcept(__nothrow_assignable<_U1, _U2>())
1208 {
1209 this->_M_assign(std::move(__in));
1210 return *this;
1211 }
1212
1213 template<typename _U1, typename _U2>
1214 _GLIBCXX20_CONSTEXPR
1215 __enable_if_t<__assignable<const _U1&, const _U2&>(), tuple&>
1216 operator=(const pair<_U1, _U2>& __in)
1217 noexcept(__nothrow_assignable<const _U1&, const _U2&>())
1218 {
1219 this->_M_head(*this) = __in.first;
1220 this->_M_tail(*this)._M_head(*this) = __in.second;
1221 return *this;
1222 }
1223
1224 template<typename _U1, typename _U2>
1225 _GLIBCXX20_CONSTEXPR
1226 __enable_if_t<__assignable<_U1, _U2>(), tuple&>
1227 operator=(pair<_U1, _U2>&& __in)
1228 noexcept(__nothrow_assignable<_U1, _U2>())
1229 {
1230 this->_M_head(*this) = std::forward<_U1>(__in.first);
1231 this->_M_tail(*this)._M_head(*this) = std::forward<_U2>(__in.second);
1232 return *this;
1233 }
1234
1235 _GLIBCXX20_CONSTEXPR
1236 void
1237 swap(tuple& __in)
1238 noexcept(__and_<__is_nothrow_swappable<_T1>,
1239 __is_nothrow_swappable<_T2>>::value)
1240 { _Inherited::_M_swap(__in); }
1241 };
1242
1243
1244 /// class tuple_size
1245 template<typename... _Elements>
1246 struct tuple_size<tuple<_Elements...>>
1247 : public integral_constant<std::size_t, sizeof...(_Elements)> { };
1248
1249#if __cplusplus201402L > 201402L
1250 template <typename _Tp>
1251 inline constexpr size_t tuple_size_v = tuple_size<_Tp>::value;
1252#endif
1253
1254 /**
1255 * Recursive case for tuple_element: strip off the first element in
1256 * the tuple and retrieve the (i-1)th element of the remaining tuple.
1257 */
1258 template<std::size_t __i, typename _Head, typename... _Tail>
1259 struct tuple_element<__i, tuple<_Head, _Tail...> >
1260 : tuple_element<__i - 1, tuple<_Tail...> > { };
1261
1262 /**
1263 * Basis case for tuple_element: The first element is the one we're seeking.
1264 */
1265 template<typename _Head, typename... _Tail>
1266 struct tuple_element<0, tuple<_Head, _Tail...> >
1267 {
1268 typedef _Head type;
1269 };
1270
1271 /**
1272 * Error case for tuple_element: invalid index.
1273 */
1274 template<size_t __i>
1275 struct tuple_element<__i, tuple<>>
1276 {
1277 static_assert(__i < tuple_size<tuple<>>::value,
1278 "tuple index is in range");
1279 };
1280
1281 template<std::size_t __i, typename _Head, typename... _Tail>
1282 constexpr _Head&
1283 __get_helper(_Tuple_impl<__i, _Head, _Tail...>& __t) noexcept
1284 { return _Tuple_impl<__i, _Head, _Tail...>::_M_head(__t); }
1285
1286 template<std::size_t __i, typename _Head, typename... _Tail>
1287 constexpr const _Head&
1288 __get_helper(const _Tuple_impl<__i, _Head, _Tail...>& __t) noexcept
1289 { return _Tuple_impl<__i, _Head, _Tail...>::_M_head(__t); }
1290
1291 /// Return a reference to the ith element of a tuple.
1292 template<std::size_t __i, typename... _Elements>
1293 constexpr __tuple_element_t<__i, tuple<_Elements...>>&
1294 get(tuple<_Elements...>& __t) noexcept
1295 { return std::__get_helper<__i>(__t); }
1296
1297 /// Return a const reference to the ith element of a const tuple.
1298 template<std::size_t __i, typename... _Elements>
1299 constexpr const __tuple_element_t<__i, tuple<_Elements...>>&
1300 get(const tuple<_Elements...>& __t) noexcept
1301 { return std::__get_helper<__i>(__t); }
1302
1303 /// Return an rvalue reference to the ith element of a tuple rvalue.
1304 template<std::size_t __i, typename... _Elements>
1305 constexpr __tuple_element_t<__i, tuple<_Elements...>>&&
1306 get(tuple<_Elements...>&& __t) noexcept
1307 {
1308 typedef __tuple_element_t<__i, tuple<_Elements...>> __element_type;
1309 return std::forward<__element_type&&>(std::get<__i>(__t));
1310 }
1311
1312 /// Return a const rvalue reference to the ith element of a const tuple rvalue.
1313 template<std::size_t __i, typename... _Elements>
1314 constexpr const __tuple_element_t<__i, tuple<_Elements...>>&&
1315 get(const tuple<_Elements...>&& __t) noexcept
1316 {
1317 typedef __tuple_element_t<__i, tuple<_Elements...>> __element_type;
1318 return std::forward<const __element_type&&>(std::get<__i>(__t));
1319 }
1320
1321#if __cplusplus201402L >= 201402L
1322
1323#define __cpp_lib_tuples_by_type201304 201304
1324
1325 template<typename _Head, size_t __i, typename... _Tail>
1326 constexpr _Head&
1327 __get_helper2(_Tuple_impl<__i, _Head, _Tail...>& __t) noexcept
1328 { return _Tuple_impl<__i, _Head, _Tail...>::_M_head(__t); }
1329
1330 template<typename _Head, size_t __i, typename... _Tail>
1331 constexpr const _Head&
1332 __get_helper2(const _Tuple_impl<__i, _Head, _Tail...>& __t) noexcept
1333 { return _Tuple_impl<__i, _Head, _Tail...>::_M_head(__t); }
1334
1335 /// Return a reference to the unique element of type _Tp of a tuple.
1336 template <typename _Tp, typename... _Types>
1337 constexpr _Tp&
1338 get(tuple<_Types...>& __t) noexcept
1339 { return std::__get_helper2<_Tp>(__t); }
1340
1341 /// Return a reference to the unique element of type _Tp of a tuple rvalue.
1342 template <typename _Tp, typename... _Types>
1343 constexpr _Tp&&
1344 get(tuple<_Types...>&& __t) noexcept
1345 { return std::forward<_Tp&&>(std::__get_helper2<_Tp>(__t)); }
1346
1347 /// Return a const reference to the unique element of type _Tp of a tuple.
1348 template <typename _Tp, typename... _Types>
1349 constexpr const _Tp&
1350 get(const tuple<_Types...>& __t) noexcept
1351 { return std::__get_helper2<_Tp>(__t); }
1352
1353 /// Return a const reference to the unique element of type _Tp of
1354 /// a const tuple rvalue.
1355 template <typename _Tp, typename... _Types>
1356 constexpr const _Tp&&
1357 get(const tuple<_Types...>&& __t) noexcept
1358 { return std::forward<const _Tp&&>(std::__get_helper2<_Tp>(__t)); }
1359#endif
1360
1361 // This class performs the comparison operations on tuples
1362 template<typename _Tp, typename _Up, size_t __i, size_t __size>
1363 struct __tuple_compare
1364 {
1365 static constexpr bool
1366 __eq(const _Tp& __t, const _Up& __u)
1367 {
1368 return bool(std::get<__i>(__t) == std::get<__i>(__u))
1369 && __tuple_compare<_Tp, _Up, __i + 1, __size>::__eq(__t, __u);
1370 }
1371
1372 static constexpr bool
1373 __less(const _Tp& __t, const _Up& __u)
1374 {
1375 return bool(std::get<__i>(__t) < std::get<__i>(__u))
1376 || (!bool(std::get<__i>(__u) < std::get<__i>(__t))
1377 && __tuple_compare<_Tp, _Up, __i + 1, __size>::__less(__t, __u));
1378 }
1379 };
1380
1381 template<typename _Tp, typename _Up, size_t __size>
1382 struct __tuple_compare<_Tp, _Up, __size, __size>
1383 {
1384 static constexpr bool
1385 __eq(const _Tp&, const _Up&) { return true; }
1386
1387 static constexpr bool
1388 __less(const _Tp&, const _Up&) { return false; }
1389 };
1390
1391 template<typename... _TElements, typename... _UElements>
1392 constexpr bool
1393 operator==(const tuple<_TElements...>& __t,
1394 const tuple<_UElements...>& __u)
1395 {
1396 static_assert(sizeof...(_TElements) == sizeof...(_UElements),
1397 "tuple objects can only be compared if they have equal sizes.");
1398 using __compare = __tuple_compare<tuple<_TElements...>,
1399 tuple<_UElements...>,
1400 0, sizeof...(_TElements)>;
1401 return __compare::__eq(__t, __u);
1402 }
1403
1404#if __cpp_lib_three_way_comparison
1405 template<typename _Cat, typename _Tp, typename _Up>
1406 constexpr _Cat
1407 __tuple_cmp(const _Tp&, const _Up&, index_sequence<>)
1408 { return _Cat::equivalent; }
1409
1410 template<typename _Cat, typename _Tp, typename _Up,
1411 size_t _Idx0, size_t... _Idxs>
1412 constexpr _Cat
1413 __tuple_cmp(const _Tp& __t, const _Up& __u,
1414 index_sequence<_Idx0, _Idxs...>)
1415 {
1416 auto __c
1417 = __detail::__synth3way(std::get<_Idx0>(__t), std::get<_Idx0>(__u));
1418 if (__c != 0)
1419 return __c;
1420 return std::__tuple_cmp<_Cat>(__t, __u, index_sequence<_Idxs...>());
1421 }
1422
1423 template<typename... _Tps, typename... _Ups>
1424 constexpr
1425 common_comparison_category_t<__detail::__synth3way_t<_Tps, _Ups>...>
1426 operator<=>(const tuple<_Tps...>& __t, const tuple<_Ups...>& __u)
1427 {
1428 using _Cat
1429 = common_comparison_category_t<__detail::__synth3way_t<_Tps, _Ups>...>;
1430 return std::__tuple_cmp<_Cat>(__t, __u, index_sequence_for<_Tps...>());
1431 }
1432#else
1433 template<typename... _TElements, typename... _UElements>
1434 constexpr bool
1435 operator<(const tuple<_TElements...>& __t,
1436 const tuple<_UElements...>& __u)
1437 {
1438 static_assert(sizeof...(_TElements) == sizeof...(_UElements),
1439 "tuple objects can only be compared if they have equal sizes.");
1440 using __compare = __tuple_compare<tuple<_TElements...>,
1441 tuple<_UElements...>,
1442 0, sizeof...(_TElements)>;
1443 return __compare::__less(__t, __u);
1444 }
1445
1446 template<typename... _TElements, typename... _UElements>
1447 constexpr bool
1448 operator!=(const tuple<_TElements...>& __t,
1449 const tuple<_UElements...>& __u)
1450 { return !(__t == __u); }
1451
1452 template<typename... _TElements, typename... _UElements>
1453 constexpr bool
1454 operator>(const tuple<_TElements...>& __t,
1455 const tuple<_UElements...>& __u)
1456 { return __u < __t; }
1457
1458 template<typename... _TElements, typename... _UElements>
1459 constexpr bool
1460 operator<=(const tuple<_TElements...>& __t,
1461 const tuple<_UElements...>& __u)
1462 { return !(__u < __t); }
1463
1464 template<typename... _TElements, typename... _UElements>
1465 constexpr bool
1466 operator>=(const tuple<_TElements...>& __t,
1467 const tuple<_UElements...>& __u)
1468 { return !(__t < __u); }
1469#endif // three_way_comparison
1470
1471 // NB: DR 705.
1472 template<typename... _Elements>
1473 constexpr tuple<typename __decay_and_strip<_Elements>::__type...>
1474 make_tuple(_Elements&&... __args)
1475 {
1476 typedef tuple<typename __decay_and_strip<_Elements>::__type...>
1477 __result_type;
1478 return __result_type(std::forward<_Elements>(__args)...);
1479 }
1480
1481 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1482 // 2275. Why is forward_as_tuple not constexpr?
1483 /// std::forward_as_tuple
1484 template<typename... _Elements>
1485 constexpr tuple<_Elements&&...>
1486 forward_as_tuple(_Elements&&... __args) noexcept
1487 { return tuple<_Elements&&...>(std::forward<_Elements>(__args)...); }
1488
1489 template<size_t, typename, typename, size_t>
1490 struct __make_tuple_impl;
1491
1492 template<size_t _Idx, typename _Tuple, typename... _Tp, size_t _Nm>
1493 struct __make_tuple_impl<_Idx, tuple<_Tp...>, _Tuple, _Nm>
1494 : __make_tuple_impl<_Idx + 1,
1495 tuple<_Tp..., __tuple_element_t<_Idx, _Tuple>>,
1496 _Tuple, _Nm>
1497 { };
1498
1499 template<std::size_t _Nm, typename _Tuple, typename... _Tp>
1500 struct __make_tuple_impl<_Nm, tuple<_Tp...>, _Tuple, _Nm>
1501 {
1502 typedef tuple<_Tp...> __type;
1503 };
1504
1505 template<typename _Tuple>
1506 struct __do_make_tuple
1507 : __make_tuple_impl<0, tuple<>, _Tuple, std::tuple_size<_Tuple>::value>
1508 { };
1509
1510 // Returns the std::tuple equivalent of a tuple-like type.
1511 template<typename _Tuple>
1512 struct __make_tuple
1513 : public __do_make_tuple<__remove_cvref_t<_Tuple>>
1514 { };
1515
1516 // Combines several std::tuple's into a single one.
1517 template<typename...>
1518 struct __combine_tuples;
1519
1520 template<>
1521 struct __combine_tuples<>
1522 {
1523 typedef tuple<> __type;
1524 };
1525
1526 template<typename... _Ts>
1527 struct __combine_tuples<tuple<_Ts...>>
1528 {
1529 typedef tuple<_Ts...> __type;
1530 };
1531
1532 template<typename... _T1s, typename... _T2s, typename... _Rem>
1533 struct __combine_tuples<tuple<_T1s...>, tuple<_T2s...>, _Rem...>
1534 {
1535 typedef typename __combine_tuples<tuple<_T1s..., _T2s...>,
1536 _Rem...>::__type __type;
1537 };
1538
1539 // Computes the result type of tuple_cat given a set of tuple-like types.
1540 template<typename... _Tpls>
1541 struct __tuple_cat_result
1542 {
1543 typedef typename __combine_tuples
1544 <typename __make_tuple<_Tpls>::__type...>::__type __type;
1545 };
1546
1547 // Helper to determine the index set for the first tuple-like
1548 // type of a given set.
1549 template<typename...>
1550 struct __make_1st_indices;
1551
1552 template<>
1553 struct __make_1st_indices<>
1554 {
1555 typedef std::_Index_tuple<> __type;
1556 };
1557
1558 template<typename _Tp, typename... _Tpls>
1559 struct __make_1st_indices<_Tp, _Tpls...>
1560 {
1561 typedef typename std::_Build_index_tuple<std::tuple_size<
1562 typename std::remove_reference<_Tp>::type>::value>::__type __type;
1563 };
1564
1565 // Performs the actual concatenation by step-wise expanding tuple-like
1566 // objects into the elements, which are finally forwarded into the
1567 // result tuple.
1568 template<typename _Ret, typename _Indices, typename... _Tpls>
1569 struct __tuple_concater;
1570
1571 template<typename _Ret, std::size_t... _Is, typename _Tp, typename... _Tpls>
1572 struct __tuple_concater<_Ret, std::_Index_tuple<_Is...>, _Tp, _Tpls...>
1573 {
1574 template<typename... _Us>
1575 static constexpr _Ret
1576 _S_do(_Tp&& __tp, _Tpls&&... __tps, _Us&&... __us)
1577 {
1578 typedef typename __make_1st_indices<_Tpls...>::__type __idx;
1579 typedef __tuple_concater<_Ret, __idx, _Tpls...> __next;
1580 return __next::_S_do(std::forward<_Tpls>(__tps)...,
1581 std::forward<_Us>(__us)...,
1582 std::get<_Is>(std::forward<_Tp>(__tp))...);
1583 }
1584 };
1585
1586 template<typename _Ret>
1587 struct __tuple_concater<_Ret, std::_Index_tuple<>>
1588 {
1589 template<typename... _Us>
1590 static constexpr _Ret
1591 _S_do(_Us&&... __us)
1592 {
1593 return _Ret(std::forward<_Us>(__us)...);
1594 }
1595 };
1596
1597 /// tuple_cat
1598 template<typename... _Tpls, typename = typename
1599 enable_if<__and_<__is_tuple_like<_Tpls>...>::value>::type>
1600 constexpr auto
1601 tuple_cat(_Tpls&&... __tpls)
1602 -> typename __tuple_cat_result<_Tpls...>::__type
1603 {
1604 typedef typename __tuple_cat_result<_Tpls...>::__type __ret;
1605 typedef typename __make_1st_indices<_Tpls...>::__type __idx;
1606 typedef __tuple_concater<__ret, __idx, _Tpls...> __concater;
1607 return __concater::_S_do(std::forward<_Tpls>(__tpls)...);
1608 }
1609
1610 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1611 // 2301. Why is tie not constexpr?
1612 /// tie
1613 template<typename... _Elements>
1614 constexpr tuple<_Elements&...>
1615 tie(_Elements&... __args) noexcept
1616 { return tuple<_Elements&...>(__args...); }
10
Calling constructor for 'tuple<llvm::IntrusiveRefCntPtr<const clang::ento::ProgramState> &, llvm::IntrusiveRefCntPtr<const clang::ento::ProgramState> &>'
17
Returning from constructor for 'tuple<llvm::IntrusiveRefCntPtr<const clang::ento::ProgramState> &, llvm::IntrusiveRefCntPtr<const clang::ento::ProgramState> &>'
1617
1618 /// swap
1619 template<typename... _Elements>
1620 _GLIBCXX20_CONSTEXPR
1621 inline
1622#if __cplusplus201402L > 201402L || !defined(__STRICT_ANSI__1) // c++1z or gnu++11
1623 // Constrained free swap overload, see p0185r1
1624 typename enable_if<__and_<__is_swappable<_Elements>...>::value
1625 >::type
1626#else
1627 void
1628#endif
1629 swap(tuple<_Elements...>& __x, tuple<_Elements...>& __y)
1630 noexcept(noexcept(__x.swap(__y)))
1631 { __x.swap(__y); }
1632
1633#if __cplusplus201402L > 201402L || !defined(__STRICT_ANSI__1) // c++1z or gnu++11
1634 template<typename... _Elements>
1635 _GLIBCXX20_CONSTEXPR
1636 typename enable_if<!__and_<__is_swappable<_Elements>...>::value>::type
1637 swap(tuple<_Elements...>&, tuple<_Elements...>&) = delete;
1638#endif
1639
1640 // A class (and instance) which can be used in 'tie' when an element
1641 // of a tuple is not required.
1642 // _GLIBCXX14_CONSTEXPR
1643 // 2933. PR for LWG 2773 could be clearer
1644 struct _Swallow_assign
1645 {
1646 template<class _Tp>
1647 _GLIBCXX14_CONSTEXPRconstexpr const _Swallow_assign&
1648 operator=(const _Tp&) const
1649 { return *this; }
1650 };
1651
1652 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1653 // 2773. Making std::ignore constexpr
1654 _GLIBCXX17_INLINE constexpr _Swallow_assign ignore{};
1655
1656 /// Partial specialization for tuples
1657 template<typename... _Types, typename _Alloc>
1658 struct uses_allocator<tuple<_Types...>, _Alloc> : true_type { };
1659
1660 // See stl_pair.h...
1661 /** "piecewise construction" using a tuple of arguments for each member.
1662 *
1663 * @param __first Arguments for the first member of the pair.
1664 * @param __second Arguments for the second member of the pair.
1665 *
1666 * The elements of each tuple will be used as the constructor arguments
1667 * for the data members of the pair.
1668 */
1669 template<class _T1, class _T2>
1670 template<typename... _Args1, typename... _Args2>
1671 _GLIBCXX20_CONSTEXPR
1672 inline
1673 pair<_T1, _T2>::
1674 pair(piecewise_construct_t,
1675 tuple<_Args1...> __first, tuple<_Args2...> __second)
1676 : pair(__first, __second,
1677 typename _Build_index_tuple<sizeof...(_Args1)>::__type(),
1678 typename _Build_index_tuple<sizeof...(_Args2)>::__type())
1679 { }
1680
1681 template<class _T1, class _T2>
1682 template<typename... _Args1, std::size_t... _Indexes1,
1683 typename... _Args2, std::size_t... _Indexes2>
1684 _GLIBCXX20_CONSTEXPR inline
1685 pair<_T1, _T2>::
1686 pair(tuple<_Args1...>& __tuple1, tuple<_Args2...>& __tuple2,
1687 _Index_tuple<_Indexes1...>, _Index_tuple<_Indexes2...>)
1688 : first(std::forward<_Args1>(std::get<_Indexes1>(__tuple1))...),
1689 second(std::forward<_Args2>(std::get<_Indexes2>(__tuple2))...)
1690 { }
1691
1692#if __cplusplus201402L >= 201703L
1693
1694 // Unpack a std::tuple into a type trait and use its value.
1695 // For cv std::tuple<_Up> the result is _Trait<_Tp, cv _Up...>::value.
1696 // For cv std::tuple<_Up>& the result is _Trait<_Tp, cv _Up&...>::value.
1697 // Otherwise the result is false (because we don't know if std::get throws).
1698 template<template<typename...> class _Trait, typename _Tp, typename _Tuple>
1699 inline constexpr bool __unpack_std_tuple = false;
1700
1701 template<template<typename...> class _Trait, typename _Tp, typename... _Up>
1702 inline constexpr bool __unpack_std_tuple<_Trait, _Tp, tuple<_Up...>>
1703 = _Trait<_Tp, _Up...>::value;
1704
1705 template<template<typename...> class _Trait, typename _Tp, typename... _Up>
1706 inline constexpr bool __unpack_std_tuple<_Trait, _Tp, tuple<_Up...>&>
1707 = _Trait<_Tp, _Up&...>::value;
1708
1709 template<template<typename...> class _Trait, typename _Tp, typename... _Up>
1710 inline constexpr bool __unpack_std_tuple<_Trait, _Tp, const tuple<_Up...>>
1711 = _Trait<_Tp, const _Up...>::value;
1712
1713 template<template<typename...> class _Trait, typename _Tp, typename... _Up>
1714 inline constexpr bool __unpack_std_tuple<_Trait, _Tp, const tuple<_Up...>&>
1715 = _Trait<_Tp, const _Up&...>::value;
1716
1717# define __cpp_lib_apply 201603
1718
1719 template <typename _Fn, typename _Tuple, size_t... _Idx>
1720 constexpr decltype(auto)
1721 __apply_impl(_Fn&& __f, _Tuple&& __t, index_sequence<_Idx...>)
1722 {
1723 return std::__invoke(std::forward<_Fn>(__f),
1724 std::get<_Idx>(std::forward<_Tuple>(__t))...);
1725 }
1726
1727 template <typename _Fn, typename _Tuple>
1728 constexpr decltype(auto)
1729 apply(_Fn&& __f, _Tuple&& __t)
1730 noexcept(__unpack_std_tuple<is_nothrow_invocable, _Fn, _Tuple>)
1731 {
1732 using _Indices
1733 = make_index_sequence<tuple_size_v<remove_reference_t<_Tuple>>>;
1734 return std::__apply_impl(std::forward<_Fn>(__f),
1735 std::forward<_Tuple>(__t),
1736 _Indices{});
1737 }
1738
1739#define __cpp_lib_make_from_tuple 201606
1740
1741 template <typename _Tp, typename _Tuple, size_t... _Idx>
1742 constexpr _Tp
1743 __make_from_tuple_impl(_Tuple&& __t, index_sequence<_Idx...>)
1744 { return _Tp(std::get<_Idx>(std::forward<_Tuple>(__t))...); }
1745
1746 template <typename _Tp, typename _Tuple>
1747 constexpr _Tp
1748 make_from_tuple(_Tuple&& __t)
1749 noexcept(__unpack_std_tuple<is_nothrow_constructible, _Tp, _Tuple>)
1750 {
1751 return __make_from_tuple_impl<_Tp>(
1752 std::forward<_Tuple>(__t),
1753 make_index_sequence<tuple_size_v<remove_reference_t<_Tuple>>>{});
1754 }
1755#endif // C++17
1756
1757 /// @}
1758
1759_GLIBCXX_END_NAMESPACE_VERSION
1760} // namespace std
1761
1762#endif // C++11
1763
1764#endif // _GLIBCXX_TUPLE

/build/llvm-toolchain-snapshot-14~++20220118101002+ec47dba1c8a2/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SVals.h

1//===- SVals.h - Abstract Values for Static Analysis ------------*- 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 SVal, Loc, and NonLoc, classes that represent
10// abstract r-values for use with path-sensitive value tracking.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_SVALS_H
15#define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_SVALS_H
16
17#include "clang/AST/Expr.h"
18#include "clang/AST/Type.h"
19#include "clang/Basic/LLVM.h"
20#include "clang/StaticAnalyzer/Core/PathSensitive/SymExpr.h"
21#include "llvm/ADT/FoldingSet.h"
22#include "llvm/ADT/ImmutableList.h"
23#include "llvm/ADT/None.h"
24#include "llvm/ADT/Optional.h"
25#include "llvm/ADT/PointerUnion.h"
26#include "llvm/Support/Casting.h"
27#include <cassert>
28#include <cstdint>
29#include <utility>
30
31//==------------------------------------------------------------------------==//
32// Base SVal types.
33//==------------------------------------------------------------------------==//
34
35namespace clang {
36
37class CXXBaseSpecifier;
38class FunctionDecl;
39class LabelDecl;
40
41namespace ento {
42
43class BasicValueFactory;
44class CompoundValData;
45class LazyCompoundValData;
46class MemRegion;
47class PointerToMemberData;
48class SValBuilder;
49class TypedValueRegion;
50
51namespace nonloc {
52
53/// Sub-kinds for NonLoc values.
54enum Kind {
55#define NONLOC_SVAL(Id, Parent) Id ## Kind,
56#include "clang/StaticAnalyzer/Core/PathSensitive/SVals.def"
57};
58
59} // namespace nonloc
60
61namespace loc {
62
63/// Sub-kinds for Loc values.
64enum Kind {
65#define LOC_SVAL(Id, Parent) Id ## Kind,
66#include "clang/StaticAnalyzer/Core/PathSensitive/SVals.def"
67};
68
69} // namespace loc
70
71/// SVal - This represents a symbolic expression, which can be either
72/// an L-value or an R-value.
73///
74class SVal {
75public:
76 enum BaseKind {
77 // The enumerators must be representable using 2 bits.
78#define BASIC_SVAL(Id, Parent) Id ## Kind,
79#define ABSTRACT_SVAL_WITH_KIND(Id, Parent) Id ## Kind,
80#include "clang/StaticAnalyzer/Core/PathSensitive/SVals.def"
81 };
82 enum { BaseBits = 2, BaseMask = 0b11 };
83
84protected:
85 const void *Data = nullptr;
86
87 /// The lowest 2 bits are a BaseKind (0 -- 3).
88 /// The higher bits are an unsigned "kind" value.
89 unsigned Kind = 0;
90
91 explicit SVal(const void *d, bool isLoc, unsigned ValKind)
92 : Data(d), Kind((isLoc ? LocKind : NonLocKind) | (ValKind << BaseBits)) {}
93
94 explicit SVal(BaseKind k, const void *D = nullptr) : Data(D), Kind(k) {}
95
96public:
97 explicit SVal() = default;
98
99 /// Convert to the specified SVal type, asserting that this SVal is of
100 /// the desired type.
101 template<typename T>
102 T castAs() const {
103 assert(T::isKind(*this))(static_cast <bool> (T::isKind(*this)) ? void (0) : __assert_fail
("T::isKind(*this)", "clang/include/clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
, 103, __extension__ __PRETTY_FUNCTION__))
;
104 return *static_cast<const T *>(this);
105 }
106
107 /// Convert to the specified SVal type, returning None if this SVal is
108 /// not of the desired type.
109 template<typename T>
110 Optional<T> getAs() const {
111 if (!T::isKind(*this))
112 return None;
113 return *static_cast<const T *>(this);
114 }
115
116 unsigned getRawKind() const { return Kind; }
117 BaseKind getBaseKind() const { return (BaseKind) (Kind & BaseMask); }
118 unsigned getSubKind() const { return Kind >> BaseBits; }
119
120 // This method is required for using SVal in a FoldingSetNode. It
121 // extracts a unique signature for this SVal object.
122 void Profile(llvm::FoldingSetNodeID &ID) const {
123 ID.AddInteger((unsigned) getRawKind());
124 ID.AddPointer(Data);
125 }
126
127 bool operator==(const SVal &R) const {
128 return getRawKind() == R.getRawKind() && Data == R.Data;
129 }
130
131 bool operator!=(const SVal &R) const {
132 return !(*this == R);
133 }
134
135 bool isUnknown() const {
136 return getRawKind() == UnknownValKind;
34
Returning the value 1, which participates in a condition later
137 }
138
139 bool isUndef() const {
140 return getRawKind() == UndefinedValKind;
24
Assuming the condition is false
25
Returning zero, which participates in a condition later
141 }
142
143 bool isUnknownOrUndef() const {
144 return getRawKind() <= UnknownValKind;
145 }
146
147 bool isValid() const {
148 return getRawKind() > UnknownValKind;
149 }
150
151 bool isConstant() const;
152
153 bool isConstant(int I) const;
154
155 bool isZeroConstant() const;
156
157 /// hasConjuredSymbol - If this SVal wraps a conjured symbol, return true;
158 bool hasConjuredSymbol() const;
159
160 /// getAsFunctionDecl - If this SVal is a MemRegionVal and wraps a
161 /// CodeTextRegion wrapping a FunctionDecl, return that FunctionDecl.
162 /// Otherwise return 0.
163 const FunctionDecl *getAsFunctionDecl() const;
164
165 /// If this SVal is a location and wraps a symbol, return that
166 /// SymbolRef. Otherwise return 0.
167 ///
168 /// Casts are ignored during lookup.
169 /// \param IncludeBaseRegions The boolean that controls whether the search
170 /// should continue to the base regions if the region is not symbolic.
171 SymbolRef getAsLocSymbol(bool IncludeBaseRegions = false) const;
172
173 /// Get the symbol in the SVal or its base region.
174 SymbolRef getLocSymbolInBase() const;
175
176 /// If this SVal wraps a symbol return that SymbolRef.
177 /// Otherwise, return 0.
178 ///
179 /// Casts are ignored during lookup.
180 /// \param IncludeBaseRegions The boolean that controls whether the search
181 /// should continue to the base regions if the region is not symbolic.
182 SymbolRef getAsSymbol(bool IncludeBaseRegions = false) const;
183
184 const MemRegion *getAsRegion() const;
185
186 /// printJson - Pretty-prints in JSON format.
187 void printJson(raw_ostream &Out, bool AddQuotes) const;
188
189 void dumpToStream(raw_ostream &OS) const;
190 void dump() const;
191
192 SymExpr::symbol_iterator symbol_begin() const {
193 const SymExpr *SE = getAsSymbol(/*IncludeBaseRegions=*/true);
194 if (SE)
195 return SE->symbol_begin();
196 else
197 return SymExpr::symbol_iterator();
198 }
199
200 SymExpr::symbol_iterator symbol_end() const {
201 return SymExpr::symbol_end();
202 }
203
204 /// Try to get a reasonable type for the given value.
205 ///
206 /// \returns The best approximation of the value type or Null.
207 /// In theory, all symbolic values should be typed, but this function
208 /// is still a WIP and might have a few blind spots.
209 ///
210 /// \note This function should not be used when the user has access to the
211 /// bound expression AST node as well, since AST always has exact types.
212 ///
213 /// \note Loc values are interpreted as pointer rvalues for the purposes of
214 /// this method.
215 QualType getType(const ASTContext &) const;
216};
217
218inline raw_ostream &operator<<(raw_ostream &os, clang::ento::SVal V) {
219 V.dumpToStream(os);
220 return os;
221}
222
223class UndefinedVal : public SVal {
224public:
225 UndefinedVal() : SVal(UndefinedValKind) {}
226
227private:
228 friend class SVal;
229
230 static bool isKind(const SVal& V) {
231 return V.getBaseKind() == UndefinedValKind;
232 }
233};
234
235class DefinedOrUnknownSVal : public SVal {
236public:
237 // We want calling these methods to be a compiler error since they are
238 // tautologically false.
239 bool isUndef() const = delete;
240 bool isValid() const = delete;
241
242protected:
243 DefinedOrUnknownSVal() = default;
244 explicit DefinedOrUnknownSVal(const void *d, bool isLoc, unsigned ValKind)
245 : SVal(d, isLoc, ValKind) {}
246 explicit DefinedOrUnknownSVal(BaseKind k, void *D = nullptr) : SVal(k, D) {}
247
248private:
249 friend class SVal;
250
251 static bool isKind(const SVal& V) {
252 return !V.isUndef();
253 }
254};
255
256class UnknownVal : public DefinedOrUnknownSVal {
257public:
258 explicit UnknownVal() : DefinedOrUnknownSVal(UnknownValKind) {}
259
260private:
261 friend class SVal;
262
263 static bool isKind(const SVal &V) {
264 return V.getBaseKind() == UnknownValKind;
265 }
266};
267
268class DefinedSVal : public DefinedOrUnknownSVal {
269public:
270 // We want calling these methods to be a compiler error since they are
271 // tautologically true/false.
272 bool isUnknown() const = delete;
273 bool isUnknownOrUndef() const = delete;
274 bool isValid() const = delete;
275
276protected:
277 DefinedSVal() = default;
278 explicit DefinedSVal(const void *d, bool isLoc, unsigned ValKind)
279 : DefinedOrUnknownSVal(d, isLoc, ValKind) {}
280
281private:
282 friend class SVal;
283
284 static bool isKind(const SVal& V) {
285 return !V.isUnknownOrUndef();
286 }
287};
288
289/// Represents an SVal that is guaranteed to not be UnknownVal.
290class KnownSVal : public SVal {
291 friend class SVal;
292
293 KnownSVal() = default;
294
295 static bool isKind(const SVal &V) {
296 return !V.isUnknown();
297 }
298
299public:
300 KnownSVal(const DefinedSVal &V) : SVal(V) {}
301 KnownSVal(const UndefinedVal &V) : SVal(V) {}
302};
303
304class NonLoc : public DefinedSVal {
305protected:
306 NonLoc() = default;
307 explicit NonLoc(unsigned SubKind, const void *d)
308 : DefinedSVal(d, false, SubKind) {}
309
310public:
311 void dumpToStream(raw_ostream &Out) const;
312
313 static bool isCompoundType(QualType T) {
314 return T->isArrayType() || T->isRecordType() ||
315 T->isAnyComplexType() || T->isVectorType();
316 }
317
318private:
319 friend class SVal;
320
321 static bool isKind(const SVal& V) {
322 return V.getBaseKind() == NonLocKind;
323 }
324};
325
326class Loc : public DefinedSVal {
327protected:
328 Loc() = default;
329 explicit Loc(unsigned SubKind, const void *D)
330 : DefinedSVal(const_cast<void *>(D), true, SubKind) {}
331
332public:
333 void dumpToStream(raw_ostream &Out) const;
334
335 static bool isLocType(QualType T) {
336 return T->isAnyPointerType() || T->isBlockPointerType() ||
337 T->isReferenceType() || T->isNullPtrType();
338 }
339
340private:
341 friend class SVal;
342
343 static bool isKind(const SVal& V) {
344 return V.getBaseKind() == LocKind;
345 }
346};
347
348//==------------------------------------------------------------------------==//
349// Subclasses of NonLoc.
350//==------------------------------------------------------------------------==//
351
352namespace nonloc {
353
354/// Represents symbolic expression that isn't a location.
355class SymbolVal : public NonLoc {
356public:
357 SymbolVal() = delete;
358 SymbolVal(SymbolRef sym) : NonLoc(SymbolValKind, sym) {
359 assert(sym)(static_cast <bool> (sym) ? void (0) : __assert_fail ("sym"
, "clang/include/clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
, 359, __extension__ __PRETTY_FUNCTION__))
;
360 assert(!Loc::isLocType(sym->getType()))(static_cast <bool> (!Loc::isLocType(sym->getType())
) ? void (0) : __assert_fail ("!Loc::isLocType(sym->getType())"
, "clang/include/clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
, 360, __extension__ __PRETTY_FUNCTION__))
;
361 }
362
363 SymbolRef getSymbol() const {
364 return (const SymExpr *) Data;
365 }
366
367 bool isExpression() const {
368 return !isa<SymbolData>(getSymbol());
369 }
370
371private:
372 friend class SVal;
373
374 static bool isKind(const SVal& V) {
375 return V.getBaseKind() == NonLocKind &&
376 V.getSubKind() == SymbolValKind;
377 }
378
379 static bool isKind(const NonLoc& V) {
380 return V.getSubKind() == SymbolValKind;
381 }
382};
383
384/// Value representing integer constant.
385class ConcreteInt : public NonLoc {
386public:
387 explicit ConcreteInt(const llvm::APSInt& V) : NonLoc(ConcreteIntKind, &V) {}
388
389 const llvm::APSInt& getValue() const {
390 return *static_cast<const llvm::APSInt *>(Data);
391 }
392
393 // Transfer functions for binary/unary operations on ConcreteInts.
394 SVal evalBinOp(SValBuilder &svalBuilder, BinaryOperator::Opcode Op,
395 const ConcreteInt& R) const;
396
397 ConcreteInt evalComplement(SValBuilder &svalBuilder) const;
398
399 ConcreteInt evalMinus(SValBuilder &svalBuilder) const;
400
401private:
402 friend class SVal;
403
404 ConcreteInt() = default;
405
406 static bool isKind(const SVal& V) {
407 return V.getBaseKind() == NonLocKind &&
408 V.getSubKind() == ConcreteIntKind;
409 }
410
411 static bool isKind(const NonLoc& V) {
412 return V.getSubKind() == ConcreteIntKind;
413 }
414};
415
416class LocAsInteger : public NonLoc {
417 friend class ento::SValBuilder;
418
419 explicit LocAsInteger(const std::pair<SVal, uintptr_t> &data)
420 : NonLoc(LocAsIntegerKind, &data) {
421 // We do not need to represent loc::ConcreteInt as LocAsInteger,
422 // as it'd collapse into a nonloc::ConcreteInt instead.
423 assert(data.first.getBaseKind() == LocKind &&(static_cast <bool> (data.first.getBaseKind() == LocKind
&& (data.first.getSubKind() == loc::MemRegionValKind
|| data.first.getSubKind() == loc::GotoLabelKind)) ? void (0
) : __assert_fail ("data.first.getBaseKind() == LocKind && (data.first.getSubKind() == loc::MemRegionValKind || data.first.getSubKind() == loc::GotoLabelKind)"
, "clang/include/clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
, 425, __extension__ __PRETTY_FUNCTION__))
424 (data.first.getSubKind() == loc::MemRegionValKind ||(static_cast <bool> (data.first.getBaseKind() == LocKind
&& (data.first.getSubKind() == loc::MemRegionValKind
|| data.first.getSubKind() == loc::GotoLabelKind)) ? void (0
) : __assert_fail ("data.first.getBaseKind() == LocKind && (data.first.getSubKind() == loc::MemRegionValKind || data.first.getSubKind() == loc::GotoLabelKind)"
, "clang/include/clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
, 425, __extension__ __PRETTY_FUNCTION__))
425 data.first.getSubKind() == loc::GotoLabelKind))(static_cast <bool> (data.first.getBaseKind() == LocKind
&& (data.first.getSubKind() == loc::MemRegionValKind
|| data.first.getSubKind() == loc::GotoLabelKind)) ? void (0
) : __assert_fail ("data.first.getBaseKind() == LocKind && (data.first.getSubKind() == loc::MemRegionValKind || data.first.getSubKind() == loc::GotoLabelKind)"
, "clang/include/clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
, 425, __extension__ __PRETTY_FUNCTION__))
;
426 }
427
428public:
429 Loc getLoc() const {
430 const std::pair<SVal, uintptr_t> *D =
431 static_cast<const std::pair<SVal, uintptr_t> *>(Data);
432 return D->first.castAs<Loc>();
433 }
434
435 Loc getPersistentLoc() const {
436 const std::pair<SVal, uintptr_t> *D =
437 static_cast<const std::pair<SVal, uintptr_t> *>(Data);
438 const SVal& V = D->first;
439 return V.castAs<Loc>();
440 }
441
442 unsigned getNumBits() const {
443 const std::pair<SVal, uintptr_t> *D =
444 static_cast<const std::pair<SVal, uintptr_t> *>(Data);
445 return D->second;
446 }
447
448private:
449 friend class SVal;
450
451 LocAsInteger() = default;
452
453 static bool isKind(const SVal& V) {
454 return V.getBaseKind() == NonLocKind &&
455 V.getSubKind() == LocAsIntegerKind;
456 }
457
458 static bool isKind(const NonLoc& V) {
459 return V.getSubKind() == LocAsIntegerKind;
460 }
461};
462
463class CompoundVal : public NonLoc {
464 friend class ento::SValBuilder;
465
466 explicit CompoundVal(const CompoundValData* D) : NonLoc(CompoundValKind, D) {}
467
468public:
469 const CompoundValData* getValue() const {
470 return static_cast<const CompoundValData *>(Data);
471 }
472
473 using iterator = llvm::ImmutableList<SVal>::iterator;
474
475 iterator begin() const;
476 iterator end() const;
477
478private:
479 friend class SVal;
480
481 CompoundVal() = default;
482
483 static bool isKind(const SVal& V) {
484 return V.getBaseKind() == NonLocKind && V.getSubKind() == CompoundValKind;
485 }
486
487 static bool isKind(const NonLoc& V) {
488 return V.getSubKind() == CompoundValKind;
489 }
490};
491
492class LazyCompoundVal : public NonLoc {
493 friend class ento::SValBuilder;
494
495 explicit LazyCompoundVal(const LazyCompoundValData *D)
496 : NonLoc(LazyCompoundValKind, D) {}
497
498public:
499 const LazyCompoundValData *getCVData() const {
500 return static_cast<const LazyCompoundValData *>(Data);
501 }
502
503 const void *getStore() const;
504 const TypedValueRegion *getRegion() const;
505
506private:
507 friend class SVal;
508
509 LazyCompoundVal() = default;
510
511 static bool isKind(const SVal& V) {
512 return V.getBaseKind() == NonLocKind &&
513 V.getSubKind() == LazyCompoundValKind;
514 }
515
516 static bool isKind(const NonLoc& V) {
517 return V.getSubKind() == LazyCompoundValKind;
518 }
519};
520
521/// Value representing pointer-to-member.
522///
523/// This value is qualified as NonLoc because neither loading nor storing
524/// operations are applied to it. Instead, the analyzer uses the L-value coming
525/// from pointer-to-member applied to an object.
526/// This SVal is represented by a NamedDecl which can be a member function
527/// pointer or a member data pointer and an optional list of CXXBaseSpecifiers.
528/// This list is required to accumulate the pointer-to-member cast history to
529/// figure out the correct subobject field. In particular, implicit casts grow
530/// this list and explicit casts like static_cast shrink this list.
531class PointerToMember : public NonLoc {
532 friend class ento::SValBuilder;
533
534public:
535 using PTMDataType =
536 llvm::PointerUnion<const NamedDecl *, const PointerToMemberData *>;
537
538 const PTMDataType getPTMData() const {
539 return PTMDataType::getFromOpaqueValue(const_cast<void *>(Data));
540 }
541
542 bool isNullMemberPointer() const;
543
544 const NamedDecl *getDecl() const;
545
546 template<typename AdjustedDecl>
547 const AdjustedDecl *getDeclAs() const {
548 return dyn_cast_or_null<AdjustedDecl>(getDecl());
549 }
550
551 using iterator = llvm::ImmutableList<const CXXBaseSpecifier *>::iterator;
552
553 iterator begin() const;
554 iterator end() const;
555
556private:
557 friend class SVal;
558
559 PointerToMember() = default;
560 explicit PointerToMember(const PTMDataType D)
561 : NonLoc(PointerToMemberKind, D.getOpaqueValue()) {}
562
563 static bool isKind(const SVal& V) {
564 return V.getBaseKind() == NonLocKind &&
565 V.getSubKind() == PointerToMemberKind;
566 }
567
568 static bool isKind(const NonLoc& V) {
569 return V.getSubKind() == PointerToMemberKind;
570 }
571};
572
573} // namespace nonloc
574
575//==------------------------------------------------------------------------==//
576// Subclasses of Loc.
577//==------------------------------------------------------------------------==//
578
579namespace loc {
580
581class GotoLabel : public Loc {
582public:
583 explicit GotoLabel(const LabelDecl *Label) : Loc(GotoLabelKind, Label) {
584 assert(Label)(static_cast <bool> (Label) ? void (0) : __assert_fail (
"Label", "clang/include/clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
, 584, __extension__ __PRETTY_FUNCTION__))
;
585 }
586
587 const LabelDecl *getLabel() const {
588 return static_cast<const LabelDecl *>(Data);
589 }
590
591private:
592 friend class SVal;
593
594 GotoLabel() = default;
595
596 static bool isKind(const SVal& V) {
597 return V.getBaseKind() == LocKind && V.getSubKind() == GotoLabelKind;
598 }
599
600 static bool isKind(const Loc& V) {
601 return V.getSubKind() == GotoLabelKind;
602 }
603};
604
605class MemRegionVal : public Loc {
606public:
607 explicit MemRegionVal(const MemRegion* r) : Loc(MemRegionValKind, r) {
608 assert(r)(static_cast <bool> (r) ? void (0) : __assert_fail ("r"
, "clang/include/clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
, 608, __extension__ __PRETTY_FUNCTION__))
;
609 }
610
611 /// Get the underlining region.
612 const MemRegion *getRegion() const {
613 return static_cast<const MemRegion *>(Data);
614 }
615
616 /// Get the underlining region and strip casts.
617 const MemRegion* stripCasts(bool StripBaseCasts = true) const;
618
619 template <typename REGION>
620 const REGION* getRegionAs() const {
621 return dyn_cast<REGION>(getRegion());
622 }
623
624 bool operator==(const MemRegionVal &R) const {
625 return getRegion() == R.getRegion();
626 }
627
628 bool operator!=(const MemRegionVal &R) const {
629 return getRegion() != R.getRegion();
630 }
631
632private:
633 friend class SVal;
634
635 MemRegionVal() = default;
636
637 static bool isKind(const SVal& V) {
638 return V.getBaseKind() == LocKind &&
639 V.getSubKind() == MemRegionValKind;
640 }
641
642 static bool isKind(const Loc& V) {
643 return V.getSubKind() == MemRegionValKind;
644 }
645};
646
647class ConcreteInt : public Loc {
648public:
649 explicit ConcreteInt(const llvm::APSInt& V) : Loc(ConcreteIntKind, &V) {}
650
651 const llvm::APSInt &getValue() const {
652 return *static_cast<const llvm::APSInt *>(Data);
653 }
654
655 // Transfer functions for binary/unary operations on ConcreteInts.
656 SVal evalBinOp(BasicValueFactory& BasicVals, BinaryOperator::Opcode Op,
657 const ConcreteInt& R) const;
658
659private:
660 friend class SVal;
661
662 ConcreteInt() = default;
663
664 static bool isKind(const SVal& V) {
665 return V.getBaseKind() == LocKind &&
666 V.getSubKind() == ConcreteIntKind;
667 }
668
669 static bool isKind(const Loc& V) {
670 return V.getSubKind() == ConcreteIntKind;
671 }
672};
673
674} // namespace loc
675
676} // namespace ento
677
678} // namespace clang
679
680#endif // LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_SVALS_H

/build/llvm-toolchain-snapshot-14~++20220118101002+ec47dba1c8a2/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
82 ProgramStateManager *stateMgr;
83 Environment Env; // Maps a Stmt to its current SVal.
84 Store store; // Maps a location to its current value.
85 GenericDataMap GDM; // Custom data stored by a client of this class.
86 unsigned refCount;
87
88 /// makeWithStore - Return a ProgramState with the same values as the current
89 /// state with the exception of using the specified Store.
90 ProgramStateRef makeWithStore(const StoreRef &store) const;
91
92 void setStore(const StoreRef &storeRef);
93
94public:
95 /// This ctor is used when creating the first ProgramState object.
96 ProgramState(ProgramStateManager *mgr, const Environment& env,
97 StoreRef st, GenericDataMap gdm);
98
99 /// Copy ctor - We must explicitly define this or else the "Next" ptr
100 /// in FoldingSetNode will also get copied.
101 ProgramState(const ProgramState &RHS);
102
103 ~ProgramState();
104
105 int64_t getID() const;
106
107 /// Return the ProgramStateManager associated with this state.
108 ProgramStateManager &getStateManager() const {
109 return *stateMgr;
110 }
111
112 AnalysisManager &getAnalysisManager() const;
113
114 /// Return the ConstraintManager.
115 ConstraintManager &getConstraintManager() const;
116
117 /// getEnvironment - Return the environment associated with this state.
118 /// The environment is the mapping from expressions to values.
119 const Environment& getEnvironment() const { return Env; }
120
121 /// Return the store associated with this state. The store
122 /// is a mapping from locations to values.
123 Store getStore() const { return store; }
124
125
126 /// getGDM - Return the generic data map associated with this state.
127 GenericDataMap getGDM() const { return GDM; }
128
129 void setGDM(GenericDataMap gdm) { GDM = gdm; }
130
131 /// Profile - Profile the contents of a ProgramState object for use in a
132 /// FoldingSet. Two ProgramState objects are considered equal if they
133 /// have the same Environment, Store, and GenericDataMap.
134 static void Profile(llvm::FoldingSetNodeID& ID, const ProgramState *V) {
135 V->Env.Profile(ID);
136 ID.AddPointer(V->store);
137 V->GDM.Profile(ID);
138 }
139
140 /// Profile - Used to profile the contents of this object for inclusion
141 /// in a FoldingSet.
142 void Profile(llvm::FoldingSetNodeID& ID) const {
143 Profile(ID, this);
144 }
145
146 BasicValueFactory &getBasicVals() const;
147 SymbolManager &getSymbolManager() const;
148
149 //==---------------------------------------------------------------------==//
150 // Constraints on values.
151 //==---------------------------------------------------------------------==//
152 //
153 // Each ProgramState records constraints on symbolic values. These constraints
154 // are managed using the ConstraintManager associated with a ProgramStateManager.
155 // As constraints gradually accrue on symbolic values, added constraints
156 // may conflict and indicate that a state is infeasible (as no real values
157 // could satisfy all the constraints). This is the principal mechanism
158 // for modeling path-sensitivity in ExprEngine/ProgramState.
159 //
160 // Various "assume" methods form the interface for adding constraints to
161 // symbolic values. A call to 'assume' indicates an assumption being placed
162 // on one or symbolic values. 'assume' methods take the following inputs:
163 //
164 // (1) A ProgramState object representing the current state.
165 //
166 // (2) The assumed constraint (which is specific to a given "assume" method).
167 //
168 // (3) A binary value "Assumption" that indicates whether the constraint is
169 // assumed to be true or false.
170 //
171 // The output of "assume*" is a new ProgramState object with the added constraints.
172 // If no new state is feasible, NULL is returned.
173 //
174
175 /// Assumes that the value of \p cond is zero (if \p assumption is "false")
176 /// or non-zero (if \p assumption is "true").
177 ///
178 /// This returns a new state with the added constraint on \p cond.
179 /// If no new state is feasible, NULL is returned.
180 LLVM_NODISCARD[[clang::warn_unused_result]] ProgramStateRef assume(DefinedOrUnknownSVal cond,
181 bool assumption) const;
182
183 /// Assumes both "true" and "false" for \p cond, and returns both
184 /// corresponding states (respectively).
185 ///
186 /// This is more efficient than calling assume() twice. Note that one (but not
187 /// both) of the returned states may be NULL.
188 LLVM_NODISCARD[[clang::warn_unused_result]] std::pair<ProgramStateRef, ProgramStateRef>
189 assume(DefinedOrUnknownSVal cond) const;
190
191 LLVM_NODISCARD[[clang::warn_unused_result]] ProgramStateRef
192 assumeInBound(DefinedOrUnknownSVal idx, DefinedOrUnknownSVal upperBound,
193 bool assumption, QualType IndexType = QualType()) const;
194
195 /// Assumes that the value of \p Val is bounded with [\p From; \p To]
196 /// (if \p assumption is "true") or it is fully out of this range
197 /// (if \p assumption is "false").
198 ///
199 /// This returns a new state with the added constraint on \p cond.
200 /// If no new state is feasible, NULL is returned.
201 LLVM_NODISCARD[[clang::warn_unused_result]] ProgramStateRef assumeInclusiveRange(DefinedOrUnknownSVal Val,
202 const llvm::APSInt &From,
203 const llvm::APSInt &To,
204 bool assumption) const;
205
206 /// Assumes given range both "true" and "false" for \p Val, and returns both
207 /// corresponding states (respectively).
208 ///
209 /// This is more efficient than calling assume() twice. Note that one (but not
210 /// both) of the returned states may be NULL.
211 LLVM_NODISCARD[[clang::warn_unused_result]] std::pair<ProgramStateRef, ProgramStateRef>
212 assumeInclusiveRange(DefinedOrUnknownSVal Val, const llvm::APSInt &From,
213 const llvm::APSInt &To) const;
214
215 /// Check if the given SVal is not constrained to zero and is not
216 /// a zero constant.
217 ConditionTruthVal isNonNull(SVal V) const;
218
219 /// Check if the given SVal is constrained to zero or is a zero
220 /// constant.
221 ConditionTruthVal isNull(SVal V) const;
222
223 /// \return Whether values \p Lhs and \p Rhs are equal.
224 ConditionTruthVal areEqual(SVal Lhs, SVal Rhs) const;
225
226 /// Utility method for getting regions.
227 const VarRegion* getRegion(const VarDecl *D, const LocationContext *LC) const;
228
229 //==---------------------------------------------------------------------==//
230 // Binding and retrieving values to/from the environment and symbolic store.
231 //==---------------------------------------------------------------------==//
232
233 /// Create a new state by binding the value 'V' to the statement 'S' in the
234 /// state's environment.
235 LLVM_NODISCARD[[clang::warn_unused_result]] ProgramStateRef BindExpr(const Stmt *S,
236 const LocationContext *LCtx, SVal V,
237 bool Invalidate = true) const;
238
239 LLVM_NODISCARD[[clang::warn_unused_result]] ProgramStateRef bindLoc(Loc location, SVal V,
240 const LocationContext *LCtx,
241 bool notifyChanges = true) const;
242
243 LLVM_NODISCARD[[clang::warn_unused_result]] ProgramStateRef bindLoc(SVal location, SVal V,
244 const LocationContext *LCtx) const;
245
246 /// Initializes the region of memory represented by \p loc with an initial
247 /// value. Once initialized, all values loaded from any sub-regions of that
248 /// region will be equal to \p V, unless overwritten later by the program.
249 /// This method should not be used on regions that are already initialized.
250 /// If you need to indicate that memory contents have suddenly become unknown
251 /// within a certain region of memory, consider invalidateRegions().
252 LLVM_NODISCARD[[clang::warn_unused_result]] ProgramStateRef
253 bindDefaultInitial(SVal loc, SVal V, const LocationContext *LCtx) const;
254
255 /// Performs C++ zero-initialization procedure on the region of memory
256 /// represented by \p loc.
257 LLVM_NODISCARD[[clang::warn_unused_result]] ProgramStateRef
258 bindDefaultZero(SVal loc, const LocationContext *LCtx) const;
259
260 LLVM_NODISCARD[[clang::warn_unused_result]] ProgramStateRef killBinding(Loc LV) const;
261
262 /// Returns the state with bindings for the given regions
263 /// cleared from the store.
264 ///
265 /// Optionally invalidates global regions as well.
266 ///
267 /// \param Regions the set of regions to be invalidated.
268 /// \param E the expression that caused the invalidation.
269 /// \param BlockCount The number of times the current basic block has been
270 // visited.
271 /// \param CausesPointerEscape the flag is set to true when
272 /// the invalidation entails escape of a symbol (representing a
273 /// pointer). For example, due to it being passed as an argument in a
274 /// call.
275 /// \param IS the set of invalidated symbols.
276 /// \param Call if non-null, the invalidated regions represent parameters to
277 /// the call and should be considered directly invalidated.
278 /// \param ITraits information about special handling for a particular
279 /// region/symbol.
280 LLVM_NODISCARD[[clang::warn_unused_result]] ProgramStateRef
281 invalidateRegions(ArrayRef<const MemRegion *> Regions, const Expr *E,
282 unsigned BlockCount, const LocationContext *LCtx,
283 bool CausesPointerEscape, InvalidatedSymbols *IS = nullptr,
284 const CallEvent *Call = nullptr,
285 RegionAndSymbolInvalidationTraits *ITraits = nullptr) const;
286
287 LLVM_NODISCARD[[clang::warn_unused_result]] ProgramStateRef
288 invalidateRegions(ArrayRef<SVal> Regions, const Expr *E,
289 unsigned BlockCount, const LocationContext *LCtx,
290 bool CausesPointerEscape, InvalidatedSymbols *IS = nullptr,
291 const CallEvent *Call = nullptr,
292 RegionAndSymbolInvalidationTraits *ITraits = nullptr) const;
293
294 /// enterStackFrame - Returns the state for entry to the given stack frame,
295 /// preserving the current state.
296 LLVM_NODISCARD[[clang::warn_unused_result]] ProgramStateRef enterStackFrame(
297 const CallEvent &Call, const StackFrameContext *CalleeCtx) const;
298
299 /// Return the value of 'self' if available in the given context.
300 SVal getSelfSVal(const LocationContext *LC) const;
301
302 /// Get the lvalue for a base class object reference.
303 Loc getLValue(const CXXBaseSpecifier &BaseSpec, const SubRegion *Super) const;
304
305 /// Get the lvalue for a base class object reference.
306 Loc getLValue(const CXXRecordDecl *BaseClass, const SubRegion *Super,
307 bool IsVirtual) const;
308
309 /// Get the lvalue for a parameter.
310 Loc getLValue(const Expr *Call, unsigned Index,
311 const LocationContext *LC) const;
312
313 /// Get the lvalue for a variable reference.
314 Loc getLValue(const VarDecl *D, const LocationContext *LC) const;
315
316 Loc getLValue(const CompoundLiteralExpr *literal,
317 const LocationContext *LC) const;
318
319 /// Get the lvalue for an ivar reference.
320 SVal getLValue(const ObjCIvarDecl *decl, SVal base) const;
321
322 /// Get the lvalue for a field reference.
323 SVal getLValue(const FieldDecl *decl, SVal Base) const;
324
325 /// Get the lvalue for an indirect field reference.
326 SVal getLValue(const IndirectFieldDecl *decl, SVal Base) const;
327
328 /// Get the lvalue for an array index.
329 SVal getLValue(QualType ElementType, SVal Idx, SVal Base) const;
330
331 /// Returns the SVal bound to the statement 'S' in the state's environment.
332 SVal getSVal(const Stmt *S, const LocationContext *LCtx) const;
333
334 SVal getSValAsScalarOrLoc(const Stmt *Ex, const LocationContext *LCtx) const;
335
336 /// Return the value bound to the specified location.
337 /// Returns UnknownVal() if none found.
338 SVal getSVal(Loc LV, QualType T = QualType()) const;
339
340 /// Returns the "raw" SVal bound to LV before any value simplfication.
341 SVal getRawSVal(Loc LV, QualType T= QualType()) const;
342
343 /// Return the value bound to the specified location.
344 /// Returns UnknownVal() if none found.
345 SVal getSVal(const MemRegion* R, QualType T = QualType()) const;
346
347 /// Return the value bound to the specified location, assuming
348 /// that the value is a scalar integer or an enumeration or a pointer.
349 /// Returns UnknownVal() if none found or the region is not known to hold
350 /// a value of such type.
351 SVal getSValAsScalarOrLoc(const MemRegion *R) const;
352
353 using region_iterator = const MemRegion **;
354
355 /// Visits the symbols reachable from the given SVal using the provided
356 /// SymbolVisitor.
357 ///
358 /// This is a convenience API. Consider using ScanReachableSymbols class
359 /// directly when making multiple scans on the same state with the same
360 /// visitor to avoid repeated initialization cost.
361 /// \sa ScanReachableSymbols
362 bool scanReachableSymbols(SVal val, SymbolVisitor& visitor) const;
363
364 /// Visits the symbols reachable from the regions in the given
365 /// MemRegions range using the provided SymbolVisitor.
366 bool scanReachableSymbols(llvm::iterator_range<region_iterator> Reachable,
367 SymbolVisitor &visitor) const;
368
369 template <typename CB> CB scanReachableSymbols(SVal val) const;
370 template <typename CB> CB
371 scanReachableSymbols(llvm::iterator_range<region_iterator> Reachable) const;
372
373 //==---------------------------------------------------------------------==//
374 // Accessing the Generic Data Map (GDM).
375 //==---------------------------------------------------------------------==//
376
377 void *const* FindGDM(void *K) const;
378
379 template <typename T>
380 LLVM_NODISCARD[[clang::warn_unused_result]] ProgramStateRef
381 add(typename ProgramStateTrait<T>::key_type K) const;
382
383 template <typename T>
384 typename ProgramStateTrait<T>::data_type
385 get() const {
386 return ProgramStateTrait<T>::MakeData(FindGDM(ProgramStateTrait<T>::GDMIndex()));
387 }
388
389 template<typename T>
390 typename ProgramStateTrait<T>::lookup_type
391 get(typename ProgramStateTrait<T>::key_type key) const {
392 void *const* d = FindGDM(ProgramStateTrait<T>::GDMIndex());
393 return ProgramStateTrait<T>::Lookup(ProgramStateTrait<T>::MakeData(d), key);
394 }
395
396 template <typename T>
397 typename ProgramStateTrait<T>::context_type get_context() const;
398
399 template <typename T>
400 LLVM_NODISCARD[[clang::warn_unused_result]] ProgramStateRef
401 remove(typename ProgramStateTrait<T>::key_type K) const;
402
403 template <typename T>
404 LLVM_NODISCARD[[clang::warn_unused_result]] ProgramStateRef
405 remove(typename ProgramStateTrait<T>::key_type K,
406 typename ProgramStateTrait<T>::context_type C) const;
407
408 template <typename T> LLVM_NODISCARD[[clang::warn_unused_result]] ProgramStateRef remove() const;
409
410 template <typename T>
411 LLVM_NODISCARD[[clang::warn_unused_result]] ProgramStateRef
412 set(typename ProgramStateTrait<T>::data_type D) const;
413
414 template <typename T>
415 LLVM_NODISCARD[[clang::warn_unused_result]] ProgramStateRef
416 set(typename ProgramStateTrait<T>::key_type K,
417 typename ProgramStateTrait<T>::value_type E) const;
418
419 template <typename T>
420 LLVM_NODISCARD[[clang::warn_unused_result]] ProgramStateRef
421 set(typename ProgramStateTrait<T>::key_type K,
422 typename ProgramStateTrait<T>::value_type E,
423 typename ProgramStateTrait<T>::context_type C) const;
424
425 template<typename T>
426 bool contains(typename ProgramStateTrait<T>::key_type key) const {
427 void *const* d = FindGDM(ProgramStateTrait<T>::GDMIndex());
428 return ProgramStateTrait<T>::Contains(ProgramStateTrait<T>::MakeData(d), key);
429 }
430