clang 24.0.0git
DynamicTypeChecker.cpp
Go to the documentation of this file.
1//== DynamicTypeChecker.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 checker looks for cases where the dynamic type of an object is unrelated
10// to its static type. The type information utilized by this check is collected
11// by the DynamicTypePropagation checker. This check does not report any type
12// error for ObjC Generic types, in order to avoid duplicate erros from the
13// ObjC Generics checker. This checker is not supposed to modify the program
14// state, it is just the observer of the type information provided by other
15// checkers.
16//
17//===----------------------------------------------------------------------===//
18
25
26using namespace clang;
27using namespace ento;
28
29namespace {
30class DynamicTypeChecker : public Checker<check::PostStmt<ImplicitCastExpr>> {
31 const BugType BT{this, "Dynamic and static type mismatch", "Type Error"};
32
33 class DynamicTypeBugVisitor : public BugReporterVisitor {
34 public:
35 DynamicTypeBugVisitor(const MemRegion *Reg) : Reg(Reg) {}
36
37 void Profile(llvm::FoldingSetNodeID &ID) const override {
38 static int X = 0;
39 ID.AddPointer(&X);
40 ID.AddPointer(Reg);
41 }
42
43 PathDiagnosticPieceRef VisitNode(const ExplodedNode *N,
44 BugReporterContext &BRC,
45 PathSensitiveBugReport &BR) override;
46
47 private:
48 // The tracked region.
49 const MemRegion *Reg;
50 };
51
52 void reportTypeError(QualType DynamicType, QualType StaticType,
53 const MemRegion *Reg, const Stmt *ReportedNode,
54 CheckerContext &C) const;
55
56public:
57 void checkPostStmt(const ImplicitCastExpr *CE, CheckerContext &C) const;
58};
59}
60
61void DynamicTypeChecker::reportTypeError(QualType DynamicType,
62 QualType StaticType,
63 const MemRegion *Reg,
64 const Stmt *ReportedNode,
65 CheckerContext &C) const {
66 SmallString<192> Buf;
67 llvm::raw_svector_ostream OS(Buf);
68 OS << "Object has a dynamic type '";
69 QualType::print(DynamicType.getTypePtr(), Qualifiers(), OS, C.getLangOpts(),
70 llvm::Twine());
71 OS << "' which is incompatible with static type '";
72 QualType::print(StaticType.getTypePtr(), Qualifiers(), OS, C.getLangOpts(),
73 llvm::Twine());
74 OS << "'";
75 ExplodedNode *N = C.generateNonFatalErrorNode();
76 if (!N)
77 return;
78 auto R = std::make_unique<PathSensitiveBugReport>(BT, OS.str(), N);
79 R->markInteresting(Reg);
80 R->addVisitor(std::make_unique<DynamicTypeBugVisitor>(Reg));
81 R->addRange(ReportedNode->getSourceRange());
82 C.emitReport(std::move(R));
83}
84
85PathDiagnosticPieceRef DynamicTypeChecker::DynamicTypeBugVisitor::VisitNode(
86 const ExplodedNode *N, BugReporterContext &BRC, PathSensitiveBugReport &) {
87 ProgramStateRef State = N->getState();
88 ProgramStateRef StatePrev = N->getFirstPred()->getState();
89
90 DynamicTypeInfo TrackedType = getDynamicTypeInfo(State, Reg);
91 DynamicTypeInfo TrackedTypePrev = getDynamicTypeInfo(StatePrev, Reg);
92 if (!TrackedType.isValid())
93 return nullptr;
94
95 if (TrackedTypePrev.isValid() &&
96 TrackedTypePrev.getType() == TrackedType.getType())
97 return nullptr;
98
99 // Retrieve the associated statement.
100 const Stmt *S = N->getStmtForDiagnostics();
101 if (!S)
102 return nullptr;
103
104 const LangOptions &LangOpts = BRC.getASTContext().getLangOpts();
105
106 SmallString<256> Buf;
107 llvm::raw_svector_ostream OS(Buf);
108 OS << "Type '";
109 QualType::print(TrackedType.getType().getTypePtr(), Qualifiers(), OS,
110 LangOpts, llvm::Twine());
111 OS << "' is inferred from ";
112
113 if (const auto *ExplicitCast = dyn_cast<ExplicitCastExpr>(S)) {
114 OS << "explicit cast (from '";
115 QualType::print(ExplicitCast->getSubExpr()->getType().getTypePtr(),
116 Qualifiers(), OS, LangOpts, llvm::Twine());
117 OS << "' to '";
118 QualType::print(ExplicitCast->getType().getTypePtr(), Qualifiers(), OS,
119 LangOpts, llvm::Twine());
120 OS << "')";
121 } else if (const auto *ImplicitCast = dyn_cast<ImplicitCastExpr>(S)) {
122 OS << "implicit cast (from '";
123 QualType::print(ImplicitCast->getSubExpr()->getType().getTypePtr(),
124 Qualifiers(), OS, LangOpts, llvm::Twine());
125 OS << "' to '";
126 QualType::print(ImplicitCast->getType().getTypePtr(), Qualifiers(), OS,
127 LangOpts, llvm::Twine());
128 OS << "')";
129 } else {
130 OS << "this context";
131 }
132
133 // Generate the extra diagnostic.
134 PathDiagnosticLocation Pos(S, BRC.getSourceManager(), N->getStackFrame());
135 return std::make_shared<PathDiagnosticEventPiece>(Pos, OS.str(), true);
136}
137
138static bool hasDefinition(const ObjCObjectPointerType *ObjPtr) {
139 const ObjCInterfaceDecl *Decl = ObjPtr->getInterfaceDecl();
140 if (!Decl)
141 return false;
142
143 return Decl->getDefinition();
144}
145
146// TODO: consider checking explicit casts?
147void DynamicTypeChecker::checkPostStmt(const ImplicitCastExpr *CE,
148 CheckerContext &C) const {
149 // TODO: C++ support.
150 if (CE->getCastKind() != CK_BitCast)
151 return;
152
153 const MemRegion *Region = C.getSVal(CE).getAsRegion();
154 if (!Region)
155 return;
156
157 ProgramStateRef State = C.getState();
158 DynamicTypeInfo DynTypeInfo = getDynamicTypeInfo(State, Region);
159
160 if (!DynTypeInfo.isValid())
161 return;
162
163 QualType DynType = DynTypeInfo.getType();
164 QualType StaticType = CE->getType();
165
166 const auto *DynObjCType = DynType->getAs<ObjCObjectPointerType>();
167 const auto *StaticObjCType = StaticType->getAs<ObjCObjectPointerType>();
168
169 if (!DynObjCType || !StaticObjCType)
170 return;
171
172 if (!hasDefinition(DynObjCType) || !hasDefinition(StaticObjCType))
173 return;
174
175 ASTContext &ASTCtxt = C.getASTContext();
176
177 // Strip kindeofness to correctly detect subtyping relationships.
178 DynObjCType = DynObjCType->stripObjCKindOfTypeAndQuals(ASTCtxt);
179 StaticObjCType = StaticObjCType->stripObjCKindOfTypeAndQuals(ASTCtxt);
180
181 // Specialized objects are handled by the generics checker.
182 if (StaticObjCType->isSpecialized())
183 return;
184
185 if (ASTCtxt.canAssignObjCInterfaces(StaticObjCType, DynObjCType))
186 return;
187
188 if (DynTypeInfo.canBeASubClass() &&
189 ASTCtxt.canAssignObjCInterfaces(DynObjCType, StaticObjCType))
190 return;
191
192 reportTypeError(DynType, StaticType, Region, CE, C);
193}
194
195void ento::registerDynamicTypeChecker(CheckerManager &mgr) {
196 mgr.registerChecker<DynamicTypeChecker>();
197}
198
199bool ento::shouldRegisterDynamicTypeChecker(const CheckerManager &mgr) {
200 return true;
201}
static bool hasDefinition(const ObjCObjectPointerType *ObjPtr)
#define X(type, name)
Definition Value.h:97
bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT)
canAssignObjCInterfaces - Return true if the two interface types are compatible for assignment from R...
const LangOptions & getLangOpts() const
CastKind getCastKind() const
Definition Expr.h:3789
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
QualType getType() const
Definition Expr.h:146
Represents an ObjC class declaration.
Definition DeclObjC.h:1160
Represents a pointer to an Objective C object.
Definition TypeBase.h:8219
bool isSpecialized() const
Whether this type is specialized, meaning that it has type arguments.
Definition TypeBase.h:8308
const ObjCObjectPointerType * stripObjCKindOfTypeAndQuals(const ASTContext &ctx) const
Strip off the Objective-C "kindof" type and (with it) any protocol qualifiers.
Definition Type.cpp:1091
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface.
Definition TypeBase.h:8271
A (possibly-)qualified type.
Definition TypeBase.h:938
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8578
void print(raw_ostream &OS, const PrintingPolicy &Policy, const Twine &PlaceHolder=Twine(), unsigned Indentation=0) const
Stmt - This represents one statement.
Definition Stmt.h:85
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9431
ASTContext & getASTContext() const
const SourceManager & getSourceManager() const
CHECKER * registerChecker(AT &&...Args)
Register a single-part checker (derived from Checker): construct its singleton instance,...
Simple checker classes that implement one frontend (i.e.
Definition Checker.h:565
bool canBeASubClass() const
Returns false if the type information is precise (the type 'DynTy' is the only type in the lattice),...
QualType getType() const
Returns the currently inferred upper bound on the runtime type.
bool isValid() const
Returns true if the dynamic type info is available.
const ProgramStateRef & getState() const
const Stmt * getStmtForDiagnostics() const
If the node's program point corresponds to a statement, retrieve that statement.
ExplodedNode * getFirstPred()
const StackFrame * getStackFrame() const
MemRegion - The root abstract class for all memory regions.
Definition MemRegion.h:97
IntrusiveRefCntPtr< const ProgramState > ProgramStateRef
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
DynamicTypeInfo getDynamicTypeInfo(ProgramStateRef State, const MemRegion *MR)
Get dynamic type information for the region MR.
std::shared_ptr< PathDiagnosticPiece > PathDiagnosticPieceRef
Top level wrappers for InstallAPI frontend operations.