1 //===-- UncheckedOptionalAccessModel.cpp ------------------------*- 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 a dataflow analysis that detects unsafe uses of optional 10 // values. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/DeclCXX.h" 17 #include "clang/AST/Expr.h" 18 #include "clang/AST/ExprCXX.h" 19 #include "clang/AST/Stmt.h" 20 #include "clang/ASTMatchers/ASTMatchers.h" 21 #include "clang/ASTMatchers/ASTMatchersMacros.h" 22 #include "clang/Analysis/CFG.h" 23 #include "clang/Analysis/FlowSensitive/CFGMatchSwitch.h" 24 #include "clang/Analysis/FlowSensitive/DataflowEnvironment.h" 25 #include "clang/Analysis/FlowSensitive/Formula.h" 26 #include "clang/Analysis/FlowSensitive/NoopLattice.h" 27 #include "clang/Analysis/FlowSensitive/StorageLocation.h" 28 #include "clang/Analysis/FlowSensitive/Value.h" 29 #include "clang/Basic/SourceLocation.h" 30 #include "llvm/ADT/StringRef.h" 31 #include "llvm/Support/Casting.h" 32 #include "llvm/Support/ErrorHandling.h" 33 #include <cassert> 34 #include <memory> 35 #include <optional> 36 #include <utility> 37 #include <vector> 38 39 namespace clang { 40 namespace dataflow { 41 42 static bool isTopLevelNamespaceWithName(const NamespaceDecl &NS, 43 llvm::StringRef Name) { 44 return NS.getDeclName().isIdentifier() && NS.getName() == Name && 45 NS.getParent() != nullptr && NS.getParent()->isTranslationUnit(); 46 } 47 48 static bool hasOptionalClassName(const CXXRecordDecl &RD) { 49 if (!RD.getDeclName().isIdentifier()) 50 return false; 51 52 if (RD.getName() == "optional") { 53 if (const auto *N = dyn_cast_or_null<NamespaceDecl>(RD.getDeclContext())) 54 return N->isStdNamespace() || isTopLevelNamespaceWithName(*N, "absl"); 55 return false; 56 } 57 58 if (RD.getName() == "Optional") { 59 // Check whether namespace is "::base" or "::folly". 60 const auto *N = dyn_cast_or_null<NamespaceDecl>(RD.getDeclContext()); 61 return N != nullptr && (isTopLevelNamespaceWithName(*N, "base") || 62 isTopLevelNamespaceWithName(*N, "folly")); 63 } 64 65 return false; 66 } 67 68 namespace { 69 70 using namespace ::clang::ast_matchers; 71 using LatticeTransferState = TransferState<NoopLattice>; 72 73 AST_MATCHER(CXXRecordDecl, hasOptionalClassNameMatcher) { 74 return hasOptionalClassName(Node); 75 } 76 77 DeclarationMatcher optionalClass() { 78 return classTemplateSpecializationDecl( 79 hasOptionalClassNameMatcher(), 80 hasTemplateArgument(0, refersToType(type().bind("T")))); 81 } 82 83 auto optionalOrAliasType() { 84 return hasUnqualifiedDesugaredType( 85 recordType(hasDeclaration(optionalClass()))); 86 } 87 88 /// Matches any of the spellings of the optional types and sugar, aliases, etc. 89 auto hasOptionalType() { return hasType(optionalOrAliasType()); } 90 91 auto isOptionalMemberCallWithNameMatcher( 92 ast_matchers::internal::Matcher<NamedDecl> matcher, 93 const std::optional<StatementMatcher> &Ignorable = std::nullopt) { 94 auto Exception = unless(Ignorable ? expr(anyOf(*Ignorable, cxxThisExpr())) 95 : cxxThisExpr()); 96 return cxxMemberCallExpr( 97 on(expr(Exception, 98 anyOf(hasOptionalType(), 99 hasType(pointerType(pointee(optionalOrAliasType())))))), 100 callee(cxxMethodDecl(matcher))); 101 } 102 103 auto isOptionalOperatorCallWithName( 104 llvm::StringRef operator_name, 105 const std::optional<StatementMatcher> &Ignorable = std::nullopt) { 106 return cxxOperatorCallExpr( 107 hasOverloadedOperatorName(operator_name), 108 callee(cxxMethodDecl(ofClass(optionalClass()))), 109 Ignorable ? callExpr(unless(hasArgument(0, *Ignorable))) : callExpr()); 110 } 111 112 auto isMakeOptionalCall() { 113 return callExpr(callee(functionDecl(hasAnyName( 114 "std::make_optional", "base::make_optional", 115 "absl::make_optional", "folly::make_optional"))), 116 hasOptionalType()); 117 } 118 119 auto nulloptTypeDecl() { 120 return namedDecl(hasAnyName("std::nullopt_t", "absl::nullopt_t", 121 "base::nullopt_t", "folly::None")); 122 } 123 124 auto hasNulloptType() { return hasType(nulloptTypeDecl()); } 125 126 // `optional` or `nullopt_t` 127 auto hasAnyOptionalType() { 128 return hasType(hasUnqualifiedDesugaredType( 129 recordType(hasDeclaration(anyOf(nulloptTypeDecl(), optionalClass()))))); 130 } 131 132 auto inPlaceClass() { 133 return recordDecl(hasAnyName("std::in_place_t", "absl::in_place_t", 134 "base::in_place_t", "folly::in_place_t")); 135 } 136 137 auto isOptionalNulloptConstructor() { 138 return cxxConstructExpr( 139 hasOptionalType(), 140 hasDeclaration(cxxConstructorDecl(parameterCountIs(1), 141 hasParameter(0, hasNulloptType())))); 142 } 143 144 auto isOptionalInPlaceConstructor() { 145 return cxxConstructExpr(hasOptionalType(), 146 hasArgument(0, hasType(inPlaceClass()))); 147 } 148 149 auto isOptionalValueOrConversionConstructor() { 150 return cxxConstructExpr( 151 hasOptionalType(), 152 unless(hasDeclaration( 153 cxxConstructorDecl(anyOf(isCopyConstructor(), isMoveConstructor())))), 154 argumentCountIs(1), hasArgument(0, unless(hasNulloptType()))); 155 } 156 157 auto isOptionalValueOrConversionAssignment() { 158 return cxxOperatorCallExpr( 159 hasOverloadedOperatorName("="), 160 callee(cxxMethodDecl(ofClass(optionalClass()))), 161 unless(hasDeclaration(cxxMethodDecl( 162 anyOf(isCopyAssignmentOperator(), isMoveAssignmentOperator())))), 163 argumentCountIs(2), hasArgument(1, unless(hasNulloptType()))); 164 } 165 166 auto isNulloptConstructor() { 167 return cxxConstructExpr(hasNulloptType(), argumentCountIs(1), 168 hasArgument(0, hasNulloptType())); 169 } 170 171 auto isOptionalNulloptAssignment() { 172 return cxxOperatorCallExpr(hasOverloadedOperatorName("="), 173 callee(cxxMethodDecl(ofClass(optionalClass()))), 174 argumentCountIs(2), 175 hasArgument(1, hasNulloptType())); 176 } 177 178 auto isStdSwapCall() { 179 return callExpr(callee(functionDecl(hasName("std::swap"))), 180 argumentCountIs(2), hasArgument(0, hasOptionalType()), 181 hasArgument(1, hasOptionalType())); 182 } 183 184 auto isStdForwardCall() { 185 return callExpr(callee(functionDecl(hasName("std::forward"))), 186 argumentCountIs(1), hasArgument(0, hasOptionalType())); 187 } 188 189 constexpr llvm::StringLiteral ValueOrCallID = "ValueOrCall"; 190 191 auto isValueOrStringEmptyCall() { 192 // `opt.value_or("").empty()` 193 return cxxMemberCallExpr( 194 callee(cxxMethodDecl(hasName("empty"))), 195 onImplicitObjectArgument(ignoringImplicit( 196 cxxMemberCallExpr(on(expr(unless(cxxThisExpr()))), 197 callee(cxxMethodDecl(hasName("value_or"), 198 ofClass(optionalClass()))), 199 hasArgument(0, stringLiteral(hasSize(0)))) 200 .bind(ValueOrCallID)))); 201 } 202 203 auto isValueOrNotEqX() { 204 auto ComparesToSame = [](ast_matchers::internal::Matcher<Stmt> Arg) { 205 return hasOperands( 206 ignoringImplicit( 207 cxxMemberCallExpr(on(expr(unless(cxxThisExpr()))), 208 callee(cxxMethodDecl(hasName("value_or"), 209 ofClass(optionalClass()))), 210 hasArgument(0, Arg)) 211 .bind(ValueOrCallID)), 212 ignoringImplicit(Arg)); 213 }; 214 215 // `opt.value_or(X) != X`, for X is `nullptr`, `""`, or `0`. Ideally, we'd 216 // support this pattern for any expression, but the AST does not have a 217 // generic expression comparison facility, so we specialize to common cases 218 // seen in practice. FIXME: define a matcher that compares values across 219 // nodes, which would let us generalize this to any `X`. 220 return binaryOperation(hasOperatorName("!="), 221 anyOf(ComparesToSame(cxxNullPtrLiteralExpr()), 222 ComparesToSame(stringLiteral(hasSize(0))), 223 ComparesToSame(integerLiteral(equals(0))))); 224 } 225 226 auto isCallReturningOptional() { 227 return callExpr(hasType(qualType(anyOf( 228 optionalOrAliasType(), referenceType(pointee(optionalOrAliasType())))))); 229 } 230 231 template <typename L, typename R> 232 auto isComparisonOperatorCall(L lhs_arg_matcher, R rhs_arg_matcher) { 233 return cxxOperatorCallExpr( 234 anyOf(hasOverloadedOperatorName("=="), hasOverloadedOperatorName("!=")), 235 argumentCountIs(2), hasArgument(0, lhs_arg_matcher), 236 hasArgument(1, rhs_arg_matcher)); 237 } 238 239 /// Ensures that `Expr` is mapped to a `BoolValue` and returns its formula. 240 const Formula &forceBoolValue(Environment &Env, const Expr &Expr) { 241 auto *Value = cast_or_null<BoolValue>(Env.getValue(Expr)); 242 if (Value != nullptr) 243 return Value->formula(); 244 245 Value = &Env.makeAtomicBoolValue(); 246 Env.setValue(Expr, *Value); 247 return Value->formula(); 248 } 249 250 /// Sets `HasValueVal` as the symbolic value that represents the "has_value" 251 /// property of the optional value `OptionalVal`. 252 void setHasValue(Value &OptionalVal, BoolValue &HasValueVal) { 253 OptionalVal.setProperty("has_value", HasValueVal); 254 } 255 256 /// Creates a symbolic value for an `optional` value at an existing storage 257 /// location. Uses `HasValueVal` as the symbolic value of the "has_value" 258 /// property. 259 RecordValue &createOptionalValue(RecordStorageLocation &Loc, 260 BoolValue &HasValueVal, Environment &Env) { 261 auto &OptionalVal = Env.create<RecordValue>(Loc); 262 Env.setValue(Loc, OptionalVal); 263 setHasValue(OptionalVal, HasValueVal); 264 return OptionalVal; 265 } 266 267 /// Returns the symbolic value that represents the "has_value" property of the 268 /// optional value `OptionalVal`. Returns null if `OptionalVal` is null. 269 BoolValue *getHasValue(Environment &Env, Value *OptionalVal) { 270 if (OptionalVal != nullptr) { 271 auto *HasValueVal = 272 cast_or_null<BoolValue>(OptionalVal->getProperty("has_value")); 273 if (HasValueVal == nullptr) { 274 HasValueVal = &Env.makeAtomicBoolValue(); 275 OptionalVal->setProperty("has_value", *HasValueVal); 276 } 277 return HasValueVal; 278 } 279 return nullptr; 280 } 281 282 /// Returns true if and only if `Type` is an optional type. 283 bool isOptionalType(QualType Type) { 284 if (!Type->isRecordType()) 285 return false; 286 const CXXRecordDecl *D = Type->getAsCXXRecordDecl(); 287 return D != nullptr && hasOptionalClassName(*D); 288 } 289 290 /// Returns the number of optional wrappers in `Type`. 291 /// 292 /// For example, if `Type` is `optional<optional<int>>`, the result of this 293 /// function will be 2. 294 int countOptionalWrappers(const ASTContext &ASTCtx, QualType Type) { 295 if (!isOptionalType(Type)) 296 return 0; 297 return 1 + countOptionalWrappers( 298 ASTCtx, 299 cast<ClassTemplateSpecializationDecl>(Type->getAsRecordDecl()) 300 ->getTemplateArgs() 301 .get(0) 302 .getAsType() 303 .getDesugaredType(ASTCtx)); 304 } 305 306 /// Tries to initialize the `optional`'s value (that is, contents), and return 307 /// its location. Returns nullptr if the value can't be represented. 308 StorageLocation *maybeInitializeOptionalValueMember(QualType Q, 309 Value &OptionalVal, 310 Environment &Env) { 311 // The "value" property represents a synthetic field. As such, it needs 312 // `StorageLocation`, like normal fields (and other variables). So, we model 313 // it with a `PointerValue`, since that includes a storage location. Once 314 // the property is set, it will be shared by all environments that access the 315 // `Value` representing the optional (here, `OptionalVal`). 316 if (auto *ValueProp = OptionalVal.getProperty("value")) { 317 auto *ValuePtr = clang::cast<PointerValue>(ValueProp); 318 auto &ValueLoc = ValuePtr->getPointeeLoc(); 319 if (Env.getValue(ValueLoc) != nullptr) 320 return &ValueLoc; 321 322 // The property was previously set, but the value has been lost. This can 323 // happen in various situations, for example: 324 // - Because of an environment merge (where the two environments mapped the 325 // property to different values, which resulted in them both being 326 // discarded). 327 // - When two blocks in the CFG, with neither a dominator of the other, 328 // visit the same optional value. (FIXME: This is something we can and 329 // should fix -- see also the lengthy FIXME below.) 330 // - Or even when a block is revisited during testing to collect 331 // per-statement state. 332 // FIXME: This situation means that the optional contents are not shared 333 // between branches and the like. Practically, this lack of sharing 334 // reduces the precision of the model when the contents are relevant to 335 // the check, like another optional or a boolean that influences control 336 // flow. 337 if (ValueLoc.getType()->isRecordType()) { 338 refreshRecordValue(cast<RecordStorageLocation>(ValueLoc), Env); 339 return &ValueLoc; 340 } else { 341 auto *ValueVal = Env.createValue(ValueLoc.getType()); 342 if (ValueVal == nullptr) 343 return nullptr; 344 Env.setValue(ValueLoc, *ValueVal); 345 return &ValueLoc; 346 } 347 } 348 349 auto Ty = Q.getNonReferenceType(); 350 auto &ValueLoc = Env.createObject(Ty); 351 auto &ValuePtr = Env.create<PointerValue>(ValueLoc); 352 // FIXME: 353 // The change we make to the `value` property below may become visible to 354 // other blocks that aren't successors of the current block and therefore 355 // don't see the change we made above mapping `ValueLoc` to `ValueVal`. For 356 // example: 357 // 358 // void target(optional<int> oo, bool b) { 359 // // `oo` is associated with a `RecordValue` here, which we will call 360 // // `OptionalVal`. 361 // 362 // // The `has_value` property is set on `OptionalVal` (but not the 363 // // `value` property yet). 364 // if (!oo.has_value()) return; 365 // 366 // if (b) { 367 // // Let's assume we transfer the `if` branch first. 368 // // 369 // // This causes us to call `maybeInitializeOptionalValueMember()`, 370 // // which causes us to set the `value` property on `OptionalVal` 371 // // (which had not been set until this point). This `value` property 372 // // refers to a `PointerValue`, which in turn refers to a 373 // // StorageLocation` that is associated to an `IntegerValue`. 374 // oo.value(); 375 // } else { 376 // // Let's assume we transfer the `else` branch after the `if` branch. 377 // // 378 // // We see the `value` property that the `if` branch set on 379 // // `OptionalVal`, but in the environment for this block, the 380 // // `StorageLocation` in the `PointerValue` is not associated with any 381 // // `Value`. 382 // oo.value(); 383 // } 384 // } 385 // 386 // This situation is currently "saved" by the code above that checks whether 387 // the `value` property is already set, and if, the `ValueLoc` is not 388 // associated with a `ValueVal`, creates a new `ValueVal`. 389 // 390 // However, what we should really do is to make sure that the change to the 391 // `value` property does not "leak" to other blocks that are not successors 392 // of this block. To do this, instead of simply setting the `value` property 393 // on the existing `OptionalVal`, we should create a new `Value` for the 394 // optional, set the property on that, and associate the storage location that 395 // is currently associated with the existing `OptionalVal` with the newly 396 // created `Value` instead. 397 OptionalVal.setProperty("value", ValuePtr); 398 return &ValueLoc; 399 } 400 401 void initializeOptionalReference(const Expr *OptionalExpr, 402 const MatchFinder::MatchResult &, 403 LatticeTransferState &State) { 404 if (auto *OptionalVal = State.Env.getValue(*OptionalExpr)) { 405 if (OptionalVal->getProperty("has_value") == nullptr) { 406 setHasValue(*OptionalVal, State.Env.makeAtomicBoolValue()); 407 } 408 } 409 } 410 411 /// Returns true if and only if `OptionalVal` is initialized and known to be 412 /// empty in `Env`. 413 bool isEmptyOptional(const Value &OptionalVal, const Environment &Env) { 414 auto *HasValueVal = 415 cast_or_null<BoolValue>(OptionalVal.getProperty("has_value")); 416 return HasValueVal != nullptr && 417 Env.flowConditionImplies(Env.arena().makeNot(HasValueVal->formula())); 418 } 419 420 /// Returns true if and only if `OptionalVal` is initialized and known to be 421 /// non-empty in `Env`. 422 bool isNonEmptyOptional(const Value &OptionalVal, const Environment &Env) { 423 auto *HasValueVal = 424 cast_or_null<BoolValue>(OptionalVal.getProperty("has_value")); 425 return HasValueVal != nullptr && 426 Env.flowConditionImplies(HasValueVal->formula()); 427 } 428 429 Value *getValueBehindPossiblePointer(const Expr &E, const Environment &Env) { 430 Value *Val = Env.getValue(E); 431 if (auto *PointerVal = dyn_cast_or_null<PointerValue>(Val)) 432 return Env.getValue(PointerVal->getPointeeLoc()); 433 return Val; 434 } 435 436 void transferUnwrapCall(const Expr *UnwrapExpr, const Expr *ObjectExpr, 437 LatticeTransferState &State) { 438 if (auto *OptionalVal = 439 getValueBehindPossiblePointer(*ObjectExpr, State.Env)) { 440 if (State.Env.getStorageLocation(*UnwrapExpr) == nullptr) 441 if (auto *Loc = maybeInitializeOptionalValueMember( 442 UnwrapExpr->getType(), *OptionalVal, State.Env)) 443 State.Env.setStorageLocation(*UnwrapExpr, *Loc); 444 } 445 } 446 447 void transferArrowOpCall(const Expr *UnwrapExpr, const Expr *ObjectExpr, 448 LatticeTransferState &State) { 449 if (auto *OptionalVal = 450 getValueBehindPossiblePointer(*ObjectExpr, State.Env)) { 451 if (auto *Loc = maybeInitializeOptionalValueMember( 452 UnwrapExpr->getType()->getPointeeType(), *OptionalVal, State.Env)) { 453 State.Env.setValue(*UnwrapExpr, State.Env.create<PointerValue>(*Loc)); 454 } 455 } 456 } 457 458 void transferMakeOptionalCall(const CallExpr *E, 459 const MatchFinder::MatchResult &, 460 LatticeTransferState &State) { 461 createOptionalValue(State.Env.getResultObjectLocation(*E), 462 State.Env.getBoolLiteralValue(true), State.Env); 463 } 464 465 void transferOptionalHasValueCall(const CXXMemberCallExpr *CallExpr, 466 const MatchFinder::MatchResult &, 467 LatticeTransferState &State) { 468 if (auto *HasValueVal = getHasValue( 469 State.Env, getValueBehindPossiblePointer( 470 *CallExpr->getImplicitObjectArgument(), State.Env))) { 471 State.Env.setValue(*CallExpr, *HasValueVal); 472 } 473 } 474 475 /// `ModelPred` builds a logical formula relating the predicate in 476 /// `ValueOrPredExpr` to the optional's `has_value` property. 477 void transferValueOrImpl( 478 const clang::Expr *ValueOrPredExpr, const MatchFinder::MatchResult &Result, 479 LatticeTransferState &State, 480 const Formula &(*ModelPred)(Environment &Env, const Formula &ExprVal, 481 const Formula &HasValueVal)) { 482 auto &Env = State.Env; 483 484 const auto *ObjectArgumentExpr = 485 Result.Nodes.getNodeAs<clang::CXXMemberCallExpr>(ValueOrCallID) 486 ->getImplicitObjectArgument(); 487 488 auto *HasValueVal = getHasValue( 489 State.Env, getValueBehindPossiblePointer(*ObjectArgumentExpr, State.Env)); 490 if (HasValueVal == nullptr) 491 return; 492 493 Env.addToFlowCondition(ModelPred(Env, forceBoolValue(Env, *ValueOrPredExpr), 494 HasValueVal->formula())); 495 } 496 497 void transferValueOrStringEmptyCall(const clang::Expr *ComparisonExpr, 498 const MatchFinder::MatchResult &Result, 499 LatticeTransferState &State) { 500 return transferValueOrImpl(ComparisonExpr, Result, State, 501 [](Environment &Env, const Formula &ExprVal, 502 const Formula &HasValueVal) -> const Formula & { 503 auto &A = Env.arena(); 504 // If the result is *not* empty, then we know the 505 // optional must have been holding a value. If 506 // `ExprVal` is true, though, we don't learn 507 // anything definite about `has_value`, so we 508 // don't add any corresponding implications to 509 // the flow condition. 510 return A.makeImplies(A.makeNot(ExprVal), 511 HasValueVal); 512 }); 513 } 514 515 void transferValueOrNotEqX(const Expr *ComparisonExpr, 516 const MatchFinder::MatchResult &Result, 517 LatticeTransferState &State) { 518 transferValueOrImpl(ComparisonExpr, Result, State, 519 [](Environment &Env, const Formula &ExprVal, 520 const Formula &HasValueVal) -> const Formula & { 521 auto &A = Env.arena(); 522 // We know that if `(opt.value_or(X) != X)` then 523 // `opt.hasValue()`, even without knowing further 524 // details about the contents of `opt`. 525 return A.makeImplies(ExprVal, HasValueVal); 526 }); 527 } 528 529 void transferCallReturningOptional(const CallExpr *E, 530 const MatchFinder::MatchResult &Result, 531 LatticeTransferState &State) { 532 if (State.Env.getValue(*E) != nullptr) 533 return; 534 535 RecordStorageLocation *Loc = nullptr; 536 if (E->isPRValue()) { 537 Loc = &State.Env.getResultObjectLocation(*E); 538 } else { 539 Loc = cast_or_null<RecordStorageLocation>(State.Env.getStorageLocation(*E)); 540 if (Loc == nullptr) { 541 Loc = &cast<RecordStorageLocation>(State.Env.createStorageLocation(*E)); 542 State.Env.setStorageLocation(*E, *Loc); 543 } 544 } 545 546 createOptionalValue(*Loc, State.Env.makeAtomicBoolValue(), State.Env); 547 } 548 549 void constructOptionalValue(const Expr &E, Environment &Env, 550 BoolValue &HasValueVal) { 551 RecordStorageLocation &Loc = Env.getResultObjectLocation(E); 552 Env.setValue(E, createOptionalValue(Loc, HasValueVal, Env)); 553 } 554 555 /// Returns a symbolic value for the "has_value" property of an `optional<T>` 556 /// value that is constructed/assigned from a value of type `U` or `optional<U>` 557 /// where `T` is constructible from `U`. 558 BoolValue &valueOrConversionHasValue(const FunctionDecl &F, const Expr &E, 559 const MatchFinder::MatchResult &MatchRes, 560 LatticeTransferState &State) { 561 assert(F.getTemplateSpecializationArgs() != nullptr); 562 assert(F.getTemplateSpecializationArgs()->size() > 0); 563 564 const int TemplateParamOptionalWrappersCount = 565 countOptionalWrappers(*MatchRes.Context, F.getTemplateSpecializationArgs() 566 ->get(0) 567 .getAsType() 568 .getNonReferenceType()); 569 const int ArgTypeOptionalWrappersCount = countOptionalWrappers( 570 *MatchRes.Context, E.getType().getNonReferenceType()); 571 572 // Check if this is a constructor/assignment call for `optional<T>` with 573 // argument of type `U` such that `T` is constructible from `U`. 574 if (TemplateParamOptionalWrappersCount == ArgTypeOptionalWrappersCount) 575 return State.Env.getBoolLiteralValue(true); 576 577 // This is a constructor/assignment call for `optional<T>` with argument of 578 // type `optional<U>` such that `T` is constructible from `U`. 579 if (auto *HasValueVal = getHasValue(State.Env, State.Env.getValue(E))) 580 return *HasValueVal; 581 return State.Env.makeAtomicBoolValue(); 582 } 583 584 void transferValueOrConversionConstructor( 585 const CXXConstructExpr *E, const MatchFinder::MatchResult &MatchRes, 586 LatticeTransferState &State) { 587 assert(E->getNumArgs() > 0); 588 589 constructOptionalValue(*E, State.Env, 590 valueOrConversionHasValue(*E->getConstructor(), 591 *E->getArg(0), MatchRes, 592 State)); 593 } 594 595 void transferAssignment(const CXXOperatorCallExpr *E, BoolValue &HasValueVal, 596 LatticeTransferState &State) { 597 assert(E->getNumArgs() > 0); 598 599 if (auto *Loc = cast<RecordStorageLocation>( 600 State.Env.getStorageLocation(*E->getArg(0)))) { 601 createOptionalValue(*Loc, HasValueVal, State.Env); 602 603 // Assign a storage location for the whole expression. 604 State.Env.setStorageLocation(*E, *Loc); 605 } 606 } 607 608 void transferValueOrConversionAssignment( 609 const CXXOperatorCallExpr *E, const MatchFinder::MatchResult &MatchRes, 610 LatticeTransferState &State) { 611 assert(E->getNumArgs() > 1); 612 transferAssignment(E, 613 valueOrConversionHasValue(*E->getDirectCallee(), 614 *E->getArg(1), MatchRes, State), 615 State); 616 } 617 618 void transferNulloptAssignment(const CXXOperatorCallExpr *E, 619 const MatchFinder::MatchResult &, 620 LatticeTransferState &State) { 621 transferAssignment(E, State.Env.getBoolLiteralValue(false), State); 622 } 623 624 void transferSwap(RecordStorageLocation *Loc1, RecordStorageLocation *Loc2, 625 Environment &Env) { 626 // We account for cases where one or both of the optionals are not modeled, 627 // either lacking associated storage locations, or lacking values associated 628 // to such storage locations. 629 630 if (Loc1 == nullptr) { 631 if (Loc2 != nullptr) 632 createOptionalValue(*Loc2, Env.makeAtomicBoolValue(), Env); 633 return; 634 } 635 if (Loc2 == nullptr) { 636 createOptionalValue(*Loc1, Env.makeAtomicBoolValue(), Env); 637 return; 638 } 639 640 // Both expressions have locations, though they may not have corresponding 641 // values. In that case, we create a fresh value at this point. Note that if 642 // two branches both do this, they will not share the value, but it at least 643 // allows for local reasoning about the value. To avoid the above, we would 644 // need *lazy* value allocation. 645 // FIXME: allocate values lazily, instead of just creating a fresh value. 646 BoolValue *BoolVal1 = getHasValue(Env, Env.getValue(*Loc1)); 647 if (BoolVal1 == nullptr) 648 BoolVal1 = &Env.makeAtomicBoolValue(); 649 650 BoolValue *BoolVal2 = getHasValue(Env, Env.getValue(*Loc2)); 651 if (BoolVal2 == nullptr) 652 BoolVal2 = &Env.makeAtomicBoolValue(); 653 654 createOptionalValue(*Loc1, *BoolVal2, Env); 655 createOptionalValue(*Loc2, *BoolVal1, Env); 656 } 657 658 void transferSwapCall(const CXXMemberCallExpr *E, 659 const MatchFinder::MatchResult &, 660 LatticeTransferState &State) { 661 assert(E->getNumArgs() == 1); 662 auto *OtherLoc = cast_or_null<RecordStorageLocation>( 663 State.Env.getStorageLocation(*E->getArg(0))); 664 transferSwap(getImplicitObjectLocation(*E, State.Env), OtherLoc, State.Env); 665 } 666 667 void transferStdSwapCall(const CallExpr *E, const MatchFinder::MatchResult &, 668 LatticeTransferState &State) { 669 assert(E->getNumArgs() == 2); 670 auto *Arg0Loc = cast_or_null<RecordStorageLocation>( 671 State.Env.getStorageLocation(*E->getArg(0))); 672 auto *Arg1Loc = cast_or_null<RecordStorageLocation>( 673 State.Env.getStorageLocation(*E->getArg(1))); 674 transferSwap(Arg0Loc, Arg1Loc, State.Env); 675 } 676 677 void transferStdForwardCall(const CallExpr *E, const MatchFinder::MatchResult &, 678 LatticeTransferState &State) { 679 assert(E->getNumArgs() == 1); 680 681 if (auto *Loc = State.Env.getStorageLocation(*E->getArg(0))) 682 State.Env.setStorageLocation(*E, *Loc); 683 } 684 685 const Formula &evaluateEquality(Arena &A, const Formula &EqVal, 686 const Formula &LHS, const Formula &RHS) { 687 // Logically, an optional<T> object is composed of two values - a `has_value` 688 // bit and a value of type T. Equality of optional objects compares both 689 // values. Therefore, merely comparing the `has_value` bits isn't sufficient: 690 // when two optional objects are engaged, the equality of their respective 691 // values of type T matters. Since we only track the `has_value` bits, we 692 // can't make any conclusions about equality when we know that two optional 693 // objects are engaged. 694 // 695 // We express this as two facts about the equality: 696 // a) EqVal => (LHS & RHS) v (!RHS & !LHS) 697 // If they are equal, then either both are set or both are unset. 698 // b) (!LHS & !RHS) => EqVal 699 // If neither is set, then they are equal. 700 // We rewrite b) as !EqVal => (LHS v RHS), for a more compact formula. 701 return A.makeAnd( 702 A.makeImplies(EqVal, A.makeOr(A.makeAnd(LHS, RHS), 703 A.makeAnd(A.makeNot(LHS), A.makeNot(RHS)))), 704 A.makeImplies(A.makeNot(EqVal), A.makeOr(LHS, RHS))); 705 } 706 707 void transferOptionalAndOptionalCmp(const clang::CXXOperatorCallExpr *CmpExpr, 708 const MatchFinder::MatchResult &, 709 LatticeTransferState &State) { 710 Environment &Env = State.Env; 711 auto &A = Env.arena(); 712 auto *CmpValue = &forceBoolValue(Env, *CmpExpr); 713 if (auto *LHasVal = getHasValue(Env, Env.getValue(*CmpExpr->getArg(0)))) 714 if (auto *RHasVal = getHasValue(Env, Env.getValue(*CmpExpr->getArg(1)))) { 715 if (CmpExpr->getOperator() == clang::OO_ExclaimEqual) 716 CmpValue = &A.makeNot(*CmpValue); 717 Env.addToFlowCondition(evaluateEquality(A, *CmpValue, LHasVal->formula(), 718 RHasVal->formula())); 719 } 720 } 721 722 void transferOptionalAndValueCmp(const clang::CXXOperatorCallExpr *CmpExpr, 723 const clang::Expr *E, Environment &Env) { 724 auto &A = Env.arena(); 725 auto *CmpValue = &forceBoolValue(Env, *CmpExpr); 726 if (auto *HasVal = getHasValue(Env, Env.getValue(*E))) { 727 if (CmpExpr->getOperator() == clang::OO_ExclaimEqual) 728 CmpValue = &A.makeNot(*CmpValue); 729 Env.addToFlowCondition( 730 evaluateEquality(A, *CmpValue, HasVal->formula(), A.makeLiteral(true))); 731 } 732 } 733 734 std::optional<StatementMatcher> 735 ignorableOptional(const UncheckedOptionalAccessModelOptions &Options) { 736 if (Options.IgnoreSmartPointerDereference) { 737 auto SmartPtrUse = expr(ignoringParenImpCasts(cxxOperatorCallExpr( 738 anyOf(hasOverloadedOperatorName("->"), hasOverloadedOperatorName("*")), 739 unless(hasArgument(0, expr(hasOptionalType())))))); 740 return expr( 741 anyOf(SmartPtrUse, memberExpr(hasObjectExpression(SmartPtrUse)))); 742 } 743 return std::nullopt; 744 } 745 746 StatementMatcher 747 valueCall(const std::optional<StatementMatcher> &IgnorableOptional) { 748 return isOptionalMemberCallWithNameMatcher(hasName("value"), 749 IgnorableOptional); 750 } 751 752 StatementMatcher 753 valueOperatorCall(const std::optional<StatementMatcher> &IgnorableOptional) { 754 return expr(anyOf(isOptionalOperatorCallWithName("*", IgnorableOptional), 755 isOptionalOperatorCallWithName("->", IgnorableOptional))); 756 } 757 758 auto buildTransferMatchSwitch() { 759 // FIXME: Evaluate the efficiency of matchers. If using matchers results in a 760 // lot of duplicated work (e.g. string comparisons), consider providing APIs 761 // that avoid it through memoization. 762 return CFGMatchSwitchBuilder<LatticeTransferState>() 763 // Attach a symbolic "has_value" state to optional values that we see for 764 // the first time. 765 .CaseOfCFGStmt<Expr>( 766 expr(anyOf(declRefExpr(), memberExpr()), hasOptionalType()), 767 initializeOptionalReference) 768 769 // make_optional 770 .CaseOfCFGStmt<CallExpr>(isMakeOptionalCall(), transferMakeOptionalCall) 771 772 // optional::optional (in place) 773 .CaseOfCFGStmt<CXXConstructExpr>( 774 isOptionalInPlaceConstructor(), 775 [](const CXXConstructExpr *E, const MatchFinder::MatchResult &, 776 LatticeTransferState &State) { 777 constructOptionalValue(*E, State.Env, 778 State.Env.getBoolLiteralValue(true)); 779 }) 780 // nullopt_t::nullopt_t 781 .CaseOfCFGStmt<CXXConstructExpr>( 782 isNulloptConstructor(), 783 [](const CXXConstructExpr *E, const MatchFinder::MatchResult &, 784 LatticeTransferState &State) { 785 constructOptionalValue(*E, State.Env, 786 State.Env.getBoolLiteralValue(false)); 787 }) 788 // optional::optional(nullopt_t) 789 .CaseOfCFGStmt<CXXConstructExpr>( 790 isOptionalNulloptConstructor(), 791 [](const CXXConstructExpr *E, const MatchFinder::MatchResult &, 792 LatticeTransferState &State) { 793 constructOptionalValue(*E, State.Env, 794 State.Env.getBoolLiteralValue(false)); 795 }) 796 // optional::optional (value/conversion) 797 .CaseOfCFGStmt<CXXConstructExpr>(isOptionalValueOrConversionConstructor(), 798 transferValueOrConversionConstructor) 799 800 // optional::operator= 801 .CaseOfCFGStmt<CXXOperatorCallExpr>( 802 isOptionalValueOrConversionAssignment(), 803 transferValueOrConversionAssignment) 804 .CaseOfCFGStmt<CXXOperatorCallExpr>(isOptionalNulloptAssignment(), 805 transferNulloptAssignment) 806 807 // optional::value 808 .CaseOfCFGStmt<CXXMemberCallExpr>( 809 valueCall(std::nullopt), 810 [](const CXXMemberCallExpr *E, const MatchFinder::MatchResult &, 811 LatticeTransferState &State) { 812 transferUnwrapCall(E, E->getImplicitObjectArgument(), State); 813 }) 814 815 // optional::operator* 816 .CaseOfCFGStmt<CallExpr>(isOptionalOperatorCallWithName("*"), 817 [](const CallExpr *E, 818 const MatchFinder::MatchResult &, 819 LatticeTransferState &State) { 820 transferUnwrapCall(E, E->getArg(0), State); 821 }) 822 823 // optional::operator-> 824 .CaseOfCFGStmt<CallExpr>(isOptionalOperatorCallWithName("->"), 825 [](const CallExpr *E, 826 const MatchFinder::MatchResult &, 827 LatticeTransferState &State) { 828 transferArrowOpCall(E, E->getArg(0), State); 829 }) 830 831 // optional::has_value, optional::hasValue 832 // Of the supported optionals only folly::Optional uses hasValue, but this 833 // will also pass for other types 834 .CaseOfCFGStmt<CXXMemberCallExpr>( 835 isOptionalMemberCallWithNameMatcher( 836 hasAnyName("has_value", "hasValue")), 837 transferOptionalHasValueCall) 838 839 // optional::operator bool 840 .CaseOfCFGStmt<CXXMemberCallExpr>( 841 isOptionalMemberCallWithNameMatcher(hasName("operator bool")), 842 transferOptionalHasValueCall) 843 844 // optional::emplace 845 .CaseOfCFGStmt<CXXMemberCallExpr>( 846 isOptionalMemberCallWithNameMatcher(hasName("emplace")), 847 [](const CXXMemberCallExpr *E, const MatchFinder::MatchResult &, 848 LatticeTransferState &State) { 849 if (RecordStorageLocation *Loc = 850 getImplicitObjectLocation(*E, State.Env)) { 851 createOptionalValue(*Loc, State.Env.getBoolLiteralValue(true), 852 State.Env); 853 } 854 }) 855 856 // optional::reset 857 .CaseOfCFGStmt<CXXMemberCallExpr>( 858 isOptionalMemberCallWithNameMatcher(hasName("reset")), 859 [](const CXXMemberCallExpr *E, const MatchFinder::MatchResult &, 860 LatticeTransferState &State) { 861 if (RecordStorageLocation *Loc = 862 getImplicitObjectLocation(*E, State.Env)) { 863 createOptionalValue(*Loc, State.Env.getBoolLiteralValue(false), 864 State.Env); 865 } 866 }) 867 868 // optional::swap 869 .CaseOfCFGStmt<CXXMemberCallExpr>( 870 isOptionalMemberCallWithNameMatcher(hasName("swap")), 871 transferSwapCall) 872 873 // std::swap 874 .CaseOfCFGStmt<CallExpr>(isStdSwapCall(), transferStdSwapCall) 875 876 // std::forward 877 .CaseOfCFGStmt<CallExpr>(isStdForwardCall(), transferStdForwardCall) 878 879 // opt.value_or("").empty() 880 .CaseOfCFGStmt<Expr>(isValueOrStringEmptyCall(), 881 transferValueOrStringEmptyCall) 882 883 // opt.value_or(X) != X 884 .CaseOfCFGStmt<Expr>(isValueOrNotEqX(), transferValueOrNotEqX) 885 886 // Comparisons (==, !=): 887 .CaseOfCFGStmt<CXXOperatorCallExpr>( 888 isComparisonOperatorCall(hasAnyOptionalType(), hasAnyOptionalType()), 889 transferOptionalAndOptionalCmp) 890 .CaseOfCFGStmt<CXXOperatorCallExpr>( 891 isComparisonOperatorCall(hasOptionalType(), 892 unless(hasAnyOptionalType())), 893 [](const clang::CXXOperatorCallExpr *Cmp, 894 const MatchFinder::MatchResult &, LatticeTransferState &State) { 895 transferOptionalAndValueCmp(Cmp, Cmp->getArg(0), State.Env); 896 }) 897 .CaseOfCFGStmt<CXXOperatorCallExpr>( 898 isComparisonOperatorCall(unless(hasAnyOptionalType()), 899 hasOptionalType()), 900 [](const clang::CXXOperatorCallExpr *Cmp, 901 const MatchFinder::MatchResult &, LatticeTransferState &State) { 902 transferOptionalAndValueCmp(Cmp, Cmp->getArg(1), State.Env); 903 }) 904 905 // returns optional 906 .CaseOfCFGStmt<CallExpr>(isCallReturningOptional(), 907 transferCallReturningOptional) 908 909 .Build(); 910 } 911 912 std::vector<SourceLocation> diagnoseUnwrapCall(const Expr *ObjectExpr, 913 const Environment &Env) { 914 if (auto *OptionalVal = getValueBehindPossiblePointer(*ObjectExpr, Env)) { 915 auto *Prop = OptionalVal->getProperty("has_value"); 916 if (auto *HasValueVal = cast_or_null<BoolValue>(Prop)) { 917 if (Env.flowConditionImplies(HasValueVal->formula())) 918 return {}; 919 } 920 } 921 922 // Record that this unwrap is *not* provably safe. 923 // FIXME: include either the name of the optional (if applicable) or a source 924 // range of the access for easier interpretation of the result. 925 return {ObjectExpr->getBeginLoc()}; 926 } 927 928 auto buildDiagnoseMatchSwitch( 929 const UncheckedOptionalAccessModelOptions &Options) { 930 // FIXME: Evaluate the efficiency of matchers. If using matchers results in a 931 // lot of duplicated work (e.g. string comparisons), consider providing APIs 932 // that avoid it through memoization. 933 auto IgnorableOptional = ignorableOptional(Options); 934 return CFGMatchSwitchBuilder<const Environment, std::vector<SourceLocation>>() 935 // optional::value 936 .CaseOfCFGStmt<CXXMemberCallExpr>( 937 valueCall(IgnorableOptional), 938 [](const CXXMemberCallExpr *E, const MatchFinder::MatchResult &, 939 const Environment &Env) { 940 return diagnoseUnwrapCall(E->getImplicitObjectArgument(), Env); 941 }) 942 943 // optional::operator*, optional::operator-> 944 .CaseOfCFGStmt<CallExpr>(valueOperatorCall(IgnorableOptional), 945 [](const CallExpr *E, 946 const MatchFinder::MatchResult &, 947 const Environment &Env) { 948 return diagnoseUnwrapCall(E->getArg(0), Env); 949 }) 950 .Build(); 951 } 952 953 } // namespace 954 955 ast_matchers::DeclarationMatcher 956 UncheckedOptionalAccessModel::optionalClassDecl() { 957 return optionalClass(); 958 } 959 960 UncheckedOptionalAccessModel::UncheckedOptionalAccessModel(ASTContext &Ctx) 961 : DataflowAnalysis<UncheckedOptionalAccessModel, NoopLattice>(Ctx), 962 TransferMatchSwitch(buildTransferMatchSwitch()) {} 963 964 void UncheckedOptionalAccessModel::transfer(const CFGElement &Elt, 965 NoopLattice &L, Environment &Env) { 966 LatticeTransferState State(L, Env); 967 TransferMatchSwitch(Elt, getASTContext(), State); 968 } 969 970 ComparisonResult UncheckedOptionalAccessModel::compare( 971 QualType Type, const Value &Val1, const Environment &Env1, 972 const Value &Val2, const Environment &Env2) { 973 if (!isOptionalType(Type)) 974 return ComparisonResult::Unknown; 975 bool MustNonEmpty1 = isNonEmptyOptional(Val1, Env1); 976 bool MustNonEmpty2 = isNonEmptyOptional(Val2, Env2); 977 if (MustNonEmpty1 && MustNonEmpty2) 978 return ComparisonResult::Same; 979 // If exactly one is true, then they're different, no reason to check whether 980 // they're definitely empty. 981 if (MustNonEmpty1 || MustNonEmpty2) 982 return ComparisonResult::Different; 983 // Check if they're both definitely empty. 984 return (isEmptyOptional(Val1, Env1) && isEmptyOptional(Val2, Env2)) 985 ? ComparisonResult::Same 986 : ComparisonResult::Different; 987 } 988 989 bool UncheckedOptionalAccessModel::merge(QualType Type, const Value &Val1, 990 const Environment &Env1, 991 const Value &Val2, 992 const Environment &Env2, 993 Value &MergedVal, 994 Environment &MergedEnv) { 995 if (!isOptionalType(Type)) 996 return true; 997 // FIXME: uses same approach as join for `BoolValues`. Requires non-const 998 // values, though, so will require updating the interface. 999 auto &HasValueVal = MergedEnv.makeAtomicBoolValue(); 1000 bool MustNonEmpty1 = isNonEmptyOptional(Val1, Env1); 1001 bool MustNonEmpty2 = isNonEmptyOptional(Val2, Env2); 1002 if (MustNonEmpty1 && MustNonEmpty2) 1003 MergedEnv.addToFlowCondition(HasValueVal.formula()); 1004 else if ( 1005 // Only make the costly calls to `isEmptyOptional` if we got "unknown" 1006 // (false) for both calls to `isNonEmptyOptional`. 1007 !MustNonEmpty1 && !MustNonEmpty2 && isEmptyOptional(Val1, Env1) && 1008 isEmptyOptional(Val2, Env2)) 1009 MergedEnv.addToFlowCondition( 1010 MergedEnv.arena().makeNot(HasValueVal.formula())); 1011 setHasValue(MergedVal, HasValueVal); 1012 return true; 1013 } 1014 1015 Value *UncheckedOptionalAccessModel::widen(QualType Type, Value &Prev, 1016 const Environment &PrevEnv, 1017 Value &Current, 1018 Environment &CurrentEnv) { 1019 switch (compare(Type, Prev, PrevEnv, Current, CurrentEnv)) { 1020 case ComparisonResult::Same: 1021 return &Prev; 1022 case ComparisonResult::Different: 1023 if (auto *PrevHasVal = 1024 cast_or_null<BoolValue>(Prev.getProperty("has_value"))) { 1025 if (isa<TopBoolValue>(PrevHasVal)) 1026 return &Prev; 1027 } 1028 if (auto *CurrentHasVal = 1029 cast_or_null<BoolValue>(Current.getProperty("has_value"))) { 1030 if (isa<TopBoolValue>(CurrentHasVal)) 1031 return &Current; 1032 } 1033 return &createOptionalValue(cast<RecordValue>(Current).getLoc(), 1034 CurrentEnv.makeTopBoolValue(), CurrentEnv); 1035 case ComparisonResult::Unknown: 1036 return nullptr; 1037 } 1038 llvm_unreachable("all cases covered in switch"); 1039 } 1040 1041 UncheckedOptionalAccessDiagnoser::UncheckedOptionalAccessDiagnoser( 1042 UncheckedOptionalAccessModelOptions Options) 1043 : DiagnoseMatchSwitch(buildDiagnoseMatchSwitch(Options)) {} 1044 1045 } // namespace dataflow 1046 } // namespace clang 1047