clang 24.0.0git
UncheckedExpectedAccessModel.cpp
Go to the documentation of this file.
1//===-- UncheckedExpectedAccessModel.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 accesses to the
10// values of `std::expected` and `tl::expected` objects.
11//
12//===----------------------------------------------------------------------===//
13
15#include "clang/AST/DeclCXX.h"
16#include "clang/AST/ExprCXX.h"
22
23namespace clang {
24namespace dataflow {
25
26/// Returns true if `DC` is `std` or the top-level `tl` namespace, which holds
27/// `tl::expected` (https://github.com/TartanLlama/expected).
28static bool isSupportedNamespace(const DeclContext &DC) {
29 if (DC.isStdNamespace())
30 return true;
31 const auto *NS = dyn_cast<NamespaceDecl>(&DC);
32 return NS != nullptr && NS->getDeclName().isIdentifier() &&
33 NS->getName() == "tl" && NS->getParent()->isTranslationUnit();
34}
35
36static bool isExpectedClass(const CXXRecordDecl &RD) {
37 return RD.getDeclName().isIdentifier() && RD.getName() == "expected" &&
39}
40
41/// Returns the name of the expected class `RD` to show in diagnostics.
42static llvm::StringRef getExpectedTypeName(const CXXRecordDecl &RD) {
43 return RD.getDeclContext()->isStdNamespace() ? "std::expected"
44 : "tl::expected";
45}
46
47// Classes derived from the expected class are deliberately not
48// supported.
49static bool isExpectedType(QualType Ty) {
50 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
51 return RD != nullptr && isExpectedClass(*RD);
52}
53
54namespace {
55
56using namespace ::clang::ast_matchers;
57
58using LatticeTransferState = TransferState<NoopLattice>;
59
60AST_MATCHER(CXXRecordDecl, expectedClass) { return isExpectedClass(Node); }
61
62auto expectedMemberCall(ast_matchers::internal::Matcher<NamedDecl> Name) {
63 return cxxMemberCallExpr(
64 callee(cxxMethodDecl(Name, ofClass(expectedClass()))));
65}
66
67auto expectedOperatorCall(ArrayRef<StringRef> Names) {
69 callee(cxxMethodDecl(ofClass(expectedClass()))));
70}
71
72StorageLocation &locForHasValue(const RecordStorageLocation &ExpectedLoc) {
73 return ExpectedLoc.getSyntheticField("has_value");
74}
75
76/// Returns the symbolic value that represents the "has_value" property of the
77/// expected at `ExpectedLoc`. Returns null if `ExpectedLoc` is null or is not
78/// the location of a supported expected object (e.g. of a
79/// derived class object).
80BoolValue *getHasValue(Environment &Env, RecordStorageLocation *ExpectedLoc) {
81 if (ExpectedLoc == nullptr || !isExpectedType(ExpectedLoc->getType()))
82 return nullptr;
83 StorageLocation &HasValueLoc = locForHasValue(*ExpectedLoc);
84 auto *HasValueVal = Env.get<BoolValue>(HasValueLoc);
85 if (HasValueVal == nullptr) {
86 HasValueVal = &Env.makeAtomicBoolValue();
87 Env.setValue(HasValueLoc, *HasValueVal);
88 }
89 return HasValueVal;
90}
91
92void transferHasValueCall(const CXXMemberCallExpr *E,
93 const MatchFinder::MatchResult &,
94 LatticeTransferState &State) {
95 if (BoolValue *HasValueVal =
96 getHasValue(State.Env, getImplicitObjectLocation(*E, State.Env)))
97 State.Env.setValue(*E, *HasValueVal);
98}
99
100// FIXME: Model the constructors, assignments, `emplace` and `swap`.
103 // expected::has_value, expected::operator bool
104 .CaseOfCFGStmt<CXXMemberCallExpr>(
105 expectedMemberCall(hasAnyName("has_value", "operator bool")),
106 transferHasValueCall)
107 .Build();
108}
109
110/// `ExpectedClass` is the class of the called accessor.
111llvm::SmallVector<UncheckedExpectedAccessDiagnostic>
112diagnoseAccess(SourceLocation AccessLoc, UncheckedExpectedAccessKind Kind,
113 const CXXRecordDecl &ExpectedClass,
114 const RecordStorageLocation *ExpectedLoc,
115 const Environment &Env) {
116 if (ExpectedLoc != nullptr) {
117 // The matchers only check the class of the called accessor, but the object
118 // may be of a derived class, whose location has no "has_value" field.
119 if (!isExpectedType(ExpectedLoc->getType()))
120 return {};
121 if (auto *HasValueVal = Env.get<BoolValue>(locForHasValue(*ExpectedLoc))) {
122 // The value may only be accessed if the expected holds a value, and the
123 // error only if it does not.
125 ? HasValueVal->formula()
126 : Env.arena().makeNot(HasValueVal->formula());
127 if (Env.proves(Safe))
128 return {};
129 }
130 }
131
132 return {{AccessLoc, Kind, getExpectedTypeName(ExpectedClass)}};
133}
134
135auto buildDiagnoseMatchSwitch() {
137 const Environment,
138 llvm::SmallVector<UncheckedExpectedAccessDiagnostic>>()
139 // expected::value
140 .CaseOfCFGStmt<CXXMemberCallExpr>(
141 expectedMemberCall(hasName("value")),
142 [](const CXXMemberCallExpr *E, const MatchFinder::MatchResult &,
143 const Environment &Env) {
144 return diagnoseAccess(E->getExprLoc(),
146 *E->getMethodDecl()->getParent(),
147 getImplicitObjectLocation(*E, Env), Env);
148 })
149 // expected::operator*, expected::operator->
150 .CaseOfCFGStmt<CXXOperatorCallExpr>(
151 expectedOperatorCall({"*", "->"}),
152 [](const CXXOperatorCallExpr *E, const MatchFinder::MatchResult &,
153 const Environment &Env) {
154 // `getExprLoc` of `operator->` is the start of the object
155 // expression, so point at the operator token instead.
156 return diagnoseAccess(
157 E->getOperatorLoc(), UncheckedExpectedAccessKind::Value,
158 *cast<CXXMethodDecl>(E->getCalleeDecl())->getParent(),
159 Env.get<RecordStorageLocation>(*E->getArg(0)), Env);
160 })
161 // expected::error
162 .CaseOfCFGStmt<CXXMemberCallExpr>(
163 expectedMemberCall(hasName("error")),
164 [](const CXXMemberCallExpr *E, const MatchFinder::MatchResult &,
165 const Environment &Env) {
166 return diagnoseAccess(E->getExprLoc(),
168 *E->getMethodDecl()->getParent(),
169 getImplicitObjectLocation(*E, Env), Env);
170 })
171 .Build();
172}
173
174} // namespace
175
178 return callExpr(callee(cxxMethodDecl(ofClass(expectedClass()))));
179}
180
182 Environment &Env)
184 TransferMatchSwitch(buildTransferMatchSwitch()) {
185 Env.getDataflowAnalysisContext().setSyntheticFieldCallback(
186 [&Ctx](QualType Ty) -> llvm::StringMap<QualType> {
187 if (!isExpectedType(Ty))
188 return {};
189 return {{"has_value", Ctx.BoolTy}};
190 });
191}
192
194 NoopLattice &L, Environment &Env) {
195 LatticeTransferState State(L, Env);
196 TransferMatchSwitch(Elt, getASTContext(), State);
197}
198
200 : DiagnoseMatchSwitch(buildDiagnoseMatchSwitch()) {}
201
202} // namespace dataflow
203} // namespace clang
#define AST_MATCHER(Type, DefineMatcher)
AST_MATCHER(Type, DefineMatcher) { ... } defines a zero parameter function named DefineMatcher() that...
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the clang::Expr interface and subclasses for C++ expressions.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:245
CanQualType BoolTy
Represents a top-level expression in a basic block.
Definition CFG.h:55
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1467
bool isStdNamespace() const
DeclContext * getDeclContext()
Definition DeclBase.h:457
bool isIdentifier() const
Predicate functions for querying what type of name this is.
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:303
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:342
A (possibly-)qualified type.
Definition TypeBase.h:938
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
Models a boolean.
Definition Value.h:94
Collects cases of a "match switch": a collection of matchers paired with callbacks,...
CFGMatchSwitchBuilder && CaseOfCFGStmt(MatchSwitchMatcher< Stmt > M, MatchSwitchAction< NodeT, State, Result > A) &&
Registers an action A for CFGStmts that will be triggered by the match of the pattern M against the S...
Holds the state of the program (store and heap) at a given program point.
DataflowAnalysisContext & getDataflowAnalysisContext() const
Returns the DataflowAnalysisContext used by the environment.
Trivial lattice for dataflow analysis with exactly one element.
Definition NoopLattice.h:27
A storage location for a record (struct, class, or union).
Base class for elements of the local variable store and of the heap.
UncheckedExpectedAccessModel(ASTContext &Ctx, Environment &Env)
static ast_matchers::StatementMatcher callToExpectedClass()
Returns a matcher for calls to member functions of a supported expected type.
void transfer(const CFGElement &Elt, NoopLattice &L, Environment &Env)
const internal::VariadicDynCastAllOfMatcher< Stmt, CallExpr > callExpr
Matches call expressions.
const internal::VariadicFunction< internal::PolymorphicMatcher< internal::HasOverloadedOperatorNameMatcher, AST_POLYMORPHIC_SUPPORTED_TYPES(CXXOperatorCallExpr, FunctionDecl), std::vector< std::string > >, StringRef, internal::hasAnyOverloadedOperatorNameFunc > hasAnyOverloadedOperatorName
Matches overloaded operator names.
const internal::VariadicFunction< internal::Matcher< NamedDecl >, StringRef, internal::hasAnyNameFunc > hasAnyName
Matches NamedDecl nodes that have any of the specified names.
internal::Matcher< Stmt > StatementMatcher
CFGMatchSwitch< LatticeTransferState > buildTransferMatchSwitch(ASTContext &Ctx, CFGMatchSwitchBuilder< LatticeTransferState > Builder)
static bool isSupportedNamespace(const DeclContext &DC)
Returns true if DC is std or the top-level tl namespace, which holds tl::expected (https://github....
static bool isExpectedType(QualType Ty)
internal::Matcher< NamedDecl > hasName(StringRef Name)
Matches NamedDecl nodes that have the specified name.
UncheckedExpectedAccessKind
The part of an expected object that is accessed.
@ Value
value(), operator* or operator->, which require a value.
const internal::VariadicDynCastAllOfMatcher< Stmt, CXXMemberCallExpr > cxxMemberCallExpr
Matches member call expressions.
static llvm::StringRef getExpectedTypeName(const CXXRecordDecl &RD)
Returns the name of the expected class RD to show in diagnostics.
static bool isExpectedClass(const CXXRecordDecl &RD)
const internal::VariadicDynCastAllOfMatcher< Stmt, CXXOperatorCallExpr > cxxOperatorCallExpr
Matches overloaded operator calls.
RecordStorageLocation * getImplicitObjectLocation(const CXXMemberCallExpr &MCE, const Environment &Env)
Returns the storage location for the implicit object of a CXXMemberCallExpr, or null if none is defin...
const internal::VariadicDynCastAllOfMatcher< Decl, CXXMethodDecl > cxxMethodDecl
Matches method declarations.
Top level wrappers for InstallAPI frontend operations.
@ ExpectedClass
U cast(CodeGen::Address addr)
Definition Address.h:327