1 //===- DynamicTypePropagation.cpp ------------------------------*- C++ -*--===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains two checkers. One helps the static analyzer core to track
11 // types, the other does type inference on Obj-C generics and report type
14 // Dynamic Type Propagation:
15 // This checker defines the rules for dynamic type gathering and propagation.
17 // Generics Checker for Objective-C:
18 // This checker tries to find type errors that the compiler is not able to catch
19 // due to the implicit conversions that were introduced for backward
22 //===----------------------------------------------------------------------===//
24 #include "ClangSACheckers.h"
25 #include "clang/AST/ParentMap.h"
26 #include "clang/AST/RecursiveASTVisitor.h"
27 #include "clang/Basic/Builtins.h"
28 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
29 #include "clang/StaticAnalyzer/Core/Checker.h"
30 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
31 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
32 #include "clang/StaticAnalyzer/Core/PathSensitive/DynamicTypeMap.h"
33 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
34 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
36 using namespace clang;
39 // ProgramState trait - The type inflation is tracked by DynamicTypeMap. This is
40 // an auxiliary map that tracks more information about generic types, because in
41 // some cases the most derived type is not the most informative one about the
42 // type parameters. This types that are stored for each symbol in this map must
44 // TODO: In some case the type stored in this map is exactly the same that is
45 // stored in DynamicTypeMap. We should no store duplicated information in those
47 REGISTER_MAP_WITH_PROGRAMSTATE(MostSpecializedTypeArgsMap, SymbolRef,
48 const ObjCObjectPointerType *)
51 class DynamicTypePropagation:
52 public Checker< check::PreCall,
55 check::PostStmt<CastExpr>,
56 check::PostStmt<CXXNewExpr>,
57 check::PreObjCMessage,
58 check::PostObjCMessage > {
59 const ObjCObjectType *getObjectTypeForAllocAndNew(const ObjCMessageExpr *MsgE,
60 CheckerContext &C) const;
62 /// \brief Return a better dynamic type if one can be derived from the cast.
63 const ObjCObjectPointerType *getBetterObjCType(const Expr *CastE,
64 CheckerContext &C) const;
66 ExplodedNode *dynamicTypePropagationOnCasts(const CastExpr *CE,
67 ProgramStateRef &State,
68 CheckerContext &C) const;
70 mutable std::unique_ptr<BugType> ObjCGenericsBugType;
71 void initBugType() const {
72 if (!ObjCGenericsBugType)
73 ObjCGenericsBugType.reset(
74 new BugType(this, "Generics", categories::CoreFoundationObjectiveC));
77 class GenericsBugVisitor : public BugReporterVisitorImpl<GenericsBugVisitor> {
79 GenericsBugVisitor(SymbolRef S) : Sym(S) {}
81 void Profile(llvm::FoldingSetNodeID &ID) const override {
87 std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *N,
88 const ExplodedNode *PrevN,
89 BugReporterContext &BRC,
90 BugReport &BR) override;
93 // The tracked symbol.
97 void reportGenericsBug(const ObjCObjectPointerType *From,
98 const ObjCObjectPointerType *To, ExplodedNode *N,
99 SymbolRef Sym, CheckerContext &C,
100 const Stmt *ReportedNode = nullptr) const;
103 void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
104 void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
105 void checkPostStmt(const CastExpr *CastE, CheckerContext &C) const;
106 void checkPostStmt(const CXXNewExpr *NewE, CheckerContext &C) const;
107 void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const;
108 void checkPreObjCMessage(const ObjCMethodCall &M, CheckerContext &C) const;
109 void checkPostObjCMessage(const ObjCMethodCall &M, CheckerContext &C) const;
111 /// This value is set to true, when the Generics checker is turned on.
112 DefaultBool CheckGenerics;
114 } // end anonymous namespace
116 void DynamicTypePropagation::checkDeadSymbols(SymbolReaper &SR,
117 CheckerContext &C) const {
118 ProgramStateRef State = C.getState();
119 DynamicTypeMapImpl TypeMap = State->get<DynamicTypeMap>();
120 for (DynamicTypeMapImpl::iterator I = TypeMap.begin(), E = TypeMap.end();
122 if (!SR.isLiveRegion(I->first)) {
123 State = State->remove<DynamicTypeMap>(I->first);
127 if (!SR.hasDeadSymbols()) {
128 C.addTransition(State);
132 MostSpecializedTypeArgsMapTy TyArgMap =
133 State->get<MostSpecializedTypeArgsMap>();
134 for (MostSpecializedTypeArgsMapTy::iterator I = TyArgMap.begin(),
137 if (SR.isDead(I->first)) {
138 State = State->remove<MostSpecializedTypeArgsMap>(I->first);
142 C.addTransition(State);
145 static void recordFixedType(const MemRegion *Region, const CXXMethodDecl *MD,
150 ASTContext &Ctx = C.getASTContext();
151 QualType Ty = Ctx.getPointerType(Ctx.getRecordType(MD->getParent()));
153 ProgramStateRef State = C.getState();
154 State = setDynamicTypeInfo(State, Region, Ty, /*CanBeSubclass=*/false);
155 C.addTransition(State);
158 void DynamicTypePropagation::checkPreCall(const CallEvent &Call,
159 CheckerContext &C) const {
160 if (const CXXConstructorCall *Ctor = dyn_cast<CXXConstructorCall>(&Call)) {
161 // C++11 [class.cdtor]p4: When a virtual function is called directly or
162 // indirectly from a constructor or from a destructor, including during
163 // the construction or destruction of the class's non-static data members,
164 // and the object to which the call applies is the object under
165 // construction or destruction, the function called is the final overrider
166 // in the constructor's or destructor's class and not one overriding it in
167 // a more-derived class.
169 switch (Ctor->getOriginExpr()->getConstructionKind()) {
170 case CXXConstructExpr::CK_Complete:
171 case CXXConstructExpr::CK_Delegating:
172 // No additional type info necessary.
174 case CXXConstructExpr::CK_NonVirtualBase:
175 case CXXConstructExpr::CK_VirtualBase:
176 if (const MemRegion *Target = Ctor->getCXXThisVal().getAsRegion())
177 recordFixedType(Target, Ctor->getDecl(), C);
184 if (const CXXDestructorCall *Dtor = dyn_cast<CXXDestructorCall>(&Call)) {
185 // C++11 [class.cdtor]p4 (see above)
186 if (!Dtor->isBaseDestructor())
189 const MemRegion *Target = Dtor->getCXXThisVal().getAsRegion();
193 const Decl *D = Dtor->getDecl();
197 recordFixedType(Target, cast<CXXDestructorDecl>(D), C);
202 void DynamicTypePropagation::checkPostCall(const CallEvent &Call,
203 CheckerContext &C) const {
204 // We can obtain perfect type info for return values from some calls.
205 if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(&Call)) {
207 // Get the returned value if it's a region.
208 const MemRegion *RetReg = Call.getReturnValue().getAsRegion();
212 ProgramStateRef State = C.getState();
213 const ObjCMethodDecl *D = Msg->getDecl();
215 if (D && D->hasRelatedResultType()) {
216 switch (Msg->getMethodFamily()) {
220 // We assume that the type of the object returned by alloc and new are the
221 // pointer to the object of the class specified in the receiver of the
225 // Get the type of object that will get created.
226 const ObjCMessageExpr *MsgE = Msg->getOriginExpr();
227 const ObjCObjectType *ObjTy = getObjectTypeForAllocAndNew(MsgE, C);
231 C.getASTContext().getObjCObjectPointerType(QualType(ObjTy, 0));
232 C.addTransition(setDynamicTypeInfo(State, RetReg, DynResTy, false));
236 // Assume, the result of the init method has the same dynamic type as
237 // the receiver and propagate the dynamic type info.
238 const MemRegion *RecReg = Msg->getReceiverSVal().getAsRegion();
241 DynamicTypeInfo RecDynType = getDynamicTypeInfo(State, RecReg);
242 C.addTransition(setDynamicTypeInfo(State, RetReg, RecDynType));
250 if (const CXXConstructorCall *Ctor = dyn_cast<CXXConstructorCall>(&Call)) {
251 // We may need to undo the effects of our pre-call check.
252 switch (Ctor->getOriginExpr()->getConstructionKind()) {
253 case CXXConstructExpr::CK_Complete:
254 case CXXConstructExpr::CK_Delegating:
255 // No additional work necessary.
256 // Note: This will leave behind the actual type of the object for
257 // complete constructors, but arguably that's a good thing, since it
258 // means the dynamic type info will be correct even for objects
259 // constructed with operator new.
261 case CXXConstructExpr::CK_NonVirtualBase:
262 case CXXConstructExpr::CK_VirtualBase:
263 if (const MemRegion *Target = Ctor->getCXXThisVal().getAsRegion()) {
264 // We just finished a base constructor. Now we can use the subclass's
265 // type when resolving virtual calls.
266 const LocationContext *LCtx = C.getLocationContext();
268 // FIXME: In C++17 classes with non-virtual bases may be treated as
269 // aggregates, and in such case no top-frame constructor will be called.
270 // Figure out if we need to do anything in this case.
271 // FIXME: Instead of relying on the ParentMap, we should have the
272 // trigger-statement (InitListExpr in this case) available in this
273 // callback, ideally as part of CallEvent.
274 if (dyn_cast_or_null<InitListExpr>(
275 LCtx->getParentMap().getParent(Ctor->getOriginExpr())))
278 recordFixedType(Target, cast<CXXConstructorDecl>(LCtx->getDecl()), C);
285 /// TODO: Handle explicit casts.
286 /// Handle C++ casts.
288 /// Precondition: the cast is between ObjCObjectPointers.
289 ExplodedNode *DynamicTypePropagation::dynamicTypePropagationOnCasts(
290 const CastExpr *CE, ProgramStateRef &State, CheckerContext &C) const {
291 // We only track type info for regions.
292 const MemRegion *ToR = C.getSVal(CE).getAsRegion();
294 return C.getPredecessor();
296 if (isa<ExplicitCastExpr>(CE))
297 return C.getPredecessor();
299 if (const Type *NewTy = getBetterObjCType(CE, C)) {
300 State = setDynamicTypeInfo(State, ToR, QualType(NewTy, 0));
301 return C.addTransition(State);
303 return C.getPredecessor();
306 void DynamicTypePropagation::checkPostStmt(const CXXNewExpr *NewE,
307 CheckerContext &C) const {
311 // We only track dynamic type info for regions.
312 const MemRegion *MR = C.getSVal(NewE).getAsRegion();
316 C.addTransition(setDynamicTypeInfo(C.getState(), MR, NewE->getType(),
317 /*CanBeSubclass=*/false));
320 const ObjCObjectType *
321 DynamicTypePropagation::getObjectTypeForAllocAndNew(const ObjCMessageExpr *MsgE,
322 CheckerContext &C) const {
323 if (MsgE->getReceiverKind() == ObjCMessageExpr::Class) {
324 if (const ObjCObjectType *ObjTy
325 = MsgE->getClassReceiver()->getAs<ObjCObjectType>())
329 if (MsgE->getReceiverKind() == ObjCMessageExpr::SuperClass) {
330 if (const ObjCObjectType *ObjTy
331 = MsgE->getSuperType()->getAs<ObjCObjectType>())
335 const Expr *RecE = MsgE->getInstanceReceiver();
339 RecE= RecE->IgnoreParenImpCasts();
340 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(RecE)) {
341 const StackFrameContext *SFCtx = C.getStackFrame();
342 // Are we calling [self alloc]? If this is self, get the type of the
343 // enclosing ObjC class.
344 if (DRE->getDecl() == SFCtx->getSelfDecl()) {
345 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(SFCtx->getDecl()))
346 if (const ObjCObjectType *ObjTy =
347 dyn_cast<ObjCObjectType>(MD->getClassInterface()->getTypeForDecl()))
354 // Return a better dynamic type if one can be derived from the cast.
355 // Compare the current dynamic type of the region and the new type to which we
356 // are casting. If the new type is lower in the inheritance hierarchy, pick it.
357 const ObjCObjectPointerType *
358 DynamicTypePropagation::getBetterObjCType(const Expr *CastE,
359 CheckerContext &C) const {
360 const MemRegion *ToR = C.getSVal(CastE).getAsRegion();
363 // Get the old and new types.
364 const ObjCObjectPointerType *NewTy =
365 CastE->getType()->getAs<ObjCObjectPointerType>();
368 QualType OldDTy = getDynamicTypeInfo(C.getState(), ToR).getType();
369 if (OldDTy.isNull()) {
372 const ObjCObjectPointerType *OldTy =
373 OldDTy->getAs<ObjCObjectPointerType>();
377 // Id the old type is 'id', the new one is more precise.
378 if (OldTy->isObjCIdType() && !NewTy->isObjCIdType())
381 // Return new if it's a subclass of old.
382 const ObjCInterfaceDecl *ToI = NewTy->getInterfaceDecl();
383 const ObjCInterfaceDecl *FromI = OldTy->getInterfaceDecl();
384 if (ToI && FromI && FromI->isSuperClassOf(ToI))
390 static const ObjCObjectPointerType *getMostInformativeDerivedClassImpl(
391 const ObjCObjectPointerType *From, const ObjCObjectPointerType *To,
392 const ObjCObjectPointerType *MostInformativeCandidate, ASTContext &C) {
393 // Checking if from and to are the same classes modulo specialization.
394 if (From->getInterfaceDecl()->getCanonicalDecl() ==
395 To->getInterfaceDecl()->getCanonicalDecl()) {
396 if (To->isSpecialized()) {
397 assert(MostInformativeCandidate->isSpecialized());
398 return MostInformativeCandidate;
403 if (To->getObjectType()->getSuperClassType().isNull()) {
404 // If To has no super class and From and To aren't the same then
405 // To was not actually a descendent of From. In this case the best we can
410 const auto *SuperOfTo =
411 To->getObjectType()->getSuperClassType()->getAs<ObjCObjectType>();
413 QualType SuperPtrOfToQual =
414 C.getObjCObjectPointerType(QualType(SuperOfTo, 0));
415 const auto *SuperPtrOfTo = SuperPtrOfToQual->getAs<ObjCObjectPointerType>();
416 if (To->isUnspecialized())
417 return getMostInformativeDerivedClassImpl(From, SuperPtrOfTo, SuperPtrOfTo,
420 return getMostInformativeDerivedClassImpl(From, SuperPtrOfTo,
421 MostInformativeCandidate, C);
424 /// A downcast may loose specialization information. E. g.:
425 /// MutableMap<T, U> : Map
426 /// The downcast to MutableMap looses the information about the types of the
427 /// Map (due to the type parameters are not being forwarded to Map), and in
428 /// general there is no way to recover that information from the
429 /// declaration. In order to have to most information, lets find the most
430 /// derived type that has all the type parameters forwarded.
432 /// Get the a subclass of \p From (which has a lower bound \p To) that do not
433 /// loose information about type parameters. \p To has to be a subclass of
434 /// \p From. From has to be specialized.
435 static const ObjCObjectPointerType *
436 getMostInformativeDerivedClass(const ObjCObjectPointerType *From,
437 const ObjCObjectPointerType *To, ASTContext &C) {
438 return getMostInformativeDerivedClassImpl(From, To, To, C);
442 /// \param StaticLowerBound Static lower bound for a symbol. The dynamic lower
443 /// bound might be the subclass of this type.
444 /// \param StaticUpperBound A static upper bound for a symbol.
445 /// \p StaticLowerBound expected to be the subclass of \p StaticUpperBound.
446 /// \param Current The type that was inferred for a symbol in a previous
447 /// context. Might be null when this is the first time that inference happens.
449 /// \p StaticLowerBound or \p StaticUpperBound is specialized. If \p Current
450 /// is not null, it is specialized.
452 /// (1) The \p Current is null and \p StaticLowerBound <: \p StaticUpperBound
453 /// (2) \p StaticLowerBound <: \p Current <: \p StaticUpperBound
454 /// (3) \p Current <: \p StaticLowerBound <: \p StaticUpperBound
455 /// (4) \p StaticLowerBound <: \p StaticUpperBound <: \p Current
457 /// Use getMostInformativeDerivedClass with the upper and lower bound of the
458 /// set {\p StaticLowerBound, \p Current, \p StaticUpperBound}. The computed
459 /// lower bound must be specialized. If the result differs from \p Current or
460 /// \p Current is null, store the result.
462 storeWhenMoreInformative(ProgramStateRef &State, SymbolRef Sym,
463 const ObjCObjectPointerType *const *Current,
464 const ObjCObjectPointerType *StaticLowerBound,
465 const ObjCObjectPointerType *StaticUpperBound,
467 // TODO: The above 4 cases are not exhaustive. In particular, it is possible
468 // for Current to be incomparable with StaticLowerBound, StaticUpperBound,
471 // For example, suppose Foo<T> and Bar<T> are unrelated types.
478 // id t2 = f; // StaticLowerBound is Foo<T>, Current is Bar<T>
480 // We should either constrain the callers of this function so that the stated
481 // preconditions hold (and assert it) or rewrite the function to expicitly
482 // handle the additional cases.
485 assert(StaticUpperBound->isSpecialized() ||
486 StaticLowerBound->isSpecialized());
487 assert(!Current || (*Current)->isSpecialized());
491 if (StaticUpperBound->isUnspecialized()) {
492 State = State->set<MostSpecializedTypeArgsMap>(Sym, StaticLowerBound);
495 // Upper bound is specialized.
496 const ObjCObjectPointerType *WithMostInfo =
497 getMostInformativeDerivedClass(StaticUpperBound, StaticLowerBound, C);
498 State = State->set<MostSpecializedTypeArgsMap>(Sym, WithMostInfo);
503 if (C.canAssignObjCInterfaces(StaticLowerBound, *Current)) {
508 if (C.canAssignObjCInterfaces(*Current, StaticUpperBound)) {
509 // The type arguments might not be forwarded at any point of inheritance.
510 const ObjCObjectPointerType *WithMostInfo =
511 getMostInformativeDerivedClass(*Current, StaticUpperBound, C);
513 getMostInformativeDerivedClass(WithMostInfo, StaticLowerBound, C);
514 if (WithMostInfo == *Current)
516 State = State->set<MostSpecializedTypeArgsMap>(Sym, WithMostInfo);
521 const ObjCObjectPointerType *WithMostInfo =
522 getMostInformativeDerivedClass(*Current, StaticLowerBound, C);
523 if (WithMostInfo != *Current) {
524 State = State->set<MostSpecializedTypeArgsMap>(Sym, WithMostInfo);
531 /// Type inference based on static type information that is available for the
532 /// cast and the tracked type information for the given symbol. When the tracked
533 /// symbol and the destination type of the cast are unrelated, report an error.
534 void DynamicTypePropagation::checkPostStmt(const CastExpr *CE,
535 CheckerContext &C) const {
536 if (CE->getCastKind() != CK_BitCast)
539 QualType OriginType = CE->getSubExpr()->getType();
540 QualType DestType = CE->getType();
542 const auto *OrigObjectPtrType = OriginType->getAs<ObjCObjectPointerType>();
543 const auto *DestObjectPtrType = DestType->getAs<ObjCObjectPointerType>();
545 if (!OrigObjectPtrType || !DestObjectPtrType)
548 ProgramStateRef State = C.getState();
549 ExplodedNode *AfterTypeProp = dynamicTypePropagationOnCasts(CE, State, C);
551 ASTContext &ASTCtxt = C.getASTContext();
553 // This checker detects the subtyping relationships using the assignment
554 // rules. In order to be able to do this the kindofness must be stripped
555 // first. The checker treats every type as kindof type anyways: when the
556 // tracked type is the subtype of the static type it tries to look up the
557 // methods in the tracked type first.
558 OrigObjectPtrType = OrigObjectPtrType->stripObjCKindOfTypeAndQuals(ASTCtxt);
559 DestObjectPtrType = DestObjectPtrType->stripObjCKindOfTypeAndQuals(ASTCtxt);
561 if (OrigObjectPtrType->isUnspecialized() &&
562 DestObjectPtrType->isUnspecialized())
565 SymbolRef Sym = State->getSVal(CE, C.getLocationContext()).getAsSymbol();
569 const ObjCObjectPointerType *const *TrackedType =
570 State->get<MostSpecializedTypeArgsMap>(Sym);
572 if (isa<ExplicitCastExpr>(CE)) {
573 // Treat explicit casts as an indication from the programmer that the
574 // Objective-C type system is not rich enough to express the needed
575 // invariant. In such cases, forget any existing information inferred
576 // about the type arguments. We don't assume the casted-to specialized
577 // type here because the invariant the programmer specifies in the cast
578 // may only hold at this particular program point and not later ones.
579 // We don't want a suppressing cast to require a cascade of casts down the
582 State = State->remove<MostSpecializedTypeArgsMap>(Sym);
583 C.addTransition(State, AfterTypeProp);
588 // Check which assignments are legal.
590 ASTCtxt.canAssignObjCInterfaces(DestObjectPtrType, OrigObjectPtrType);
592 ASTCtxt.canAssignObjCInterfaces(OrigObjectPtrType, DestObjectPtrType);
594 // The tracked type should be the sub or super class of the static destination
595 // type. When an (implicit) upcast or a downcast happens according to static
596 // types, and there is no subtyping relationship between the tracked and the
597 // static destination types, it indicates an error.
599 !ASTCtxt.canAssignObjCInterfaces(DestObjectPtrType, *TrackedType) &&
600 !ASTCtxt.canAssignObjCInterfaces(*TrackedType, DestObjectPtrType)) {
601 static CheckerProgramPointTag IllegalConv(this, "IllegalConversion");
602 ExplodedNode *N = C.addTransition(State, AfterTypeProp, &IllegalConv);
603 reportGenericsBug(*TrackedType, DestObjectPtrType, N, Sym, C);
607 // Handle downcasts and upcasts.
609 const ObjCObjectPointerType *LowerBound = DestObjectPtrType;
610 const ObjCObjectPointerType *UpperBound = OrigObjectPtrType;
611 if (OrigToDest && !DestToOrig)
612 std::swap(LowerBound, UpperBound);
614 // The id type is not a real bound. Eliminate it.
615 LowerBound = LowerBound->isObjCIdType() ? UpperBound : LowerBound;
616 UpperBound = UpperBound->isObjCIdType() ? LowerBound : UpperBound;
618 if (storeWhenMoreInformative(State, Sym, TrackedType, LowerBound, UpperBound,
620 C.addTransition(State, AfterTypeProp);
624 static const Expr *stripCastsAndSugar(const Expr *E) {
625 E = E->IgnoreParenImpCasts();
626 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
627 E = POE->getSyntacticForm()->IgnoreParenImpCasts();
628 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
629 E = OVE->getSourceExpr()->IgnoreParenImpCasts();
633 static bool isObjCTypeParamDependent(QualType Type) {
634 // It is illegal to typedef parameterized types inside an interface. Therfore
635 // an Objective-C type can only be dependent on a type parameter when the type
636 // parameter structurally present in the type itself.
637 class IsObjCTypeParamDependentTypeVisitor
638 : public RecursiveASTVisitor<IsObjCTypeParamDependentTypeVisitor> {
640 IsObjCTypeParamDependentTypeVisitor() : Result(false) {}
641 bool VisitObjCTypeParamType(const ObjCTypeParamType *Type) {
642 if (isa<ObjCTypeParamDecl>(Type->getDecl())) {
652 IsObjCTypeParamDependentTypeVisitor Visitor;
653 Visitor.TraverseType(Type);
654 return Visitor.Result;
657 /// A method might not be available in the interface indicated by the static
658 /// type. However it might be available in the tracked type. In order to
659 /// properly substitute the type parameters we need the declaration context of
660 /// the method. The more specialized the enclosing class of the method is, the
661 /// more likely that the parameter substitution will be successful.
662 static const ObjCMethodDecl *
663 findMethodDecl(const ObjCMessageExpr *MessageExpr,
664 const ObjCObjectPointerType *TrackedType, ASTContext &ASTCtxt) {
665 const ObjCMethodDecl *Method = nullptr;
667 QualType ReceiverType = MessageExpr->getReceiverType();
668 const auto *ReceiverObjectPtrType =
669 ReceiverType->getAs<ObjCObjectPointerType>();
671 // Do this "devirtualization" on instance and class methods only. Trust the
672 // static type on super and super class calls.
673 if (MessageExpr->getReceiverKind() == ObjCMessageExpr::Instance ||
674 MessageExpr->getReceiverKind() == ObjCMessageExpr::Class) {
675 // When the receiver type is id, Class, or some super class of the tracked
676 // type, look up the method in the tracked type, not in the receiver type.
677 // This way we preserve more information.
678 if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType() ||
679 ASTCtxt.canAssignObjCInterfaces(ReceiverObjectPtrType, TrackedType)) {
680 const ObjCInterfaceDecl *InterfaceDecl = TrackedType->getInterfaceDecl();
681 // The method might not be found.
682 Selector Sel = MessageExpr->getSelector();
683 Method = InterfaceDecl->lookupInstanceMethod(Sel);
685 Method = InterfaceDecl->lookupClassMethod(Sel);
689 // Fallback to statick method lookup when the one based on the tracked type
691 return Method ? Method : MessageExpr->getMethodDecl();
694 /// Get the returned ObjCObjectPointerType by a method based on the tracked type
695 /// information, or null pointer when the returned type is not an
696 /// ObjCObjectPointerType.
697 static QualType getReturnTypeForMethod(
698 const ObjCMethodDecl *Method, ArrayRef<QualType> TypeArgs,
699 const ObjCObjectPointerType *SelfType, ASTContext &C) {
700 QualType StaticResultType = Method->getReturnType();
702 // Is the return type declared as instance type?
703 if (StaticResultType == C.getObjCInstanceType())
704 return QualType(SelfType, 0);
706 // Check whether the result type depends on a type parameter.
707 if (!isObjCTypeParamDependent(StaticResultType))
710 QualType ResultType = StaticResultType.substObjCTypeArgs(
711 C, TypeArgs, ObjCSubstitutionContext::Result);
716 /// When the receiver has a tracked type, use that type to validate the
717 /// argumments of the message expression and the return value.
718 void DynamicTypePropagation::checkPreObjCMessage(const ObjCMethodCall &M,
719 CheckerContext &C) const {
720 ProgramStateRef State = C.getState();
721 SymbolRef Sym = M.getReceiverSVal().getAsSymbol();
725 const ObjCObjectPointerType *const *TrackedType =
726 State->get<MostSpecializedTypeArgsMap>(Sym);
730 // Get the type arguments from tracked type and substitute type arguments
731 // before do the semantic check.
733 ASTContext &ASTCtxt = C.getASTContext();
734 const ObjCMessageExpr *MessageExpr = M.getOriginExpr();
735 const ObjCMethodDecl *Method =
736 findMethodDecl(MessageExpr, *TrackedType, ASTCtxt);
738 // It is possible to call non-existent methods in Obj-C.
742 // If the method is declared on a class that has a non-invariant
743 // type parameter, don't warn about parameter mismatches after performing
744 // substitution. This prevents warning when the programmer has purposely
745 // casted the receiver to a super type or unspecialized type but the analyzer
746 // has a more precise tracked type than the programmer intends at the call
749 // For example, consider NSArray (which has a covariant type parameter)
750 // and NSMutableArray (a subclass of NSArray where the type parameter is
752 // NSMutableArray *a = [[NSMutableArray<NSString *> alloc] init;
754 // [a containsObject:number]; // Safe: -containsObject is defined on NSArray.
755 // NSArray<NSObject *> *other = [a arrayByAddingObject:number] // Safe
757 // [a addObject:number] // Unsafe: -addObject: is defined on NSMutableArray
760 const ObjCInterfaceDecl *Interface = Method->getClassInterface();
764 ObjCTypeParamList *TypeParams = Interface->getTypeParamList();
768 for (ObjCTypeParamDecl *TypeParam : *TypeParams) {
769 if (TypeParam->getVariance() != ObjCTypeParamVariance::Invariant)
773 Optional<ArrayRef<QualType>> TypeArgs =
774 (*TrackedType)->getObjCSubstitutions(Method->getDeclContext());
775 // This case might happen when there is an unspecialized override of a
776 // specialized method.
780 for (unsigned i = 0; i < Method->param_size(); i++) {
781 const Expr *Arg = MessageExpr->getArg(i);
782 const ParmVarDecl *Param = Method->parameters()[i];
784 QualType OrigParamType = Param->getType();
785 if (!isObjCTypeParamDependent(OrigParamType))
788 QualType ParamType = OrigParamType.substObjCTypeArgs(
789 ASTCtxt, *TypeArgs, ObjCSubstitutionContext::Parameter);
790 // Check if it can be assigned
791 const auto *ParamObjectPtrType = ParamType->getAs<ObjCObjectPointerType>();
792 const auto *ArgObjectPtrType =
793 stripCastsAndSugar(Arg)->getType()->getAs<ObjCObjectPointerType>();
794 if (!ParamObjectPtrType || !ArgObjectPtrType)
797 // Check if we have more concrete tracked type that is not a super type of
798 // the static argument type.
799 SVal ArgSVal = M.getArgSVal(i);
800 SymbolRef ArgSym = ArgSVal.getAsSymbol();
802 const ObjCObjectPointerType *const *TrackedArgType =
803 State->get<MostSpecializedTypeArgsMap>(ArgSym);
804 if (TrackedArgType &&
805 ASTCtxt.canAssignObjCInterfaces(ArgObjectPtrType, *TrackedArgType)) {
806 ArgObjectPtrType = *TrackedArgType;
810 // Warn when argument is incompatible with the parameter.
811 if (!ASTCtxt.canAssignObjCInterfaces(ParamObjectPtrType,
813 static CheckerProgramPointTag Tag(this, "ArgTypeMismatch");
814 ExplodedNode *N = C.addTransition(State, &Tag);
815 reportGenericsBug(ArgObjectPtrType, ParamObjectPtrType, N, Sym, C, Arg);
821 /// This callback is used to infer the types for Class variables. This info is
822 /// used later to validate messages that sent to classes. Class variables are
823 /// initialized with by invoking the 'class' method on a class.
824 /// This method is also used to infer the type information for the return
826 // TODO: right now it only tracks generic types. Extend this to track every
827 // type in the DynamicTypeMap and diagnose type errors!
828 void DynamicTypePropagation::checkPostObjCMessage(const ObjCMethodCall &M,
829 CheckerContext &C) const {
830 const ObjCMessageExpr *MessageExpr = M.getOriginExpr();
832 SymbolRef RetSym = M.getReturnValue().getAsSymbol();
836 Selector Sel = MessageExpr->getSelector();
837 ProgramStateRef State = C.getState();
838 // Inference for class variables.
839 // We are only interested in cases where the class method is invoked on a
840 // class. This method is provided by the runtime and available on all classes.
841 if (MessageExpr->getReceiverKind() == ObjCMessageExpr::Class &&
842 Sel.getAsString() == "class") {
843 QualType ReceiverType = MessageExpr->getClassReceiver();
844 const auto *ReceiverClassType = ReceiverType->getAs<ObjCObjectType>();
845 QualType ReceiverClassPointerType =
846 C.getASTContext().getObjCObjectPointerType(
847 QualType(ReceiverClassType, 0));
849 if (!ReceiverClassType->isSpecialized())
851 const auto *InferredType =
852 ReceiverClassPointerType->getAs<ObjCObjectPointerType>();
853 assert(InferredType);
855 State = State->set<MostSpecializedTypeArgsMap>(RetSym, InferredType);
856 C.addTransition(State);
860 // Tracking for return types.
861 SymbolRef RecSym = M.getReceiverSVal().getAsSymbol();
865 const ObjCObjectPointerType *const *TrackedType =
866 State->get<MostSpecializedTypeArgsMap>(RecSym);
870 ASTContext &ASTCtxt = C.getASTContext();
871 const ObjCMethodDecl *Method =
872 findMethodDecl(MessageExpr, *TrackedType, ASTCtxt);
876 Optional<ArrayRef<QualType>> TypeArgs =
877 (*TrackedType)->getObjCSubstitutions(Method->getDeclContext());
881 QualType ResultType =
882 getReturnTypeForMethod(Method, *TypeArgs, *TrackedType, ASTCtxt);
883 // The static type is the same as the deduced type.
884 if (ResultType.isNull())
887 const MemRegion *RetRegion = M.getReturnValue().getAsRegion();
888 ExplodedNode *Pred = C.getPredecessor();
889 // When there is an entry available for the return symbol in DynamicTypeMap,
890 // the call was inlined, and the information in the DynamicTypeMap is should
892 if (RetRegion && !State->get<DynamicTypeMap>(RetRegion)) {
893 // TODO: we have duplicated information in DynamicTypeMap and
894 // MostSpecializedTypeArgsMap. We should only store anything in the later if
895 // the stored data differs from the one stored in the former.
896 State = setDynamicTypeInfo(State, RetRegion, ResultType,
897 /*CanBeSubclass=*/true);
898 Pred = C.addTransition(State);
901 const auto *ResultPtrType = ResultType->getAs<ObjCObjectPointerType>();
903 if (!ResultPtrType || ResultPtrType->isUnspecialized())
906 // When the result is a specialized type and it is not tracked yet, track it
907 // for the result symbol.
908 if (!State->get<MostSpecializedTypeArgsMap>(RetSym)) {
909 State = State->set<MostSpecializedTypeArgsMap>(RetSym, ResultPtrType);
910 C.addTransition(State, Pred);
914 void DynamicTypePropagation::reportGenericsBug(
915 const ObjCObjectPointerType *From, const ObjCObjectPointerType *To,
916 ExplodedNode *N, SymbolRef Sym, CheckerContext &C,
917 const Stmt *ReportedNode) const {
922 SmallString<192> Buf;
923 llvm::raw_svector_ostream OS(Buf);
924 OS << "Conversion from value of type '";
925 QualType::print(From, Qualifiers(), OS, C.getLangOpts(), llvm::Twine());
926 OS << "' to incompatible type '";
927 QualType::print(To, Qualifiers(), OS, C.getLangOpts(), llvm::Twine());
929 std::unique_ptr<BugReport> R(
930 new BugReport(*ObjCGenericsBugType, OS.str(), N));
931 R->markInteresting(Sym);
932 R->addVisitor(llvm::make_unique<GenericsBugVisitor>(Sym));
934 R->addRange(ReportedNode->getSourceRange());
935 C.emitReport(std::move(R));
938 std::shared_ptr<PathDiagnosticPiece>
939 DynamicTypePropagation::GenericsBugVisitor::VisitNode(const ExplodedNode *N,
940 const ExplodedNode *PrevN,
941 BugReporterContext &BRC,
943 ProgramStateRef state = N->getState();
944 ProgramStateRef statePrev = PrevN->getState();
946 const ObjCObjectPointerType *const *TrackedType =
947 state->get<MostSpecializedTypeArgsMap>(Sym);
948 const ObjCObjectPointerType *const *TrackedTypePrev =
949 statePrev->get<MostSpecializedTypeArgsMap>(Sym);
953 if (TrackedTypePrev && *TrackedTypePrev == *TrackedType)
956 // Retrieve the associated statement.
957 const Stmt *S = PathDiagnosticLocation::getStmt(N);
961 const LangOptions &LangOpts = BRC.getASTContext().getLangOpts();
963 SmallString<256> Buf;
964 llvm::raw_svector_ostream OS(Buf);
966 QualType::print(*TrackedType, Qualifiers(), OS, LangOpts, llvm::Twine());
967 OS << "' is inferred from ";
969 if (const auto *ExplicitCast = dyn_cast<ExplicitCastExpr>(S)) {
970 OS << "explicit cast (from '";
971 QualType::print(ExplicitCast->getSubExpr()->getType().getTypePtr(),
972 Qualifiers(), OS, LangOpts, llvm::Twine());
974 QualType::print(ExplicitCast->getType().getTypePtr(), Qualifiers(), OS,
975 LangOpts, llvm::Twine());
977 } else if (const auto *ImplicitCast = dyn_cast<ImplicitCastExpr>(S)) {
978 OS << "implicit cast (from '";
979 QualType::print(ImplicitCast->getSubExpr()->getType().getTypePtr(),
980 Qualifiers(), OS, LangOpts, llvm::Twine());
982 QualType::print(ImplicitCast->getType().getTypePtr(), Qualifiers(), OS,
983 LangOpts, llvm::Twine());
986 OS << "this context";
989 // Generate the extra diagnostic.
990 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
991 N->getLocationContext());
992 return std::make_shared<PathDiagnosticEventPiece>(Pos, OS.str(), true,
996 /// Register checkers.
997 void ento::registerObjCGenericsChecker(CheckerManager &mgr) {
998 DynamicTypePropagation *checker =
999 mgr.registerChecker<DynamicTypePropagation>();
1000 checker->CheckGenerics = true;
1003 void ento::registerDynamicTypePropagation(CheckerManager &mgr) {
1004 mgr.registerChecker<DynamicTypePropagation>();