Bug Summary

File:clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
Warning:line 1453, 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 -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 -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-12/lib/clang/12.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/build-llvm/tools/clang/lib/StaticAnalyzer/Checkers -I /build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/clang/lib/StaticAnalyzer/Checkers -I /build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/clang/include -I /build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/build-llvm/include -I /build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-12/lib/clang/12.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/build-llvm/tools/clang/lib/StaticAnalyzer/Checkers -fdebug-prefix-map=/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-11-29-190409-37574-1 -x c++ /build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp

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

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

1// <tuple> -*- C++ -*-
2
3// Copyright (C) 2007-2016 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
42namespace std _GLIBCXX_VISIBILITY(default)__attribute__ ((__visibility__ ("default")))
43{
44_GLIBCXX_BEGIN_NAMESPACE_VERSION
45
46 /**
47 * @addtogroup utilities
48 * @{
49 */
50
51 template<std::size_t _Idx, typename _Head, bool _IsEmptyNotFinal>
52 struct _Head_base;
53
54 template<std::size_t _Idx, typename _Head>
55 struct _Head_base<_Idx, _Head, true>
56 : public _Head
57 {
58 constexpr _Head_base()
59 : _Head() { }
60
61 constexpr _Head_base(const _Head& __h)
62 : _Head(__h) { }
63
64 constexpr _Head_base(const _Head_base&) = default;
65 constexpr _Head_base(_Head_base&&) = default;
66
67 template<typename _UHead>
68 constexpr _Head_base(_UHead&& __h)
69 : _Head(std::forward<_UHead>(__h)) { }
70
71 _Head_base(allocator_arg_t, __uses_alloc0)
72 : _Head() { }
73
74 template<typename _Alloc>
75 _Head_base(allocator_arg_t, __uses_alloc1<_Alloc> __a)
76 : _Head(allocator_arg, *__a._M_a) { }
77
78 template<typename _Alloc>
79 _Head_base(allocator_arg_t, __uses_alloc2<_Alloc> __a)
80 : _Head(*__a._M_a) { }
81
82 template<typename _UHead>
83 _Head_base(__uses_alloc0, _UHead&& __uhead)
84 : _Head(std::forward<_UHead>(__uhead)) { }
85
86 template<typename _Alloc, typename _UHead>
87 _Head_base(__uses_alloc1<_Alloc> __a, _UHead&& __uhead)
88 : _Head(allocator_arg, *__a._M_a, std::forward<_UHead>(__uhead)) { }
89
90 template<typename _Alloc, typename _UHead>
91 _Head_base(__uses_alloc2<_Alloc> __a, _UHead&& __uhead)
92 : _Head(std::forward<_UHead>(__uhead), *__a._M_a) { }
93
94 static constexpr _Head&
95 _M_head(_Head_base& __b) noexcept { return __b; }
96
97 static constexpr const _Head&
98 _M_head(const _Head_base& __b) noexcept { return __b; }
99 };
100
101 template<std::size_t _Idx, typename _Head>
102 struct _Head_base<_Idx, _Head, false>
103 {
104 constexpr _Head_base()
105 : _M_head_impl() { }
106
107 constexpr _Head_base(const _Head& __h)
108 : _M_head_impl(__h) { }
109
110 constexpr _Head_base(const _Head_base&) = default;
111 constexpr _Head_base(_Head_base&&) = default;
112
113 template<typename _UHead>
114 constexpr _Head_base(_UHead&& __h)
115 : _M_head_impl(std::forward<_UHead>(__h)) { }
116
117 _Head_base(allocator_arg_t, __uses_alloc0)
118 : _M_head_impl() { }
119
120 template<typename _Alloc>
121 _Head_base(allocator_arg_t, __uses_alloc1<_Alloc> __a)
122 : _M_head_impl(allocator_arg, *__a._M_a) { }
123
124 template<typename _Alloc>
125 _Head_base(allocator_arg_t, __uses_alloc2<_Alloc> __a)
126 : _M_head_impl(*__a._M_a) { }
127
128 template<typename _UHead>
129 _Head_base(__uses_alloc0, _UHead&& __uhead)
130 : _M_head_impl(std::forward<_UHead>(__uhead)) { }
131
132 template<typename _Alloc, typename _UHead>
133 _Head_base(__uses_alloc1<_Alloc> __a, _UHead&& __uhead)
134 : _M_head_impl(allocator_arg, *__a._M_a, std::forward<_UHead>(__uhead))
135 { }
136
137 template<typename _Alloc, typename _UHead>
138 _Head_base(__uses_alloc2<_Alloc> __a, _UHead&& __uhead)
139 : _M_head_impl(std::forward<_UHead>(__uhead), *__a._M_a) { }
140
141 static constexpr _Head&
142 _M_head(_Head_base& __b) noexcept { return __b._M_head_impl; }
143
144 static constexpr const _Head&
145 _M_head(const _Head_base& __b) noexcept { return __b._M_head_impl; }
146
147 _Head _M_head_impl;
148 };
149
150 /**
151 * Contains the actual implementation of the @c tuple template, stored
152 * as a recursive inheritance hierarchy from the first element (most
153 * derived class) to the last (least derived class). The @c Idx
154 * parameter gives the 0-based index of the element stored at this
155 * point in the hierarchy; we use it to implement a constant-time
156 * get() operation.
157 */
158 template<std::size_t _Idx, typename... _Elements>
159 struct _Tuple_impl;
160
161 template<typename _Tp>
162 struct __is_empty_non_tuple : is_empty<_Tp> { };
163
164 // Using EBO for elements that are tuples causes ambiguous base errors.
165 template<typename _El0, typename... _El>
166 struct __is_empty_non_tuple<tuple<_El0, _El...>> : false_type { };
167
168 // Use the Empty Base-class Optimization for empty, non-final types.
169 template<typename _Tp>
170 using __empty_not_final
171 = typename conditional<__is_final(_Tp), false_type,
172 __is_empty_non_tuple<_Tp>>::type;
173
174 /**
175 * Recursive tuple implementation. Here we store the @c Head element
176 * and derive from a @c Tuple_impl containing the remaining elements
177 * (which contains the @c Tail).
178 */
179 template<std::size_t _Idx, typename _Head, typename... _Tail>
180 struct _Tuple_impl<_Idx, _Head, _Tail...>
181 : public _Tuple_impl<_Idx + 1, _Tail...>,
182 private _Head_base<_Idx, _Head, __empty_not_final<_Head>::value>
183 {
184 template<std::size_t, typename...> friend class _Tuple_impl;
185
186 typedef _Tuple_impl<_Idx + 1, _Tail...> _Inherited;
187 typedef _Head_base<_Idx, _Head, __empty_not_final<_Head>::value> _Base;
188
189 static constexpr _Head&
190 _M_head(_Tuple_impl& __t) noexcept { return _Base::_M_head(__t); }
191
192 static constexpr const _Head&
193 _M_head(const _Tuple_impl& __t) noexcept { return _Base::_M_head(__t); }
194
195 static constexpr _Inherited&
196 _M_tail(_Tuple_impl& __t) noexcept { return __t; }
197
198 static constexpr const _Inherited&
199 _M_tail(const _Tuple_impl& __t) noexcept { return __t; }
200
201 constexpr _Tuple_impl()
202 : _Inherited(), _Base() { }
203
204 explicit
205 constexpr _Tuple_impl(const _Head& __head, const _Tail&... __tail)
206 : _Inherited(__tail...), _Base(__head) { }
12
Calling constructor for '_Tuple_impl<1, llvm::IntrusiveRefCntPtr<const clang::ento::ProgramState> &>'
15
Returning from constructor for '_Tuple_impl<1, llvm::IntrusiveRefCntPtr<const clang::ento::ProgramState> &>'
207
208 template<typename _UHead, typename... _UTail, typename = typename
209 enable_if<sizeof...(_Tail) == sizeof...(_UTail)>::type>
210 explicit
211 constexpr _Tuple_impl(_UHead&& __head, _UTail&&... __tail)
212 : _Inherited(std::forward<_UTail>(__tail)...),
213 _Base(std::forward<_UHead>(__head)) { }
214
215 constexpr _Tuple_impl(const _Tuple_impl&) = default;
216
217 constexpr
218 _Tuple_impl(_Tuple_impl&& __in)
219 noexcept(__and_<is_nothrow_move_constructible<_Head>,
220 is_nothrow_move_constructible<_Inherited>>::value)
221 : _Inherited(std::move(_M_tail(__in))),
222 _Base(std::forward<_Head>(_M_head(__in))) { }
223
224 template<typename... _UElements>
225 constexpr _Tuple_impl(const _Tuple_impl<_Idx, _UElements...>& __in)
226 : _Inherited(_Tuple_impl<_Idx, _UElements...>::_M_tail(__in)),
227 _Base(_Tuple_impl<_Idx, _UElements...>::_M_head(__in)) { }
228
229 template<typename _UHead, typename... _UTails>
230 constexpr _Tuple_impl(_Tuple_impl<_Idx, _UHead, _UTails...>&& __in)
231 : _Inherited(std::move
232 (_Tuple_impl<_Idx, _UHead, _UTails...>::_M_tail(__in))),
233 _Base(std::forward<_UHead>
234 (_Tuple_impl<_Idx, _UHead, _UTails...>::_M_head(__in))) { }
235
236 template<typename _Alloc>
237 _Tuple_impl(allocator_arg_t __tag, const _Alloc& __a)
238 : _Inherited(__tag, __a),
239 _Base(__tag, __use_alloc<_Head>(__a)) { }
240
241 template<typename _Alloc>
242 _Tuple_impl(allocator_arg_t __tag, const _Alloc& __a,
243 const _Head& __head, const _Tail&... __tail)
244 : _Inherited(__tag, __a, __tail...),
245 _Base(__use_alloc<_Head, _Alloc, _Head>(__a), __head) { }
246
247 template<typename _Alloc, typename _UHead, typename... _UTail,
248 typename = typename enable_if<sizeof...(_Tail)
249 == sizeof...(_UTail)>::type>
250 _Tuple_impl(allocator_arg_t __tag, const _Alloc& __a,
251 _UHead&& __head, _UTail&&... __tail)
252 : _Inherited(__tag, __a, std::forward<_UTail>(__tail)...),
253 _Base(__use_alloc<_Head, _Alloc, _UHead>(__a),
254 std::forward<_UHead>(__head)) { }
255
256 template<typename _Alloc>
257 _Tuple_impl(allocator_arg_t __tag, const _Alloc& __a,
258 const _Tuple_impl& __in)
259 : _Inherited(__tag, __a, _M_tail(__in)),
260 _Base(__use_alloc<_Head, _Alloc, _Head>(__a), _M_head(__in)) { }
261
262 template<typename _Alloc>
263 _Tuple_impl(allocator_arg_t __tag, const _Alloc& __a,
264 _Tuple_impl&& __in)
265 : _Inherited(__tag, __a, std::move(_M_tail(__in))),
266 _Base(__use_alloc<_Head, _Alloc, _Head>(__a),
267 std::forward<_Head>(_M_head(__in))) { }
268
269 template<typename _Alloc, typename... _UElements>
270 _Tuple_impl(allocator_arg_t __tag, const _Alloc& __a,
271 const _Tuple_impl<_Idx, _UElements...>& __in)
272 : _Inherited(__tag, __a,
273 _Tuple_impl<_Idx, _UElements...>::_M_tail(__in)),
274 _Base(__use_alloc<_Head, _Alloc, _Head>(__a),
275 _Tuple_impl<_Idx, _UElements...>::_M_head(__in)) { }
276
277 template<typename _Alloc, typename _UHead, typename... _UTails>
278 _Tuple_impl(allocator_arg_t __tag, const _Alloc& __a,
279 _Tuple_impl<_Idx, _UHead, _UTails...>&& __in)
280 : _Inherited(__tag, __a, std::move
281 (_Tuple_impl<_Idx, _UHead, _UTails...>::_M_tail(__in))),
282 _Base(__use_alloc<_Head, _Alloc, _UHead>(__a),
283 std::forward<_UHead>
284 (_Tuple_impl<_Idx, _UHead, _UTails...>::_M_head(__in))) { }
285
286 _Tuple_impl&
287 operator=(const _Tuple_impl& __in)
288 {
289 _M_head(*this) = _M_head(__in);
290 _M_tail(*this) = _M_tail(__in);
291 return *this;
292 }
293
294 _Tuple_impl&
295 operator=(_Tuple_impl&& __in)
296 noexcept(__and_<is_nothrow_move_assignable<_Head>,
297 is_nothrow_move_assignable<_Inherited>>::value)
298 {
299 _M_head(*this) = std::forward<_Head>(_M_head(__in));
300 _M_tail(*this) = std::move(_M_tail(__in));
301 return *this;
302 }
303
304 template<typename... _UElements>
305 _Tuple_impl&
306 operator=(const _Tuple_impl<_Idx, _UElements...>& __in)
307 {
308 _M_head(*this) = _Tuple_impl<_Idx, _UElements...>::_M_head(__in);
309 _M_tail(*this) = _Tuple_impl<_Idx, _UElements...>::_M_tail(__in);
310 return *this;
311 }
312
313 template<typename _UHead, typename... _UTails>
314 _Tuple_impl&
315 operator=(_Tuple_impl<_Idx, _UHead, _UTails...>&& __in)
316 {
317 _M_head(*this) = std::forward<_UHead>
318 (_Tuple_impl<_Idx, _UHead, _UTails...>::_M_head(__in));
319 _M_tail(*this) = std::move
320 (_Tuple_impl<_Idx, _UHead, _UTails...>::_M_tail(__in));
321 return *this;
322 }
323
324 protected:
325 void
326 _M_swap(_Tuple_impl& __in)
327 noexcept(__is_nothrow_swappable<_Head>::value
328 && noexcept(_M_tail(__in)._M_swap(_M_tail(__in))))
329 {
330 using std::swap;
331 swap(_M_head(*this), _M_head(__in));
332 _Inherited::_M_swap(_M_tail(__in));
333 }
334 };
335
336 // Basis case of inheritance recursion.
337 template<std::size_t _Idx, typename _Head>
338 struct _Tuple_impl<_Idx, _Head>
339 : private _Head_base<_Idx, _Head, __empty_not_final<_Head>::value>
340 {
341 template<std::size_t, typename...> friend class _Tuple_impl;
342
343 typedef _Head_base<_Idx, _Head, __empty_not_final<_Head>::value> _Base;
344
345 static constexpr _Head&
346 _M_head(_Tuple_impl& __t) noexcept { return _Base::_M_head(__t); }
347
348 static constexpr const _Head&
349 _M_head(const _Tuple_impl& __t) noexcept { return _Base::_M_head(__t); }
350
351 constexpr _Tuple_impl()
352 : _Base() { }
353
354 explicit
355 constexpr _Tuple_impl(const _Head& __head)
356 : _Base(__head) { }
13
Calling constructor for '_Head_base<1, llvm::IntrusiveRefCntPtr<const clang::ento::ProgramState> &, false>'
14
Returning from constructor for '_Head_base<1, llvm::IntrusiveRefCntPtr<const clang::ento::ProgramState> &, false>'
357
358 template<typename _UHead>
359 explicit
360 constexpr _Tuple_impl(_UHead&& __head)
361 : _Base(std::forward<_UHead>(__head)) { }
362
363 constexpr _Tuple_impl(const _Tuple_impl&) = default;
364
365 constexpr
366 _Tuple_impl(_Tuple_impl&& __in)
367 noexcept(is_nothrow_move_constructible<_Head>::value)
368 : _Base(std::forward<_Head>(_M_head(__in))) { }
369
370 template<typename _UHead>
371 constexpr _Tuple_impl(const _Tuple_impl<_Idx, _UHead>& __in)
372 : _Base(_Tuple_impl<_Idx, _UHead>::_M_head(__in)) { }
373
374 template<typename _UHead>
375 constexpr _Tuple_impl(_Tuple_impl<_Idx, _UHead>&& __in)
376 : _Base(std::forward<_UHead>(_Tuple_impl<_Idx, _UHead>::_M_head(__in)))
377 { }
378
379 template<typename _Alloc>
380 _Tuple_impl(allocator_arg_t __tag, const _Alloc& __a)
381 : _Base(__tag, __use_alloc<_Head>(__a)) { }
382
383 template<typename _Alloc>
384 _Tuple_impl(allocator_arg_t __tag, const _Alloc& __a,
385 const _Head& __head)
386 : _Base(__use_alloc<_Head, _Alloc, _Head>(__a), __head) { }
387
388 template<typename _Alloc, typename _UHead>
389 _Tuple_impl(allocator_arg_t __tag, const _Alloc& __a,
390 _UHead&& __head)
391 : _Base(__use_alloc<_Head, _Alloc, _UHead>(__a),
392 std::forward<_UHead>(__head)) { }
393
394 template<typename _Alloc>
395 _Tuple_impl(allocator_arg_t __tag, const _Alloc& __a,
396 const _Tuple_impl& __in)
397 : _Base(__use_alloc<_Head, _Alloc, _Head>(__a), _M_head(__in)) { }
398
399 template<typename _Alloc>
400 _Tuple_impl(allocator_arg_t __tag, const _Alloc& __a,
401 _Tuple_impl&& __in)
402 : _Base(__use_alloc<_Head, _Alloc, _Head>(__a),
403 std::forward<_Head>(_M_head(__in))) { }
404
405 template<typename _Alloc, typename _UHead>
406 _Tuple_impl(allocator_arg_t __tag, const _Alloc& __a,
407 const _Tuple_impl<_Idx, _UHead>& __in)
408 : _Base(__use_alloc<_Head, _Alloc, _Head>(__a),
409 _Tuple_impl<_Idx, _UHead>::_M_head(__in)) { }
410
411 template<typename _Alloc, typename _UHead>
412 _Tuple_impl(allocator_arg_t __tag, const _Alloc& __a,
413 _Tuple_impl<_Idx, _UHead>&& __in)
414 : _Base(__use_alloc<_Head, _Alloc, _UHead>(__a),
415 std::forward<_UHead>(_Tuple_impl<_Idx, _UHead>::_M_head(__in)))
416 { }
417
418 _Tuple_impl&
419 operator=(const _Tuple_impl& __in)
420 {
421 _M_head(*this) = _M_head(__in);
422 return *this;
423 }
424
425 _Tuple_impl&
426 operator=(_Tuple_impl&& __in)
427 noexcept(is_nothrow_move_assignable<_Head>::value)
428 {
429 _M_head(*this) = std::forward<_Head>(_M_head(__in));
430 return *this;
431 }
432
433 template<typename _UHead>
434 _Tuple_impl&
435 operator=(const _Tuple_impl<_Idx, _UHead>& __in)
436 {
437 _M_head(*this) = _Tuple_impl<_Idx, _UHead>::_M_head(__in);
438 return *this;
439 }
440
441 template<typename _UHead>
442 _Tuple_impl&
443 operator=(_Tuple_impl<_Idx, _UHead>&& __in)
444 {
445 _M_head(*this)
446 = std::forward<_UHead>(_Tuple_impl<_Idx, _UHead>::_M_head(__in));
447 return *this;
448 }
449
450 protected:
451 void
452 _M_swap(_Tuple_impl& __in)
453 noexcept(__is_nothrow_swappable<_Head>::value)
454 {
455 using std::swap;
456 swap(_M_head(*this), _M_head(__in));
457 }
458 };
459
460 template<typename... _Elements>
461 class tuple;
462
463 // Concept utility functions, reused in conditionally-explicit
464 // constructors.
465 template<bool, typename... _Elements>
466 struct _TC
467 {
468 template<typename... _UElements>
469 static constexpr bool _ConstructibleTuple()
470 {
471 return __and_<is_constructible<_Elements, const _UElements&>...>::value;
472 }
473
474 template<typename... _UElements>
475 static constexpr bool _ImplicitlyConvertibleTuple()
476 {
477 return __and_<is_convertible<const _UElements&, _Elements>...>::value;
478 }
479
480 template<typename... _UElements>
481 static constexpr bool _MoveConstructibleTuple()
482 {
483 return __and_<is_constructible<_Elements, _UElements&&>...>::value;
484 }
485
486 template<typename... _UElements>
487 static constexpr bool _ImplicitlyMoveConvertibleTuple()
488 {
489 return __and_<is_convertible<_UElements&&, _Elements>...>::value;
490 }
491
492 template<typename _SrcTuple>
493 static constexpr bool _NonNestedTuple()
494 {
495 return __and_<__not_<is_same<tuple<_Elements...>,
496 typename remove_cv<
497 typename remove_reference<_SrcTuple>::type
498 >::type>>,
499 __not_<is_convertible<_SrcTuple, _Elements...>>,
500 __not_<is_constructible<_Elements..., _SrcTuple>>
501 >::value;
502 }
503 template<typename... _UElements>
504 static constexpr bool _NotSameTuple()
505 {
506 return __not_<is_same<tuple<_Elements...>,
507 typename remove_const<
508 typename remove_reference<_UElements...>::type
509 >::type>>::value;
510 }
511 };
512
513 template<typename... _Elements>
514 struct _TC<false, _Elements...>
515 {
516 template<typename... _UElements>
517 static constexpr bool _ConstructibleTuple()
518 {
519 return false;
520 }
521
522 template<typename... _UElements>
523 static constexpr bool _ImplicitlyConvertibleTuple()
524 {
525 return false;
526 }
527
528 template<typename... _UElements>
529 static constexpr bool _MoveConstructibleTuple()
530 {
531 return false;
532 }
533
534 template<typename... _UElements>
535 static constexpr bool _ImplicitlyMoveConvertibleTuple()
536 {
537 return false;
538 }
539
540 template<typename... _UElements>
541 static constexpr bool _NonNestedTuple()
542 {
543 return true;
544 }
545 template<typename... _UElements>
546 static constexpr bool _NotSameTuple()
547 {
548 return true;
549 }
550 };
551
552 /// Primary class template, tuple
553 template<typename... _Elements>
554 class tuple : public _Tuple_impl<0, _Elements...>
555 {
556 typedef _Tuple_impl<0, _Elements...> _Inherited;
557
558 // Used for constraining the default constructor so
559 // that it becomes dependent on the constraints.
560 template<typename _Dummy>
561 struct _TC2
562 {
563 static constexpr bool _DefaultConstructibleTuple()
564 {
565 return __and_<is_default_constructible<_Elements>...>::value;
566 }
567 static constexpr bool _ImplicitlyDefaultConstructibleTuple()
568 {
569 return __and_<__is_implicitly_default_constructible<_Elements>...>
570 ::value;
571 }
572 };
573
574 public:
575 template<typename _Dummy = void,
576 typename enable_if<_TC2<_Dummy>::
577 _ImplicitlyDefaultConstructibleTuple(),
578 bool>::type = true>
579 constexpr tuple()
580 : _Inherited() { }
581
582 template<typename _Dummy = void,
583 typename enable_if<_TC2<_Dummy>::
584 _DefaultConstructibleTuple()
585 &&
586 !_TC2<_Dummy>::
587 _ImplicitlyDefaultConstructibleTuple(),
588 bool>::type = false>
589 explicit constexpr tuple()
590 : _Inherited() { }
591
592 // Shortcut for the cases where constructors taking _Elements...
593 // need to be constrained.
594 template<typename _Dummy> using _TCC =
595 _TC<is_same<_Dummy, void>::value,
596 _Elements...>;
597
598 template<typename _Dummy = void,
599 typename enable_if<
600 _TCC<_Dummy>::template
601 _ConstructibleTuple<_Elements...>()
602 && _TCC<_Dummy>::template
603 _ImplicitlyConvertibleTuple<_Elements...>()
604 && (sizeof...(_Elements) >= 1),
605 bool>::type=true>
606 constexpr tuple(const _Elements&... __elements)
607 : _Inherited(__elements...) { }
608
609 template<typename _Dummy = void,
610 typename enable_if<
611 _TCC<_Dummy>::template
612 _ConstructibleTuple<_Elements...>()
613 && !_TCC<_Dummy>::template
614 _ImplicitlyConvertibleTuple<_Elements...>()
615 && (sizeof...(_Elements) >= 1),
616 bool>::type=false>
617 explicit constexpr tuple(const _Elements&... __elements)
618 : _Inherited(__elements...) { }
619
620 // Shortcut for the cases where constructors taking _UElements...
621 // need to be constrained.
622 template<typename... _UElements> using _TMC =
623 _TC<(sizeof...(_Elements) == sizeof...(_UElements)),
624 _Elements...>;
625
626 template<typename... _UElements, typename
627 enable_if<
628 _TC<sizeof...(_UElements) == 1, _Elements...>::template
629 _NotSameTuple<_UElements...>()
630 && _TMC<_UElements...>::template
631 _MoveConstructibleTuple<_UElements...>()
632 && _TMC<_UElements...>::template
633 _ImplicitlyMoveConvertibleTuple<_UElements...>()
634 && (sizeof...(_Elements) >= 1),
635 bool>::type=true>
636 constexpr tuple(_UElements&&... __elements)
637 : _Inherited(std::forward<_UElements>(__elements)...) { }
638
639 template<typename... _UElements, typename
640 enable_if<
641 _TC<sizeof...(_UElements) == 1, _Elements...>::template
642 _NotSameTuple<_UElements...>()
643 && _TMC<_UElements...>::template
644 _MoveConstructibleTuple<_UElements...>()
645 && !_TMC<_UElements...>::template
646 _ImplicitlyMoveConvertibleTuple<_UElements...>()
647 && (sizeof...(_Elements) >= 1),
648 bool>::type=false>
649 explicit constexpr tuple(_UElements&&... __elements)
650 : _Inherited(std::forward<_UElements>(__elements)...) { }
651
652 constexpr tuple(const tuple&) = default;
653
654 constexpr tuple(tuple&&) = default;
655
656 // Shortcut for the cases where constructors taking tuples
657 // must avoid creating temporaries.
658 template<typename _Dummy> using _TNTC =
659 _TC<is_same<_Dummy, void>::value && sizeof...(_Elements) == 1,
660 _Elements...>;
661
662 template<typename... _UElements, typename _Dummy = void, typename
663 enable_if<_TMC<_UElements...>::template
664 _ConstructibleTuple<_UElements...>()
665 && _TMC<_UElements...>::template
666 _ImplicitlyConvertibleTuple<_UElements...>()
667 && _TNTC<_Dummy>::template
668 _NonNestedTuple<const tuple<_UElements...>&>(),
669 bool>::type=true>
670 constexpr tuple(const tuple<_UElements...>& __in)
671 : _Inherited(static_cast<const _Tuple_impl<0, _UElements...>&>(__in))
672 { }
673
674 template<typename... _UElements, typename _Dummy = void, typename
675 enable_if<_TMC<_UElements...>::template
676 _ConstructibleTuple<_UElements...>()
677 && !_TMC<_UElements...>::template
678 _ImplicitlyConvertibleTuple<_UElements...>()
679 && _TNTC<_Dummy>::template
680 _NonNestedTuple<const tuple<_UElements...>&>(),
681 bool>::type=false>
682 explicit constexpr tuple(const tuple<_UElements...>& __in)
683 : _Inherited(static_cast<const _Tuple_impl<0, _UElements...>&>(__in))
684 { }
685
686 template<typename... _UElements, typename _Dummy = void, typename
687 enable_if<_TMC<_UElements...>::template
688 _MoveConstructibleTuple<_UElements...>()
689 && _TMC<_UElements...>::template
690 _ImplicitlyMoveConvertibleTuple<_UElements...>()
691 && _TNTC<_Dummy>::template
692 _NonNestedTuple<tuple<_UElements...>&&>(),
693 bool>::type=true>
694 constexpr tuple(tuple<_UElements...>&& __in)
695 : _Inherited(static_cast<_Tuple_impl<0, _UElements...>&&>(__in)) { }
696
697 template<typename... _UElements, typename _Dummy = void, typename
698 enable_if<_TMC<_UElements...>::template
699 _MoveConstructibleTuple<_UElements...>()
700 && !_TMC<_UElements...>::template
701 _ImplicitlyMoveConvertibleTuple<_UElements...>()
702 && _TNTC<_Dummy>::template
703 _NonNestedTuple<tuple<_UElements...>&&>(),
704 bool>::type=false>
705 explicit constexpr tuple(tuple<_UElements...>&& __in)
706 : _Inherited(static_cast<_Tuple_impl<0, _UElements...>&&>(__in)) { }
707
708 // Allocator-extended constructors.
709
710 template<typename _Alloc>
711 tuple(allocator_arg_t __tag, const _Alloc& __a)
712 : _Inherited(__tag, __a) { }
713
714 template<typename _Alloc, typename _Dummy = void,
715 typename enable_if<
716 _TCC<_Dummy>::template
717 _ConstructibleTuple<_Elements...>()
718 && _TCC<_Dummy>::template
719 _ImplicitlyConvertibleTuple<_Elements...>(),
720 bool>::type=true>
721 tuple(allocator_arg_t __tag, const _Alloc& __a,
722 const _Elements&... __elements)
723 : _Inherited(__tag, __a, __elements...) { }
724
725 template<typename _Alloc, typename _Dummy = void,
726 typename enable_if<
727 _TCC<_Dummy>::template
728 _ConstructibleTuple<_Elements...>()
729 && !_TCC<_Dummy>::template
730 _ImplicitlyConvertibleTuple<_Elements...>(),
731 bool>::type=false>
732 explicit tuple(allocator_arg_t __tag, const _Alloc& __a,
733 const _Elements&... __elements)
734 : _Inherited(__tag, __a, __elements...) { }
735
736 template<typename _Alloc, typename... _UElements, typename
737 enable_if<_TMC<_UElements...>::template
738 _MoveConstructibleTuple<_UElements...>()
739 && _TMC<_UElements...>::template
740 _ImplicitlyMoveConvertibleTuple<_UElements...>(),
741 bool>::type=true>
742 tuple(allocator_arg_t __tag, const _Alloc& __a,
743 _UElements&&... __elements)
744 : _Inherited(__tag, __a, std::forward<_UElements>(__elements)...)
745 { }
746
747 template<typename _Alloc, typename... _UElements, typename
748 enable_if<_TMC<_UElements...>::template
749 _MoveConstructibleTuple<_UElements...>()
750 && !_TMC<_UElements...>::template
751 _ImplicitlyMoveConvertibleTuple<_UElements...>(),
752 bool>::type=false>
753 explicit tuple(allocator_arg_t __tag, const _Alloc& __a,
754 _UElements&&... __elements)
755 : _Inherited(__tag, __a, std::forward<_UElements>(__elements)...)
756 { }
757
758 template<typename _Alloc>
759 tuple(allocator_arg_t __tag, const _Alloc& __a, const tuple& __in)
760 : _Inherited(__tag, __a, static_cast<const _Inherited&>(__in)) { }
761
762 template<typename _Alloc>
763 tuple(allocator_arg_t __tag, const _Alloc& __a, tuple&& __in)
764 : _Inherited(__tag, __a, static_cast<_Inherited&&>(__in)) { }
765
766 template<typename _Alloc, typename... _UElements, typename
767 enable_if<_TMC<_UElements...>::template
768 _ConstructibleTuple<_UElements...>()
769 && _TMC<_UElements...>::template
770 _ImplicitlyConvertibleTuple<_UElements...>(),
771 bool>::type=true>
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, typename
779 enable_if<_TMC<_UElements...>::template
780 _ConstructibleTuple<_UElements...>()
781 && !_TMC<_UElements...>::template
782 _ImplicitlyConvertibleTuple<_UElements...>(),
783 bool>::type=false>
784 explicit tuple(allocator_arg_t __tag, const _Alloc& __a,
785 const tuple<_UElements...>& __in)
786 : _Inherited(__tag, __a,
787 static_cast<const _Tuple_impl<0, _UElements...>&>(__in))
788 { }
789
790 template<typename _Alloc, typename... _UElements, typename
791 enable_if<_TMC<_UElements...>::template
792 _MoveConstructibleTuple<_UElements...>()
793 && _TMC<_UElements...>::template
794 _ImplicitlyMoveConvertibleTuple<_UElements...>(),
795 bool>::type=true>
796 tuple(allocator_arg_t __tag, const _Alloc& __a,
797 tuple<_UElements...>&& __in)
798 : _Inherited(__tag, __a,
799 static_cast<_Tuple_impl<0, _UElements...>&&>(__in))
800 { }
801
802 template<typename _Alloc, typename... _UElements, typename
803 enable_if<_TMC<_UElements...>::template
804 _MoveConstructibleTuple<_UElements...>()
805 && !_TMC<_UElements...>::template
806 _ImplicitlyMoveConvertibleTuple<_UElements...>(),
807 bool>::type=false>
808 explicit tuple(allocator_arg_t __tag, const _Alloc& __a,
809 tuple<_UElements...>&& __in)
810 : _Inherited(__tag, __a,
811 static_cast<_Tuple_impl<0, _UElements...>&&>(__in))
812 { }
813
814 tuple&
815 operator=(const tuple& __in)
816 {
817 static_cast<_Inherited&>(*this) = __in;
818 return *this;
819 }
820
821 tuple&
822 operator=(tuple&& __in)
823 noexcept(is_nothrow_move_assignable<_Inherited>::value)
824 {
825 static_cast<_Inherited&>(*this) = std::move(__in);
826 return *this;
827 }
828
829 template<typename... _UElements, typename = typename
830 enable_if<sizeof...(_UElements)
831 == sizeof...(_Elements)>::type>
832 tuple&
833 operator=(const tuple<_UElements...>& __in)
834 {
835 static_cast<_Inherited&>(*this) = __in;
836 return *this;
837 }
838
839 template<typename... _UElements, typename = typename
840 enable_if<sizeof...(_UElements)
841 == sizeof...(_Elements)>::type>
842 tuple&
843 operator=(tuple<_UElements...>&& __in)
844 {
845 static_cast<_Inherited&>(*this) = std::move(__in);
846 return *this;
847 }
848
849 void
850 swap(tuple& __in)
851 noexcept(noexcept(__in._M_swap(__in)))
852 { _Inherited::_M_swap(__in); }
853 };
854
855 // Explicit specialization, zero-element tuple.
856 template<>
857 class tuple<>
858 {
859 public:
860 void swap(tuple&) noexcept { /* no-op */ }
861 };
862
863 /// Partial specialization, 2-element tuple.
864 /// Includes construction and assignment from a pair.
865 template<typename _T1, typename _T2>
866 class tuple<_T1, _T2> : public _Tuple_impl<0, _T1, _T2>
867 {
868 typedef _Tuple_impl<0, _T1, _T2> _Inherited;
869
870 public:
871 template <typename _U1 = _T1,
872 typename _U2 = _T2,
873 typename enable_if<__and_<
874 __is_implicitly_default_constructible<_U1>,
875 __is_implicitly_default_constructible<_U2>>
876 ::value, bool>::type = true>
877
878 constexpr tuple()
879 : _Inherited() { }
880
881 template <typename _U1 = _T1,
882 typename _U2 = _T2,
883 typename enable_if<
884 __and_<
885 is_default_constructible<_U1>,
886 is_default_constructible<_U2>,
887 __not_<
888 __and_<__is_implicitly_default_constructible<_U1>,
889 __is_implicitly_default_constructible<_U2>>>>
890 ::value, bool>::type = false>
891
892 explicit constexpr tuple()
893 : _Inherited() { }
894
895 // Shortcut for the cases where constructors taking _T1, _T2
896 // need to be constrained.
897 template<typename _Dummy> using _TCC =
898 _TC<is_same<_Dummy, void>::value, _T1, _T2>;
899
900 template<typename _Dummy = void, typename
901 enable_if<_TCC<_Dummy>::template
902 _ConstructibleTuple<_T1, _T2>()
903 && _TCC<_Dummy>::template
904 _ImplicitlyConvertibleTuple<_T1, _T2>(),
905 bool>::type = true>
906 constexpr tuple(const _T1& __a1, const _T2& __a2)
907 : _Inherited(__a1, __a2) { }
11
Calling constructor for '_Tuple_impl<0, llvm::IntrusiveRefCntPtr<const clang::ento::ProgramState> &, llvm::IntrusiveRefCntPtr<const clang::ento::ProgramState> &>'
16
Returning from constructor for '_Tuple_impl<0, llvm::IntrusiveRefCntPtr<const clang::ento::ProgramState> &, llvm::IntrusiveRefCntPtr<const clang::ento::ProgramState> &>'
908
909 template<typename _Dummy = void, typename
910 enable_if<_TCC<_Dummy>::template
911 _ConstructibleTuple<_T1, _T2>()
912 && !_TCC<_Dummy>::template
913 _ImplicitlyConvertibleTuple<_T1, _T2>(),
914 bool>::type = false>
915 explicit constexpr tuple(const _T1& __a1, const _T2& __a2)
916 : _Inherited(__a1, __a2) { }
917
918 // Shortcut for the cases where constructors taking _U1, _U2
919 // need to be constrained.
920 using _TMC = _TC<true, _T1, _T2>;
921
922 template<typename _U1, typename _U2, typename
923 enable_if<_TMC::template
924 _MoveConstructibleTuple<_U1, _U2>()
925 && _TMC::template
926 _ImplicitlyMoveConvertibleTuple<_U1, _U2>()
927 && !is_same<typename decay<_U1>::type,
928 allocator_arg_t>::value,
929 bool>::type = true>
930 constexpr tuple(_U1&& __a1, _U2&& __a2)
931 : _Inherited(std::forward<_U1>(__a1), std::forward<_U2>(__a2)) { }
932
933 template<typename _U1, typename _U2, typename
934 enable_if<_TMC::template
935 _MoveConstructibleTuple<_U1, _U2>()
936 && !_TMC::template
937 _ImplicitlyMoveConvertibleTuple<_U1, _U2>()
938 && !is_same<typename decay<_U1>::type,
939 allocator_arg_t>::value,
940 bool>::type = false>
941 explicit constexpr tuple(_U1&& __a1, _U2&& __a2)
942 : _Inherited(std::forward<_U1>(__a1), std::forward<_U2>(__a2)) { }
943
944 constexpr tuple(const tuple&) = default;
945
946 constexpr tuple(tuple&&) = default;
947
948 template<typename _U1, typename _U2, typename
949 enable_if<_TMC::template
950 _ConstructibleTuple<_U1, _U2>()
951 && _TMC::template
952 _ImplicitlyConvertibleTuple<_U1, _U2>(),
953 bool>::type = true>
954 constexpr tuple(const tuple<_U1, _U2>& __in)
955 : _Inherited(static_cast<const _Tuple_impl<0, _U1, _U2>&>(__in)) { }
956
957 template<typename _U1, typename _U2, typename
958 enable_if<_TMC::template
959 _ConstructibleTuple<_U1, _U2>()
960 && !_TMC::template
961 _ImplicitlyConvertibleTuple<_U1, _U2>(),
962 bool>::type = false>
963 explicit constexpr tuple(const tuple<_U1, _U2>& __in)
964 : _Inherited(static_cast<const _Tuple_impl<0, _U1, _U2>&>(__in)) { }
965
966 template<typename _U1, typename _U2, typename
967 enable_if<_TMC::template
968 _MoveConstructibleTuple<_U1, _U2>()
969 && _TMC::template
970 _ImplicitlyMoveConvertibleTuple<_U1, _U2>(),
971 bool>::type = true>
972 constexpr tuple(tuple<_U1, _U2>&& __in)
973 : _Inherited(static_cast<_Tuple_impl<0, _U1, _U2>&&>(__in)) { }
974
975 template<typename _U1, typename _U2, typename
976 enable_if<_TMC::template
977 _MoveConstructibleTuple<_U1, _U2>()
978 && !_TMC::template
979 _ImplicitlyMoveConvertibleTuple<_U1, _U2>(),
980 bool>::type = false>
981 explicit constexpr tuple(tuple<_U1, _U2>&& __in)
982 : _Inherited(static_cast<_Tuple_impl<0, _U1, _U2>&&>(__in)) { }
983
984 template<typename _U1, typename _U2, typename
985 enable_if<_TMC::template
986 _ConstructibleTuple<_U1, _U2>()
987 && _TMC::template
988 _ImplicitlyConvertibleTuple<_U1, _U2>(),
989 bool>::type = true>
990 constexpr tuple(const pair<_U1, _U2>& __in)
991 : _Inherited(__in.first, __in.second) { }
992
993 template<typename _U1, typename _U2, typename
994 enable_if<_TMC::template
995 _ConstructibleTuple<_U1, _U2>()
996 && !_TMC::template
997 _ImplicitlyConvertibleTuple<_U1, _U2>(),
998 bool>::type = false>
999 explicit constexpr tuple(const pair<_U1, _U2>& __in)
1000 : _Inherited(__in.first, __in.second) { }
1001
1002 template<typename _U1, typename _U2, typename
1003 enable_if<_TMC::template
1004 _MoveConstructibleTuple<_U1, _U2>()
1005 && _TMC::template
1006 _ImplicitlyMoveConvertibleTuple<_U1, _U2>(),
1007 bool>::type = true>
1008 constexpr tuple(pair<_U1, _U2>&& __in)
1009 : _Inherited(std::forward<_U1>(__in.first),
1010 std::forward<_U2>(__in.second)) { }
1011
1012 template<typename _U1, typename _U2, typename
1013 enable_if<_TMC::template
1014 _MoveConstructibleTuple<_U1, _U2>()
1015 && !_TMC::template
1016 _ImplicitlyMoveConvertibleTuple<_U1, _U2>(),
1017 bool>::type = false>
1018 explicit constexpr tuple(pair<_U1, _U2>&& __in)
1019 : _Inherited(std::forward<_U1>(__in.first),
1020 std::forward<_U2>(__in.second)) { }
1021
1022 // Allocator-extended constructors.
1023
1024 template<typename _Alloc>
1025 tuple(allocator_arg_t __tag, const _Alloc& __a)
1026 : _Inherited(__tag, __a) { }
1027
1028 template<typename _Alloc, typename _Dummy = void,
1029 typename enable_if<
1030 _TCC<_Dummy>::template
1031 _ConstructibleTuple<_T1, _T2>()
1032 && _TCC<_Dummy>::template
1033 _ImplicitlyConvertibleTuple<_T1, _T2>(),
1034 bool>::type=true>
1035
1036 tuple(allocator_arg_t __tag, const _Alloc& __a,
1037 const _T1& __a1, const _T2& __a2)
1038 : _Inherited(__tag, __a, __a1, __a2) { }
1039
1040 template<typename _Alloc, typename _Dummy = void,
1041 typename enable_if<
1042 _TCC<_Dummy>::template
1043 _ConstructibleTuple<_T1, _T2>()
1044 && !_TCC<_Dummy>::template
1045 _ImplicitlyConvertibleTuple<_T1, _T2>(),
1046 bool>::type=false>
1047
1048 explicit tuple(allocator_arg_t __tag, const _Alloc& __a,
1049 const _T1& __a1, const _T2& __a2)
1050 : _Inherited(__tag, __a, __a1, __a2) { }
1051
1052 template<typename _Alloc, typename _U1, typename _U2, typename
1053 enable_if<_TMC::template
1054 _MoveConstructibleTuple<_U1, _U2>()
1055 && _TMC::template
1056 _ImplicitlyMoveConvertibleTuple<_U1, _U2>(),
1057 bool>::type = true>
1058 tuple(allocator_arg_t __tag, const _Alloc& __a, _U1&& __a1, _U2&& __a2)
1059 : _Inherited(__tag, __a, std::forward<_U1>(__a1),
1060 std::forward<_U2>(__a2)) { }
1061
1062 template<typename _Alloc, typename _U1, typename _U2, typename
1063 enable_if<_TMC::template
1064 _MoveConstructibleTuple<_U1, _U2>()
1065 && !_TMC::template
1066 _ImplicitlyMoveConvertibleTuple<_U1, _U2>(),
1067 bool>::type = false>
1068 explicit tuple(allocator_arg_t __tag, const _Alloc& __a,
1069 _U1&& __a1, _U2&& __a2)
1070 : _Inherited(__tag, __a, std::forward<_U1>(__a1),
1071 std::forward<_U2>(__a2)) { }
1072
1073 template<typename _Alloc>
1074 tuple(allocator_arg_t __tag, const _Alloc& __a, const tuple& __in)
1075 : _Inherited(__tag, __a, static_cast<const _Inherited&>(__in)) { }
1076
1077 template<typename _Alloc>
1078 tuple(allocator_arg_t __tag, const _Alloc& __a, tuple&& __in)
1079 : _Inherited(__tag, __a, static_cast<_Inherited&&>(__in)) { }
1080
1081 template<typename _Alloc, typename _U1, typename _U2, typename
1082 enable_if<_TMC::template
1083 _ConstructibleTuple<_U1, _U2>()
1084 && _TMC::template
1085 _ImplicitlyConvertibleTuple<_U1, _U2>(),
1086 bool>::type = true>
1087 tuple(allocator_arg_t __tag, const _Alloc& __a,
1088 const tuple<_U1, _U2>& __in)
1089 : _Inherited(__tag, __a,
1090 static_cast<const _Tuple_impl<0, _U1, _U2>&>(__in))
1091 { }
1092
1093 template<typename _Alloc, typename _U1, typename _U2, typename
1094 enable_if<_TMC::template
1095 _ConstructibleTuple<_U1, _U2>()
1096 && !_TMC::template
1097 _ImplicitlyConvertibleTuple<_U1, _U2>(),
1098 bool>::type = false>
1099 explicit tuple(allocator_arg_t __tag, const _Alloc& __a,
1100 const tuple<_U1, _U2>& __in)
1101 : _Inherited(__tag, __a,
1102 static_cast<const _Tuple_impl<0, _U1, _U2>&>(__in))
1103 { }
1104
1105 template<typename _Alloc, typename _U1, typename _U2, typename
1106 enable_if<_TMC::template
1107 _MoveConstructibleTuple<_U1, _U2>()
1108 && _TMC::template
1109 _ImplicitlyMoveConvertibleTuple<_U1, _U2>(),
1110 bool>::type = true>
1111 tuple(allocator_arg_t __tag, const _Alloc& __a, tuple<_U1, _U2>&& __in)
1112 : _Inherited(__tag, __a, static_cast<_Tuple_impl<0, _U1, _U2>&&>(__in))
1113 { }
1114
1115 template<typename _Alloc, typename _U1, typename _U2, typename
1116 enable_if<_TMC::template
1117 _MoveConstructibleTuple<_U1, _U2>()
1118 && !_TMC::template
1119 _ImplicitlyMoveConvertibleTuple<_U1, _U2>(),
1120 bool>::type = false>
1121 explicit tuple(allocator_arg_t __tag, const _Alloc& __a,
1122 tuple<_U1, _U2>&& __in)
1123 : _Inherited(__tag, __a, static_cast<_Tuple_impl<0, _U1, _U2>&&>(__in))
1124 { }
1125
1126 template<typename _Alloc, typename _U1, typename _U2, typename
1127 enable_if<_TMC::template
1128 _ConstructibleTuple<_U1, _U2>()
1129 && _TMC::template
1130 _ImplicitlyConvertibleTuple<_U1, _U2>(),
1131 bool>::type = true>
1132 tuple(allocator_arg_t __tag, const _Alloc& __a,
1133 const pair<_U1, _U2>& __in)
1134 : _Inherited(__tag, __a, __in.first, __in.second) { }
1135
1136 template<typename _Alloc, typename _U1, typename _U2, typename
1137 enable_if<_TMC::template
1138 _ConstructibleTuple<_U1, _U2>()
1139 && !_TMC::template
1140 _ImplicitlyConvertibleTuple<_U1, _U2>(),
1141 bool>::type = false>
1142 explicit 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, typename
1147 enable_if<_TMC::template
1148 _MoveConstructibleTuple<_U1, _U2>()
1149 && _TMC::template
1150 _ImplicitlyMoveConvertibleTuple<_U1, _U2>(),
1151 bool>::type = true>
1152 tuple(allocator_arg_t __tag, const _Alloc& __a, pair<_U1, _U2>&& __in)
1153 : _Inherited(__tag, __a, std::forward<_U1>(__in.first),
1154 std::forward<_U2>(__in.second)) { }
1155
1156 template<typename _Alloc, typename _U1, typename _U2, typename
1157 enable_if<_TMC::template
1158 _MoveConstructibleTuple<_U1, _U2>()
1159 && !_TMC::template
1160 _ImplicitlyMoveConvertibleTuple<_U1, _U2>(),
1161 bool>::type = false>
1162 explicit tuple(allocator_arg_t __tag, const _Alloc& __a,
1163 pair<_U1, _U2>&& __in)
1164 : _Inherited(__tag, __a, std::forward<_U1>(__in.first),
1165 std::forward<_U2>(__in.second)) { }
1166
1167 tuple&
1168 operator=(const tuple& __in)
1169 {
1170 static_cast<_Inherited&>(*this) = __in;
1171 return *this;
1172 }
1173
1174 tuple&
1175 operator=(tuple&& __in)
1176 noexcept(is_nothrow_move_assignable<_Inherited>::value)
1177 {
1178 static_cast<_Inherited&>(*this) = std::move(__in);
1179 return *this;
1180 }
1181
1182 template<typename _U1, typename _U2>
1183 tuple&
1184 operator=(const tuple<_U1, _U2>& __in)
1185 {
1186 static_cast<_Inherited&>(*this) = __in;
1187 return *this;
1188 }
1189
1190 template<typename _U1, typename _U2>
1191 tuple&
1192 operator=(tuple<_U1, _U2>&& __in)
1193 {
1194 static_cast<_Inherited&>(*this) = std::move(__in);
1195 return *this;
1196 }
1197
1198 template<typename _U1, typename _U2>
1199 tuple&
1200 operator=(const pair<_U1, _U2>& __in)
1201 {
1202 this->_M_head(*this) = __in.first;
1203 this->_M_tail(*this)._M_head(*this) = __in.second;
1204 return *this;
1205 }
1206
1207 template<typename _U1, typename _U2>
1208 tuple&
1209 operator=(pair<_U1, _U2>&& __in)
1210 {
1211 this->_M_head(*this) = std::forward<_U1>(__in.first);
1212 this->_M_tail(*this)._M_head(*this) = std::forward<_U2>(__in.second);
1213 return *this;
1214 }
1215
1216 void
1217 swap(tuple& __in)
1218 noexcept(noexcept(__in._M_swap(__in)))
1219 { _Inherited::_M_swap(__in); }
1220 };
1221
1222
1223 /**
1224 * Recursive case for tuple_element: strip off the first element in
1225 * the tuple and retrieve the (i-1)th element of the remaining tuple.
1226 */
1227 template<std::size_t __i, typename _Head, typename... _Tail>
1228 struct tuple_element<__i, tuple<_Head, _Tail...> >
1229 : tuple_element<__i - 1, tuple<_Tail...> > { };
1230
1231 /**
1232 * Basis case for tuple_element: The first element is the one we're seeking.
1233 */
1234 template<typename _Head, typename... _Tail>
1235 struct tuple_element<0, tuple<_Head, _Tail...> >
1236 {
1237 typedef _Head type;
1238 };
1239
1240 /// class tuple_size
1241 template<typename... _Elements>
1242 struct tuple_size<tuple<_Elements...>>
1243 : public integral_constant<std::size_t, sizeof...(_Elements)> { };
1244
1245 template<std::size_t __i, typename _Head, typename... _Tail>
1246 constexpr _Head&
1247 __get_helper(_Tuple_impl<__i, _Head, _Tail...>& __t) noexcept
1248 { return _Tuple_impl<__i, _Head, _Tail...>::_M_head(__t); }
1249
1250 template<std::size_t __i, typename _Head, typename... _Tail>
1251 constexpr const _Head&
1252 __get_helper(const _Tuple_impl<__i, _Head, _Tail...>& __t) noexcept
1253 { return _Tuple_impl<__i, _Head, _Tail...>::_M_head(__t); }
1254
1255 /// Return a reference to the ith element of a tuple.
1256 template<std::size_t __i, typename... _Elements>
1257 constexpr __tuple_element_t<__i, tuple<_Elements...>>&
1258 get(tuple<_Elements...>& __t) noexcept
1259 { return std::__get_helper<__i>(__t); }
1260
1261 /// Return a const reference to the ith element of a const tuple.
1262 template<std::size_t __i, typename... _Elements>
1263 constexpr const __tuple_element_t<__i, tuple<_Elements...>>&
1264 get(const tuple<_Elements...>& __t) noexcept
1265 { return std::__get_helper<__i>(__t); }
1266
1267 /// Return an rvalue reference to the ith element of a tuple rvalue.
1268 template<std::size_t __i, typename... _Elements>
1269 constexpr __tuple_element_t<__i, tuple<_Elements...>>&&
1270 get(tuple<_Elements...>&& __t) noexcept
1271 {
1272 typedef __tuple_element_t<__i, tuple<_Elements...>> __element_type;
1273 return std::forward<__element_type&&>(std::get<__i>(__t));
1274 }
1275
1276#if __cplusplus201402L > 201103L
1277
1278#define __cpp_lib_tuples_by_type201304 201304
1279
1280 template<typename _Head, size_t __i, typename... _Tail>
1281 constexpr _Head&
1282 __get_helper2(_Tuple_impl<__i, _Head, _Tail...>& __t) noexcept
1283 { return _Tuple_impl<__i, _Head, _Tail...>::_M_head(__t); }
1284
1285 template<typename _Head, size_t __i, typename... _Tail>
1286 constexpr const _Head&
1287 __get_helper2(const _Tuple_impl<__i, _Head, _Tail...>& __t) noexcept
1288 { return _Tuple_impl<__i, _Head, _Tail...>::_M_head(__t); }
1289
1290 /// Return a reference to the unique element of type _Tp of a tuple.
1291 template <typename _Tp, typename... _Types>
1292 constexpr _Tp&
1293 get(tuple<_Types...>& __t) noexcept
1294 { return std::__get_helper2<_Tp>(__t); }
1295
1296 /// Return a reference to the unique element of type _Tp of a tuple rvalue.
1297 template <typename _Tp, typename... _Types>
1298 constexpr _Tp&&
1299 get(tuple<_Types...>&& __t) noexcept
1300 { return std::forward<_Tp&&>(std::__get_helper2<_Tp>(__t)); }
1301
1302 /// Return a const reference to the unique element of type _Tp of a tuple.
1303 template <typename _Tp, typename... _Types>
1304 constexpr const _Tp&
1305 get(const tuple<_Types...>& __t) noexcept
1306 { return std::__get_helper2<_Tp>(__t); }
1307#endif
1308
1309 // This class performs the comparison operations on tuples
1310 template<typename _Tp, typename _Up, size_t __i, size_t __size>
1311 struct __tuple_compare
1312 {
1313 static constexpr bool
1314 __eq(const _Tp& __t, const _Up& __u)
1315 {
1316 return bool(std::get<__i>(__t) == std::get<__i>(__u))
1317 && __tuple_compare<_Tp, _Up, __i + 1, __size>::__eq(__t, __u);
1318 }
1319
1320 static constexpr bool
1321 __less(const _Tp& __t, const _Up& __u)
1322 {
1323 return bool(std::get<__i>(__t) < std::get<__i>(__u))
1324 || (!bool(std::get<__i>(__u) < std::get<__i>(__t))
1325 && __tuple_compare<_Tp, _Up, __i + 1, __size>::__less(__t, __u));
1326 }
1327 };
1328
1329 template<typename _Tp, typename _Up, size_t __size>
1330 struct __tuple_compare<_Tp, _Up, __size, __size>
1331 {
1332 static constexpr bool
1333 __eq(const _Tp&, const _Up&) { return true; }
1334
1335 static constexpr bool
1336 __less(const _Tp&, const _Up&) { return false; }
1337 };
1338
1339 template<typename... _TElements, typename... _UElements>
1340 constexpr bool
1341 operator==(const tuple<_TElements...>& __t,
1342 const tuple<_UElements...>& __u)
1343 {
1344 static_assert(sizeof...(_TElements) == sizeof...(_UElements),
1345 "tuple objects can only be compared if they have equal sizes.");
1346 using __compare = __tuple_compare<tuple<_TElements...>,
1347 tuple<_UElements...>,
1348 0, sizeof...(_TElements)>;
1349 return __compare::__eq(__t, __u);
1350 }
1351
1352 template<typename... _TElements, typename... _UElements>
1353 constexpr bool
1354 operator<(const tuple<_TElements...>& __t,
1355 const tuple<_UElements...>& __u)
1356 {
1357 static_assert(sizeof...(_TElements) == sizeof...(_UElements),
1358 "tuple objects can only be compared if they have equal sizes.");
1359 using __compare = __tuple_compare<tuple<_TElements...>,
1360 tuple<_UElements...>,
1361 0, sizeof...(_TElements)>;
1362 return __compare::__less(__t, __u);
1363 }
1364
1365 template<typename... _TElements, typename... _UElements>
1366 constexpr bool
1367 operator!=(const tuple<_TElements...>& __t,
1368 const tuple<_UElements...>& __u)
1369 { return !(__t == __u); }
1370
1371 template<typename... _TElements, typename... _UElements>
1372 constexpr bool
1373 operator>(const tuple<_TElements...>& __t,
1374 const tuple<_UElements...>& __u)
1375 { return __u < __t; }
1376
1377 template<typename... _TElements, typename... _UElements>
1378 constexpr bool
1379 operator<=(const tuple<_TElements...>& __t,
1380 const tuple<_UElements...>& __u)
1381 { return !(__u < __t); }
1382
1383 template<typename... _TElements, typename... _UElements>
1384 constexpr bool
1385 operator>=(const tuple<_TElements...>& __t,
1386 const tuple<_UElements...>& __u)
1387 { return !(__t < __u); }
1388
1389 // NB: DR 705.
1390 template<typename... _Elements>
1391 constexpr tuple<typename __decay_and_strip<_Elements>::__type...>
1392 make_tuple(_Elements&&... __args)
1393 {
1394 typedef tuple<typename __decay_and_strip<_Elements>::__type...>
1395 __result_type;
1396 return __result_type(std::forward<_Elements>(__args)...);
1397 }
1398
1399 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1400 // 2275. Why is forward_as_tuple not constexpr?
1401 template<typename... _Elements>
1402 constexpr tuple<_Elements&&...>
1403 forward_as_tuple(_Elements&&... __args) noexcept
1404 { return tuple<_Elements&&...>(std::forward<_Elements>(__args)...); }
1405
1406 template<typename... _Tps>
1407 struct __is_tuple_like_impl<tuple<_Tps...>> : true_type
1408 { };
1409
1410 // Internal type trait that allows us to sfinae-protect tuple_cat.
1411 template<typename _Tp>
1412 struct __is_tuple_like
1413 : public __is_tuple_like_impl<typename std::remove_cv
1414 <typename std::remove_reference<_Tp>::type>::type>::type
1415 { };
1416
1417 template<size_t, typename, typename, size_t>
1418 struct __make_tuple_impl;
1419
1420 template<size_t _Idx, typename _Tuple, typename... _Tp, size_t _Nm>
1421 struct __make_tuple_impl<_Idx, tuple<_Tp...>, _Tuple, _Nm>
1422 : __make_tuple_impl<_Idx + 1,
1423 tuple<_Tp..., __tuple_element_t<_Idx, _Tuple>>,
1424 _Tuple, _Nm>
1425 { };
1426
1427 template<std::size_t _Nm, typename _Tuple, typename... _Tp>
1428 struct __make_tuple_impl<_Nm, tuple<_Tp...>, _Tuple, _Nm>
1429 {
1430 typedef tuple<_Tp...> __type;
1431 };
1432
1433 template<typename _Tuple>
1434 struct __do_make_tuple
1435 : __make_tuple_impl<0, tuple<>, _Tuple, std::tuple_size<_Tuple>::value>
1436 { };
1437
1438 // Returns the std::tuple equivalent of a tuple-like type.
1439 template<typename _Tuple>
1440 struct __make_tuple
1441 : public __do_make_tuple<typename std::remove_cv
1442 <typename std::remove_reference<_Tuple>::type>::type>
1443 { };
1444
1445 // Combines several std::tuple's into a single one.
1446 template<typename...>
1447 struct __combine_tuples;
1448
1449 template<>
1450 struct __combine_tuples<>
1451 {
1452 typedef tuple<> __type;
1453 };
1454
1455 template<typename... _Ts>
1456 struct __combine_tuples<tuple<_Ts...>>
1457 {
1458 typedef tuple<_Ts...> __type;
1459 };
1460
1461 template<typename... _T1s, typename... _T2s, typename... _Rem>
1462 struct __combine_tuples<tuple<_T1s...>, tuple<_T2s...>, _Rem...>
1463 {
1464 typedef typename __combine_tuples<tuple<_T1s..., _T2s...>,
1465 _Rem...>::__type __type;
1466 };
1467
1468 // Computes the result type of tuple_cat given a set of tuple-like types.
1469 template<typename... _Tpls>
1470 struct __tuple_cat_result
1471 {
1472 typedef typename __combine_tuples
1473 <typename __make_tuple<_Tpls>::__type...>::__type __type;
1474 };
1475
1476 // Helper to determine the index set for the first tuple-like
1477 // type of a given set.
1478 template<typename...>
1479 struct __make_1st_indices;
1480
1481 template<>
1482 struct __make_1st_indices<>
1483 {
1484 typedef std::_Index_tuple<> __type;
1485 };
1486
1487 template<typename _Tp, typename... _Tpls>
1488 struct __make_1st_indices<_Tp, _Tpls...>
1489 {
1490 typedef typename std::_Build_index_tuple<std::tuple_size<
1491 typename std::remove_reference<_Tp>::type>::value>::__type __type;
1492 };
1493
1494 // Performs the actual concatenation by step-wise expanding tuple-like
1495 // objects into the elements, which are finally forwarded into the
1496 // result tuple.
1497 template<typename _Ret, typename _Indices, typename... _Tpls>
1498 struct __tuple_concater;
1499
1500 template<typename _Ret, std::size_t... _Is, typename _Tp, typename... _Tpls>
1501 struct __tuple_concater<_Ret, std::_Index_tuple<_Is...>, _Tp, _Tpls...>
1502 {
1503 template<typename... _Us>
1504 static constexpr _Ret
1505 _S_do(_Tp&& __tp, _Tpls&&... __tps, _Us&&... __us)
1506 {
1507 typedef typename __make_1st_indices<_Tpls...>::__type __idx;
1508 typedef __tuple_concater<_Ret, __idx, _Tpls...> __next;
1509 return __next::_S_do(std::forward<_Tpls>(__tps)...,
1510 std::forward<_Us>(__us)...,
1511 std::get<_Is>(std::forward<_Tp>(__tp))...);
1512 }
1513 };
1514
1515 template<typename _Ret>
1516 struct __tuple_concater<_Ret, std::_Index_tuple<>>
1517 {
1518 template<typename... _Us>
1519 static constexpr _Ret
1520 _S_do(_Us&&... __us)
1521 {
1522 return _Ret(std::forward<_Us>(__us)...);
1523 }
1524 };
1525
1526 /// tuple_cat
1527 template<typename... _Tpls, typename = typename
1528 enable_if<__and_<__is_tuple_like<_Tpls>...>::value>::type>
1529 constexpr auto
1530 tuple_cat(_Tpls&&... __tpls)
1531 -> typename __tuple_cat_result<_Tpls...>::__type
1532 {
1533 typedef typename __tuple_cat_result<_Tpls...>::__type __ret;
1534 typedef typename __make_1st_indices<_Tpls...>::__type __idx;
1535 typedef __tuple_concater<__ret, __idx, _Tpls...> __concater;
1536 return __concater::_S_do(std::forward<_Tpls>(__tpls)...);
1537 }
1538
1539 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1540 // 2301. Why is tie not constexpr?
1541 /// tie
1542 template<typename... _Elements>
1543 constexpr tuple<_Elements&...>
1544 tie(_Elements&... __args) noexcept
1545 { 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> &>'
1546
1547 /// swap
1548 template<typename... _Elements>
1549 inline void
1550 swap(tuple<_Elements...>& __x, tuple<_Elements...>& __y)
1551 noexcept(noexcept(__x.swap(__y)))
1552 { __x.swap(__y); }
1553
1554 // A class (and instance) which can be used in 'tie' when an element
1555 // of a tuple is not required
1556 struct _Swallow_assign
1557 {
1558 template<class _Tp>
1559 const _Swallow_assign&
1560 operator=(const _Tp&) const
1561 { return *this; }
1562 };
1563
1564 const _Swallow_assign ignore{};
1565
1566 /// Partial specialization for tuples
1567 template<typename... _Types, typename _Alloc>
1568 struct uses_allocator<tuple<_Types...>, _Alloc> : true_type { };
1569
1570 // See stl_pair.h...
1571 template<class _T1, class _T2>
1572 template<typename... _Args1, typename... _Args2>
1573 inline
1574 pair<_T1, _T2>::
1575 pair(piecewise_construct_t,
1576 tuple<_Args1...> __first, tuple<_Args2...> __second)
1577 : pair(__first, __second,
1578 typename _Build_index_tuple<sizeof...(_Args1)>::__type(),
1579 typename _Build_index_tuple<sizeof...(_Args2)>::__type())
1580 { }
1581
1582 template<class _T1, class _T2>
1583 template<typename... _Args1, std::size_t... _Indexes1,
1584 typename... _Args2, std::size_t... _Indexes2>
1585 inline
1586 pair<_T1, _T2>::
1587 pair(tuple<_Args1...>& __tuple1, tuple<_Args2...>& __tuple2,
1588 _Index_tuple<_Indexes1...>, _Index_tuple<_Indexes2...>)
1589 : first(std::forward<_Args1>(std::get<_Indexes1>(__tuple1))...),
1590 second(std::forward<_Args2>(std::get<_Indexes2>(__tuple2))...)
1591 { }
1592
1593 /// @}
1594
1595_GLIBCXX_END_NAMESPACE_VERSION
1596} // namespace std
1597
1598#endif // C++11
1599
1600#endif // _GLIBCXX_TUPLE

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

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

/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/ADT/Optional.h

1//===- Optional.h - Simple variant for passing optional 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//===----------------------------------------------------------------------===//