1 //===- DynamicTypePropagation.cpp ------------------------------*- C++ -*--===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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
12 // errors.
13 //
14 // Dynamic Type Propagation:
15 // This checker defines the rules for dynamic type gathering and propagation.
16 //
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
20 // compatibility.
21 //
22 //===----------------------------------------------------------------------===//
23 
24 #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.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"
35 
36 using namespace clang;
37 using namespace ento;
38 
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
43 // be specialized.
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
46 // cases.
47 REGISTER_MAP_WITH_PROGRAMSTATE(MostSpecializedTypeArgsMap, SymbolRef,
48                                const ObjCObjectPointerType *)
49 
50 namespace {
51 class DynamicTypePropagation:
52     public Checker< check::PreCall,
53                     check::PostCall,
54                     check::DeadSymbols,
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;
61 
62   /// Return a better dynamic type if one can be derived from the cast.
63   const ObjCObjectPointerType *getBetterObjCType(const Expr *CastE,
64                                                  CheckerContext &C) const;
65 
66   ExplodedNode *dynamicTypePropagationOnCasts(const CastExpr *CE,
67                                               ProgramStateRef &State,
68                                               CheckerContext &C) const;
69 
70   mutable std::unique_ptr<BugType> ObjCGenericsBugType;
initBugType() const71   void initBugType() const {
72     if (!ObjCGenericsBugType)
73       ObjCGenericsBugType.reset(
74           new BugType(this, "Generics", categories::CoreFoundationObjectiveC));
75   }
76 
77   class GenericsBugVisitor : public BugReporterVisitor {
78   public:
GenericsBugVisitor(SymbolRef S)79     GenericsBugVisitor(SymbolRef S) : Sym(S) {}
80 
Profile(llvm::FoldingSetNodeID & ID) const81     void Profile(llvm::FoldingSetNodeID &ID) const override {
82       static int X = 0;
83       ID.AddPointer(&X);
84       ID.AddPointer(Sym);
85     }
86 
87     std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *N,
88                                                    BugReporterContext &BRC,
89                                                    BugReport &BR) override;
90 
91   private:
92     // The tracked symbol.
93     SymbolRef Sym;
94   };
95 
96   void reportGenericsBug(const ObjCObjectPointerType *From,
97                          const ObjCObjectPointerType *To, ExplodedNode *N,
98                          SymbolRef Sym, CheckerContext &C,
99                          const Stmt *ReportedNode = nullptr) const;
100 
101 public:
102   void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
103   void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
104   void checkPostStmt(const CastExpr *CastE, CheckerContext &C) const;
105   void checkPostStmt(const CXXNewExpr *NewE, CheckerContext &C) const;
106   void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const;
107   void checkPreObjCMessage(const ObjCMethodCall &M, CheckerContext &C) const;
108   void checkPostObjCMessage(const ObjCMethodCall &M, CheckerContext &C) const;
109 
110   /// This value is set to true, when the Generics checker is turned on.
111   DefaultBool CheckGenerics;
112 };
113 } // end anonymous namespace
114 
checkDeadSymbols(SymbolReaper & SR,CheckerContext & C) const115 void DynamicTypePropagation::checkDeadSymbols(SymbolReaper &SR,
116                                               CheckerContext &C) const {
117   ProgramStateRef State = C.getState();
118   DynamicTypeMapImpl TypeMap = State->get<DynamicTypeMap>();
119   for (DynamicTypeMapImpl::iterator I = TypeMap.begin(), E = TypeMap.end();
120        I != E; ++I) {
121     if (!SR.isLiveRegion(I->first)) {
122       State = State->remove<DynamicTypeMap>(I->first);
123     }
124   }
125 
126   MostSpecializedTypeArgsMapTy TyArgMap =
127       State->get<MostSpecializedTypeArgsMap>();
128   for (MostSpecializedTypeArgsMapTy::iterator I = TyArgMap.begin(),
129                                               E = TyArgMap.end();
130        I != E; ++I) {
131     if (SR.isDead(I->first)) {
132       State = State->remove<MostSpecializedTypeArgsMap>(I->first);
133     }
134   }
135 
136   C.addTransition(State);
137 }
138 
recordFixedType(const MemRegion * Region,const CXXMethodDecl * MD,CheckerContext & C)139 static void recordFixedType(const MemRegion *Region, const CXXMethodDecl *MD,
140                             CheckerContext &C) {
141   assert(Region);
142   assert(MD);
143 
144   ASTContext &Ctx = C.getASTContext();
145   QualType Ty = Ctx.getPointerType(Ctx.getRecordType(MD->getParent()));
146 
147   ProgramStateRef State = C.getState();
148   State = setDynamicTypeInfo(State, Region, Ty, /*CanBeSubclass=*/false);
149   C.addTransition(State);
150 }
151 
checkPreCall(const CallEvent & Call,CheckerContext & C) const152 void DynamicTypePropagation::checkPreCall(const CallEvent &Call,
153                                           CheckerContext &C) const {
154   if (const CXXConstructorCall *Ctor = dyn_cast<CXXConstructorCall>(&Call)) {
155     // C++11 [class.cdtor]p4: When a virtual function is called directly or
156     //   indirectly from a constructor or from a destructor, including during
157     //   the construction or destruction of the class's non-static data members,
158     //   and the object to which the call applies is the object under
159     //   construction or destruction, the function called is the final overrider
160     //   in the constructor's or destructor's class and not one overriding it in
161     //   a more-derived class.
162 
163     switch (Ctor->getOriginExpr()->getConstructionKind()) {
164     case CXXConstructExpr::CK_Complete:
165     case CXXConstructExpr::CK_Delegating:
166       // No additional type info necessary.
167       return;
168     case CXXConstructExpr::CK_NonVirtualBase:
169     case CXXConstructExpr::CK_VirtualBase:
170       if (const MemRegion *Target = Ctor->getCXXThisVal().getAsRegion())
171         recordFixedType(Target, Ctor->getDecl(), C);
172       return;
173     }
174 
175     return;
176   }
177 
178   if (const CXXDestructorCall *Dtor = dyn_cast<CXXDestructorCall>(&Call)) {
179     // C++11 [class.cdtor]p4 (see above)
180     if (!Dtor->isBaseDestructor())
181       return;
182 
183     const MemRegion *Target = Dtor->getCXXThisVal().getAsRegion();
184     if (!Target)
185       return;
186 
187     const Decl *D = Dtor->getDecl();
188     if (!D)
189       return;
190 
191     recordFixedType(Target, cast<CXXDestructorDecl>(D), C);
192     return;
193   }
194 }
195 
checkPostCall(const CallEvent & Call,CheckerContext & C) const196 void DynamicTypePropagation::checkPostCall(const CallEvent &Call,
197                                            CheckerContext &C) const {
198   // We can obtain perfect type info for return values from some calls.
199   if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(&Call)) {
200 
201     // Get the returned value if it's a region.
202     const MemRegion *RetReg = Call.getReturnValue().getAsRegion();
203     if (!RetReg)
204       return;
205 
206     ProgramStateRef State = C.getState();
207     const ObjCMethodDecl *D = Msg->getDecl();
208 
209     if (D && D->hasRelatedResultType()) {
210       switch (Msg->getMethodFamily()) {
211       default:
212         break;
213 
214       // We assume that the type of the object returned by alloc and new are the
215       // pointer to the object of the class specified in the receiver of the
216       // message.
217       case OMF_alloc:
218       case OMF_new: {
219         // Get the type of object that will get created.
220         const ObjCMessageExpr *MsgE = Msg->getOriginExpr();
221         const ObjCObjectType *ObjTy = getObjectTypeForAllocAndNew(MsgE, C);
222         if (!ObjTy)
223           return;
224         QualType DynResTy =
225                  C.getASTContext().getObjCObjectPointerType(QualType(ObjTy, 0));
226         C.addTransition(setDynamicTypeInfo(State, RetReg, DynResTy, false));
227         break;
228       }
229       case OMF_init: {
230         // Assume, the result of the init method has the same dynamic type as
231         // the receiver and propagate the dynamic type info.
232         const MemRegion *RecReg = Msg->getReceiverSVal().getAsRegion();
233         if (!RecReg)
234           return;
235         DynamicTypeInfo RecDynType = getDynamicTypeInfo(State, RecReg);
236         C.addTransition(setDynamicTypeInfo(State, RetReg, RecDynType));
237         break;
238       }
239       }
240     }
241     return;
242   }
243 
244   if (const CXXConstructorCall *Ctor = dyn_cast<CXXConstructorCall>(&Call)) {
245     // We may need to undo the effects of our pre-call check.
246     switch (Ctor->getOriginExpr()->getConstructionKind()) {
247     case CXXConstructExpr::CK_Complete:
248     case CXXConstructExpr::CK_Delegating:
249       // No additional work necessary.
250       // Note: This will leave behind the actual type of the object for
251       // complete constructors, but arguably that's a good thing, since it
252       // means the dynamic type info will be correct even for objects
253       // constructed with operator new.
254       return;
255     case CXXConstructExpr::CK_NonVirtualBase:
256     case CXXConstructExpr::CK_VirtualBase:
257       if (const MemRegion *Target = Ctor->getCXXThisVal().getAsRegion()) {
258         // We just finished a base constructor. Now we can use the subclass's
259         // type when resolving virtual calls.
260         const LocationContext *LCtx = C.getLocationContext();
261 
262         // FIXME: In C++17 classes with non-virtual bases may be treated as
263         // aggregates, and in such case no top-frame constructor will be called.
264         // Figure out if we need to do anything in this case.
265         // FIXME: Instead of relying on the ParentMap, we should have the
266         // trigger-statement (InitListExpr in this case) available in this
267         // callback, ideally as part of CallEvent.
268         if (dyn_cast_or_null<InitListExpr>(
269                 LCtx->getParentMap().getParent(Ctor->getOriginExpr())))
270           return;
271 
272         recordFixedType(Target, cast<CXXConstructorDecl>(LCtx->getDecl()), C);
273       }
274       return;
275     }
276   }
277 }
278 
279 /// TODO: Handle explicit casts.
280 ///       Handle C++ casts.
281 ///
282 /// Precondition: the cast is between ObjCObjectPointers.
dynamicTypePropagationOnCasts(const CastExpr * CE,ProgramStateRef & State,CheckerContext & C) const283 ExplodedNode *DynamicTypePropagation::dynamicTypePropagationOnCasts(
284     const CastExpr *CE, ProgramStateRef &State, CheckerContext &C) const {
285   // We only track type info for regions.
286   const MemRegion *ToR = C.getSVal(CE).getAsRegion();
287   if (!ToR)
288     return C.getPredecessor();
289 
290   if (isa<ExplicitCastExpr>(CE))
291     return C.getPredecessor();
292 
293   if (const Type *NewTy = getBetterObjCType(CE, C)) {
294     State = setDynamicTypeInfo(State, ToR, QualType(NewTy, 0));
295     return C.addTransition(State);
296   }
297   return C.getPredecessor();
298 }
299 
checkPostStmt(const CXXNewExpr * NewE,CheckerContext & C) const300 void DynamicTypePropagation::checkPostStmt(const CXXNewExpr *NewE,
301                                            CheckerContext &C) const {
302   if (NewE->isArray())
303     return;
304 
305   // We only track dynamic type info for regions.
306   const MemRegion *MR = C.getSVal(NewE).getAsRegion();
307   if (!MR)
308     return;
309 
310   C.addTransition(setDynamicTypeInfo(C.getState(), MR, NewE->getType(),
311                                      /*CanBeSubclass=*/false));
312 }
313 
314 const ObjCObjectType *
getObjectTypeForAllocAndNew(const ObjCMessageExpr * MsgE,CheckerContext & C) const315 DynamicTypePropagation::getObjectTypeForAllocAndNew(const ObjCMessageExpr *MsgE,
316                                                     CheckerContext &C) const {
317   if (MsgE->getReceiverKind() == ObjCMessageExpr::Class) {
318     if (const ObjCObjectType *ObjTy
319           = MsgE->getClassReceiver()->getAs<ObjCObjectType>())
320     return ObjTy;
321   }
322 
323   if (MsgE->getReceiverKind() == ObjCMessageExpr::SuperClass) {
324     if (const ObjCObjectType *ObjTy
325           = MsgE->getSuperType()->getAs<ObjCObjectType>())
326       return ObjTy;
327   }
328 
329   const Expr *RecE = MsgE->getInstanceReceiver();
330   if (!RecE)
331     return nullptr;
332 
333   RecE= RecE->IgnoreParenImpCasts();
334   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(RecE)) {
335     const StackFrameContext *SFCtx = C.getStackFrame();
336     // Are we calling [self alloc]? If this is self, get the type of the
337     // enclosing ObjC class.
338     if (DRE->getDecl() == SFCtx->getSelfDecl()) {
339       if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(SFCtx->getDecl()))
340         if (const ObjCObjectType *ObjTy =
341             dyn_cast<ObjCObjectType>(MD->getClassInterface()->getTypeForDecl()))
342           return ObjTy;
343     }
344   }
345   return nullptr;
346 }
347 
348 // Return a better dynamic type if one can be derived from the cast.
349 // Compare the current dynamic type of the region and the new type to which we
350 // are casting. If the new type is lower in the inheritance hierarchy, pick it.
351 const ObjCObjectPointerType *
getBetterObjCType(const Expr * CastE,CheckerContext & C) const352 DynamicTypePropagation::getBetterObjCType(const Expr *CastE,
353                                           CheckerContext &C) const {
354   const MemRegion *ToR = C.getSVal(CastE).getAsRegion();
355   assert(ToR);
356 
357   // Get the old and new types.
358   const ObjCObjectPointerType *NewTy =
359       CastE->getType()->getAs<ObjCObjectPointerType>();
360   if (!NewTy)
361     return nullptr;
362   QualType OldDTy = getDynamicTypeInfo(C.getState(), ToR).getType();
363   if (OldDTy.isNull()) {
364     return NewTy;
365   }
366   const ObjCObjectPointerType *OldTy =
367     OldDTy->getAs<ObjCObjectPointerType>();
368   if (!OldTy)
369     return nullptr;
370 
371   // Id the old type is 'id', the new one is more precise.
372   if (OldTy->isObjCIdType() && !NewTy->isObjCIdType())
373     return NewTy;
374 
375   // Return new if it's a subclass of old.
376   const ObjCInterfaceDecl *ToI = NewTy->getInterfaceDecl();
377   const ObjCInterfaceDecl *FromI = OldTy->getInterfaceDecl();
378   if (ToI && FromI && FromI->isSuperClassOf(ToI))
379     return NewTy;
380 
381   return nullptr;
382 }
383 
getMostInformativeDerivedClassImpl(const ObjCObjectPointerType * From,const ObjCObjectPointerType * To,const ObjCObjectPointerType * MostInformativeCandidate,ASTContext & C)384 static const ObjCObjectPointerType *getMostInformativeDerivedClassImpl(
385     const ObjCObjectPointerType *From, const ObjCObjectPointerType *To,
386     const ObjCObjectPointerType *MostInformativeCandidate, ASTContext &C) {
387   // Checking if from and to are the same classes modulo specialization.
388   if (From->getInterfaceDecl()->getCanonicalDecl() ==
389       To->getInterfaceDecl()->getCanonicalDecl()) {
390     if (To->isSpecialized()) {
391       assert(MostInformativeCandidate->isSpecialized());
392       return MostInformativeCandidate;
393     }
394     return From;
395   }
396 
397   if (To->getObjectType()->getSuperClassType().isNull()) {
398     // If To has no super class and From and To aren't the same then
399     // To was not actually a descendent of From. In this case the best we can
400     // do is 'From'.
401     return From;
402   }
403 
404   const auto *SuperOfTo =
405       To->getObjectType()->getSuperClassType()->getAs<ObjCObjectType>();
406   assert(SuperOfTo);
407   QualType SuperPtrOfToQual =
408       C.getObjCObjectPointerType(QualType(SuperOfTo, 0));
409   const auto *SuperPtrOfTo = SuperPtrOfToQual->getAs<ObjCObjectPointerType>();
410   if (To->isUnspecialized())
411     return getMostInformativeDerivedClassImpl(From, SuperPtrOfTo, SuperPtrOfTo,
412                                               C);
413   else
414     return getMostInformativeDerivedClassImpl(From, SuperPtrOfTo,
415                                               MostInformativeCandidate, C);
416 }
417 
418 /// A downcast may loose specialization information. E. g.:
419 ///   MutableMap<T, U> : Map
420 /// The downcast to MutableMap looses the information about the types of the
421 /// Map (due to the type parameters are not being forwarded to Map), and in
422 /// general there is no way to recover that information from the
423 /// declaration. In order to have to most information, lets find the most
424 /// derived type that has all the type parameters forwarded.
425 ///
426 /// Get the a subclass of \p From (which has a lower bound \p To) that do not
427 /// loose information about type parameters. \p To has to be a subclass of
428 /// \p From. From has to be specialized.
429 static const ObjCObjectPointerType *
getMostInformativeDerivedClass(const ObjCObjectPointerType * From,const ObjCObjectPointerType * To,ASTContext & C)430 getMostInformativeDerivedClass(const ObjCObjectPointerType *From,
431                                const ObjCObjectPointerType *To, ASTContext &C) {
432   return getMostInformativeDerivedClassImpl(From, To, To, C);
433 }
434 
435 /// Inputs:
436 ///   \param StaticLowerBound Static lower bound for a symbol. The dynamic lower
437 ///   bound might be the subclass of this type.
438 ///   \param StaticUpperBound A static upper bound for a symbol.
439 ///   \p StaticLowerBound expected to be the subclass of \p StaticUpperBound.
440 ///   \param Current The type that was inferred for a symbol in a previous
441 ///   context. Might be null when this is the first time that inference happens.
442 /// Precondition:
443 ///   \p StaticLowerBound or \p StaticUpperBound is specialized. If \p Current
444 ///   is not null, it is specialized.
445 /// Possible cases:
446 ///   (1) The \p Current is null and \p StaticLowerBound <: \p StaticUpperBound
447 ///   (2) \p StaticLowerBound <: \p Current <: \p StaticUpperBound
448 ///   (3) \p Current <: \p StaticLowerBound <: \p StaticUpperBound
449 ///   (4) \p StaticLowerBound <: \p StaticUpperBound <: \p Current
450 /// Effect:
451 ///   Use getMostInformativeDerivedClass with the upper and lower bound of the
452 ///   set {\p StaticLowerBound, \p Current, \p StaticUpperBound}. The computed
453 ///   lower bound must be specialized. If the result differs from \p Current or
454 ///   \p Current is null, store the result.
455 static bool
storeWhenMoreInformative(ProgramStateRef & State,SymbolRef Sym,const ObjCObjectPointerType * const * Current,const ObjCObjectPointerType * StaticLowerBound,const ObjCObjectPointerType * StaticUpperBound,ASTContext & C)456 storeWhenMoreInformative(ProgramStateRef &State, SymbolRef Sym,
457                          const ObjCObjectPointerType *const *Current,
458                          const ObjCObjectPointerType *StaticLowerBound,
459                          const ObjCObjectPointerType *StaticUpperBound,
460                          ASTContext &C) {
461   // TODO: The above 4 cases are not exhaustive. In particular, it is possible
462   // for Current to be incomparable with StaticLowerBound, StaticUpperBound,
463   // or both.
464   //
465   // For example, suppose Foo<T> and Bar<T> are unrelated types.
466   //
467   //  Foo<T> *f = ...
468   //  Bar<T> *b = ...
469   //
470   //  id t1 = b;
471   //  f = t1;
472   //  id t2 = f; // StaticLowerBound is Foo<T>, Current is Bar<T>
473   //
474   // We should either constrain the callers of this function so that the stated
475   // preconditions hold (and assert it) or rewrite the function to expicitly
476   // handle the additional cases.
477 
478   // Precondition
479   assert(StaticUpperBound->isSpecialized() ||
480          StaticLowerBound->isSpecialized());
481   assert(!Current || (*Current)->isSpecialized());
482 
483   // Case (1)
484   if (!Current) {
485     if (StaticUpperBound->isUnspecialized()) {
486       State = State->set<MostSpecializedTypeArgsMap>(Sym, StaticLowerBound);
487       return true;
488     }
489     // Upper bound is specialized.
490     const ObjCObjectPointerType *WithMostInfo =
491         getMostInformativeDerivedClass(StaticUpperBound, StaticLowerBound, C);
492     State = State->set<MostSpecializedTypeArgsMap>(Sym, WithMostInfo);
493     return true;
494   }
495 
496   // Case (3)
497   if (C.canAssignObjCInterfaces(StaticLowerBound, *Current)) {
498     return false;
499   }
500 
501   // Case (4)
502   if (C.canAssignObjCInterfaces(*Current, StaticUpperBound)) {
503     // The type arguments might not be forwarded at any point of inheritance.
504     const ObjCObjectPointerType *WithMostInfo =
505         getMostInformativeDerivedClass(*Current, StaticUpperBound, C);
506     WithMostInfo =
507         getMostInformativeDerivedClass(WithMostInfo, StaticLowerBound, C);
508     if (WithMostInfo == *Current)
509       return false;
510     State = State->set<MostSpecializedTypeArgsMap>(Sym, WithMostInfo);
511     return true;
512   }
513 
514   // Case (2)
515   const ObjCObjectPointerType *WithMostInfo =
516       getMostInformativeDerivedClass(*Current, StaticLowerBound, C);
517   if (WithMostInfo != *Current) {
518     State = State->set<MostSpecializedTypeArgsMap>(Sym, WithMostInfo);
519     return true;
520   }
521 
522   return false;
523 }
524 
525 /// Type inference based on static type information that is available for the
526 /// cast and the tracked type information for the given symbol. When the tracked
527 /// symbol and the destination type of the cast are unrelated, report an error.
checkPostStmt(const CastExpr * CE,CheckerContext & C) const528 void DynamicTypePropagation::checkPostStmt(const CastExpr *CE,
529                                            CheckerContext &C) const {
530   if (CE->getCastKind() != CK_BitCast)
531     return;
532 
533   QualType OriginType = CE->getSubExpr()->getType();
534   QualType DestType = CE->getType();
535 
536   const auto *OrigObjectPtrType = OriginType->getAs<ObjCObjectPointerType>();
537   const auto *DestObjectPtrType = DestType->getAs<ObjCObjectPointerType>();
538 
539   if (!OrigObjectPtrType || !DestObjectPtrType)
540     return;
541 
542   ProgramStateRef State = C.getState();
543   ExplodedNode *AfterTypeProp = dynamicTypePropagationOnCasts(CE, State, C);
544 
545   ASTContext &ASTCtxt = C.getASTContext();
546 
547   // This checker detects the subtyping relationships using the assignment
548   // rules. In order to be able to do this the kindofness must be stripped
549   // first. The checker treats every type as kindof type anyways: when the
550   // tracked type is the subtype of the static type it tries to look up the
551   // methods in the tracked type first.
552   OrigObjectPtrType = OrigObjectPtrType->stripObjCKindOfTypeAndQuals(ASTCtxt);
553   DestObjectPtrType = DestObjectPtrType->stripObjCKindOfTypeAndQuals(ASTCtxt);
554 
555   if (OrigObjectPtrType->isUnspecialized() &&
556       DestObjectPtrType->isUnspecialized())
557     return;
558 
559   SymbolRef Sym = C.getSVal(CE).getAsSymbol();
560   if (!Sym)
561     return;
562 
563   const ObjCObjectPointerType *const *TrackedType =
564       State->get<MostSpecializedTypeArgsMap>(Sym);
565 
566   if (isa<ExplicitCastExpr>(CE)) {
567     // Treat explicit casts as an indication from the programmer that the
568     // Objective-C type system is not rich enough to express the needed
569     // invariant. In such cases, forget any existing information inferred
570     // about the type arguments. We don't assume the casted-to specialized
571     // type here because the invariant the programmer specifies in the cast
572     // may only hold at this particular program point and not later ones.
573     // We don't want a suppressing cast to require a cascade of casts down the
574     // line.
575     if (TrackedType) {
576       State = State->remove<MostSpecializedTypeArgsMap>(Sym);
577       C.addTransition(State, AfterTypeProp);
578     }
579     return;
580   }
581 
582   // Check which assignments are legal.
583   bool OrigToDest =
584       ASTCtxt.canAssignObjCInterfaces(DestObjectPtrType, OrigObjectPtrType);
585   bool DestToOrig =
586       ASTCtxt.canAssignObjCInterfaces(OrigObjectPtrType, DestObjectPtrType);
587 
588   // The tracked type should be the sub or super class of the static destination
589   // type. When an (implicit) upcast or a downcast happens according to static
590   // types, and there is no subtyping relationship between the tracked and the
591   // static destination types, it indicates an error.
592   if (TrackedType &&
593       !ASTCtxt.canAssignObjCInterfaces(DestObjectPtrType, *TrackedType) &&
594       !ASTCtxt.canAssignObjCInterfaces(*TrackedType, DestObjectPtrType)) {
595     static CheckerProgramPointTag IllegalConv(this, "IllegalConversion");
596     ExplodedNode *N = C.addTransition(State, AfterTypeProp, &IllegalConv);
597     reportGenericsBug(*TrackedType, DestObjectPtrType, N, Sym, C);
598     return;
599   }
600 
601   // Handle downcasts and upcasts.
602 
603   const ObjCObjectPointerType *LowerBound = DestObjectPtrType;
604   const ObjCObjectPointerType *UpperBound = OrigObjectPtrType;
605   if (OrigToDest && !DestToOrig)
606     std::swap(LowerBound, UpperBound);
607 
608   // The id type is not a real bound. Eliminate it.
609   LowerBound = LowerBound->isObjCIdType() ? UpperBound : LowerBound;
610   UpperBound = UpperBound->isObjCIdType() ? LowerBound : UpperBound;
611 
612   if (storeWhenMoreInformative(State, Sym, TrackedType, LowerBound, UpperBound,
613                                ASTCtxt)) {
614     C.addTransition(State, AfterTypeProp);
615   }
616 }
617 
stripCastsAndSugar(const Expr * E)618 static const Expr *stripCastsAndSugar(const Expr *E) {
619   E = E->IgnoreParenImpCasts();
620   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
621     E = POE->getSyntacticForm()->IgnoreParenImpCasts();
622   if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
623     E = OVE->getSourceExpr()->IgnoreParenImpCasts();
624   return E;
625 }
626 
isObjCTypeParamDependent(QualType Type)627 static bool isObjCTypeParamDependent(QualType Type) {
628   // It is illegal to typedef parameterized types inside an interface. Therefore
629   // an Objective-C type can only be dependent on a type parameter when the type
630   // parameter structurally present in the type itself.
631   class IsObjCTypeParamDependentTypeVisitor
632       : public RecursiveASTVisitor<IsObjCTypeParamDependentTypeVisitor> {
633   public:
634     IsObjCTypeParamDependentTypeVisitor() : Result(false) {}
635     bool VisitObjCTypeParamType(const ObjCTypeParamType *Type) {
636       if (isa<ObjCTypeParamDecl>(Type->getDecl())) {
637         Result = true;
638         return false;
639       }
640       return true;
641     }
642 
643     bool Result;
644   };
645 
646   IsObjCTypeParamDependentTypeVisitor Visitor;
647   Visitor.TraverseType(Type);
648   return Visitor.Result;
649 }
650 
651 /// A method might not be available in the interface indicated by the static
652 /// type. However it might be available in the tracked type. In order to
653 /// properly substitute the type parameters we need the declaration context of
654 /// the method. The more specialized the enclosing class of the method is, the
655 /// more likely that the parameter substitution will be successful.
656 static const ObjCMethodDecl *
findMethodDecl(const ObjCMessageExpr * MessageExpr,const ObjCObjectPointerType * TrackedType,ASTContext & ASTCtxt)657 findMethodDecl(const ObjCMessageExpr *MessageExpr,
658                const ObjCObjectPointerType *TrackedType, ASTContext &ASTCtxt) {
659   const ObjCMethodDecl *Method = nullptr;
660 
661   QualType ReceiverType = MessageExpr->getReceiverType();
662   const auto *ReceiverObjectPtrType =
663       ReceiverType->getAs<ObjCObjectPointerType>();
664 
665   // Do this "devirtualization" on instance and class methods only. Trust the
666   // static type on super and super class calls.
667   if (MessageExpr->getReceiverKind() == ObjCMessageExpr::Instance ||
668       MessageExpr->getReceiverKind() == ObjCMessageExpr::Class) {
669     // When the receiver type is id, Class, or some super class of the tracked
670     // type, look up the method in the tracked type, not in the receiver type.
671     // This way we preserve more information.
672     if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType() ||
673         ASTCtxt.canAssignObjCInterfaces(ReceiverObjectPtrType, TrackedType)) {
674       const ObjCInterfaceDecl *InterfaceDecl = TrackedType->getInterfaceDecl();
675       // The method might not be found.
676       Selector Sel = MessageExpr->getSelector();
677       Method = InterfaceDecl->lookupInstanceMethod(Sel);
678       if (!Method)
679         Method = InterfaceDecl->lookupClassMethod(Sel);
680     }
681   }
682 
683   // Fallback to statick method lookup when the one based on the tracked type
684   // failed.
685   return Method ? Method : MessageExpr->getMethodDecl();
686 }
687 
688 /// Get the returned ObjCObjectPointerType by a method based on the tracked type
689 /// information, or null pointer when the returned type is not an
690 /// ObjCObjectPointerType.
getReturnTypeForMethod(const ObjCMethodDecl * Method,ArrayRef<QualType> TypeArgs,const ObjCObjectPointerType * SelfType,ASTContext & C)691 static QualType getReturnTypeForMethod(
692     const ObjCMethodDecl *Method, ArrayRef<QualType> TypeArgs,
693     const ObjCObjectPointerType *SelfType, ASTContext &C) {
694   QualType StaticResultType = Method->getReturnType();
695 
696   // Is the return type declared as instance type?
697   if (StaticResultType == C.getObjCInstanceType())
698     return QualType(SelfType, 0);
699 
700   // Check whether the result type depends on a type parameter.
701   if (!isObjCTypeParamDependent(StaticResultType))
702     return QualType();
703 
704   QualType ResultType = StaticResultType.substObjCTypeArgs(
705       C, TypeArgs, ObjCSubstitutionContext::Result);
706 
707   return ResultType;
708 }
709 
710 /// When the receiver has a tracked type, use that type to validate the
711 /// argumments of the message expression and the return value.
checkPreObjCMessage(const ObjCMethodCall & M,CheckerContext & C) const712 void DynamicTypePropagation::checkPreObjCMessage(const ObjCMethodCall &M,
713                                                  CheckerContext &C) const {
714   ProgramStateRef State = C.getState();
715   SymbolRef Sym = M.getReceiverSVal().getAsSymbol();
716   if (!Sym)
717     return;
718 
719   const ObjCObjectPointerType *const *TrackedType =
720       State->get<MostSpecializedTypeArgsMap>(Sym);
721   if (!TrackedType)
722     return;
723 
724   // Get the type arguments from tracked type and substitute type arguments
725   // before do the semantic check.
726 
727   ASTContext &ASTCtxt = C.getASTContext();
728   const ObjCMessageExpr *MessageExpr = M.getOriginExpr();
729   const ObjCMethodDecl *Method =
730       findMethodDecl(MessageExpr, *TrackedType, ASTCtxt);
731 
732   // It is possible to call non-existent methods in Obj-C.
733   if (!Method)
734     return;
735 
736   // If the method is declared on a class that has a non-invariant
737   // type parameter, don't warn about parameter mismatches after performing
738   // substitution. This prevents warning when the programmer has purposely
739   // casted the receiver to a super type or unspecialized type but the analyzer
740   // has a more precise tracked type than the programmer intends at the call
741   // site.
742   //
743   // For example, consider NSArray (which has a covariant type parameter)
744   // and NSMutableArray (a subclass of NSArray where the type parameter is
745   // invariant):
746   // NSMutableArray *a = [[NSMutableArray<NSString *> alloc] init;
747   //
748   // [a containsObject:number]; // Safe: -containsObject is defined on NSArray.
749   // NSArray<NSObject *> *other = [a arrayByAddingObject:number]  // Safe
750   //
751   // [a addObject:number] // Unsafe: -addObject: is defined on NSMutableArray
752   //
753 
754   const ObjCInterfaceDecl *Interface = Method->getClassInterface();
755   if (!Interface)
756     return;
757 
758   ObjCTypeParamList *TypeParams = Interface->getTypeParamList();
759   if (!TypeParams)
760     return;
761 
762   for (ObjCTypeParamDecl *TypeParam : *TypeParams) {
763     if (TypeParam->getVariance() != ObjCTypeParamVariance::Invariant)
764       return;
765   }
766 
767   Optional<ArrayRef<QualType>> TypeArgs =
768       (*TrackedType)->getObjCSubstitutions(Method->getDeclContext());
769   // This case might happen when there is an unspecialized override of a
770   // specialized method.
771   if (!TypeArgs)
772     return;
773 
774   for (unsigned i = 0; i < Method->param_size(); i++) {
775     const Expr *Arg = MessageExpr->getArg(i);
776     const ParmVarDecl *Param = Method->parameters()[i];
777 
778     QualType OrigParamType = Param->getType();
779     if (!isObjCTypeParamDependent(OrigParamType))
780       continue;
781 
782     QualType ParamType = OrigParamType.substObjCTypeArgs(
783         ASTCtxt, *TypeArgs, ObjCSubstitutionContext::Parameter);
784     // Check if it can be assigned
785     const auto *ParamObjectPtrType = ParamType->getAs<ObjCObjectPointerType>();
786     const auto *ArgObjectPtrType =
787         stripCastsAndSugar(Arg)->getType()->getAs<ObjCObjectPointerType>();
788     if (!ParamObjectPtrType || !ArgObjectPtrType)
789       continue;
790 
791     // Check if we have more concrete tracked type that is not a super type of
792     // the static argument type.
793     SVal ArgSVal = M.getArgSVal(i);
794     SymbolRef ArgSym = ArgSVal.getAsSymbol();
795     if (ArgSym) {
796       const ObjCObjectPointerType *const *TrackedArgType =
797           State->get<MostSpecializedTypeArgsMap>(ArgSym);
798       if (TrackedArgType &&
799           ASTCtxt.canAssignObjCInterfaces(ArgObjectPtrType, *TrackedArgType)) {
800         ArgObjectPtrType = *TrackedArgType;
801       }
802     }
803 
804     // Warn when argument is incompatible with the parameter.
805     if (!ASTCtxt.canAssignObjCInterfaces(ParamObjectPtrType,
806                                          ArgObjectPtrType)) {
807       static CheckerProgramPointTag Tag(this, "ArgTypeMismatch");
808       ExplodedNode *N = C.addTransition(State, &Tag);
809       reportGenericsBug(ArgObjectPtrType, ParamObjectPtrType, N, Sym, C, Arg);
810       return;
811     }
812   }
813 }
814 
815 /// This callback is used to infer the types for Class variables. This info is
816 /// used later to validate messages that sent to classes. Class variables are
817 /// initialized with by invoking the 'class' method on a class.
818 /// This method is also used to infer the type information for the return
819 /// types.
820 // TODO: right now it only tracks generic types. Extend this to track every
821 // type in the DynamicTypeMap and diagnose type errors!
checkPostObjCMessage(const ObjCMethodCall & M,CheckerContext & C) const822 void DynamicTypePropagation::checkPostObjCMessage(const ObjCMethodCall &M,
823                                                   CheckerContext &C) const {
824   const ObjCMessageExpr *MessageExpr = M.getOriginExpr();
825 
826   SymbolRef RetSym = M.getReturnValue().getAsSymbol();
827   if (!RetSym)
828     return;
829 
830   Selector Sel = MessageExpr->getSelector();
831   ProgramStateRef State = C.getState();
832   // Inference for class variables.
833   // We are only interested in cases where the class method is invoked on a
834   // class. This method is provided by the runtime and available on all classes.
835   if (MessageExpr->getReceiverKind() == ObjCMessageExpr::Class &&
836       Sel.getAsString() == "class") {
837     QualType ReceiverType = MessageExpr->getClassReceiver();
838     const auto *ReceiverClassType = ReceiverType->getAs<ObjCObjectType>();
839     QualType ReceiverClassPointerType =
840         C.getASTContext().getObjCObjectPointerType(
841             QualType(ReceiverClassType, 0));
842 
843     if (!ReceiverClassType->isSpecialized())
844       return;
845     const auto *InferredType =
846         ReceiverClassPointerType->getAs<ObjCObjectPointerType>();
847     assert(InferredType);
848 
849     State = State->set<MostSpecializedTypeArgsMap>(RetSym, InferredType);
850     C.addTransition(State);
851     return;
852   }
853 
854   // Tracking for return types.
855   SymbolRef RecSym = M.getReceiverSVal().getAsSymbol();
856   if (!RecSym)
857     return;
858 
859   const ObjCObjectPointerType *const *TrackedType =
860       State->get<MostSpecializedTypeArgsMap>(RecSym);
861   if (!TrackedType)
862     return;
863 
864   ASTContext &ASTCtxt = C.getASTContext();
865   const ObjCMethodDecl *Method =
866       findMethodDecl(MessageExpr, *TrackedType, ASTCtxt);
867   if (!Method)
868     return;
869 
870   Optional<ArrayRef<QualType>> TypeArgs =
871       (*TrackedType)->getObjCSubstitutions(Method->getDeclContext());
872   if (!TypeArgs)
873     return;
874 
875   QualType ResultType =
876       getReturnTypeForMethod(Method, *TypeArgs, *TrackedType, ASTCtxt);
877   // The static type is the same as the deduced type.
878   if (ResultType.isNull())
879     return;
880 
881   const MemRegion *RetRegion = M.getReturnValue().getAsRegion();
882   ExplodedNode *Pred = C.getPredecessor();
883   // When there is an entry available for the return symbol in DynamicTypeMap,
884   // the call was inlined, and the information in the DynamicTypeMap is should
885   // be precise.
886   if (RetRegion && !State->get<DynamicTypeMap>(RetRegion)) {
887     // TODO: we have duplicated information in DynamicTypeMap and
888     // MostSpecializedTypeArgsMap. We should only store anything in the later if
889     // the stored data differs from the one stored in the former.
890     State = setDynamicTypeInfo(State, RetRegion, ResultType,
891                                /*CanBeSubclass=*/true);
892     Pred = C.addTransition(State);
893   }
894 
895   const auto *ResultPtrType = ResultType->getAs<ObjCObjectPointerType>();
896 
897   if (!ResultPtrType || ResultPtrType->isUnspecialized())
898     return;
899 
900   // When the result is a specialized type and it is not tracked yet, track it
901   // for the result symbol.
902   if (!State->get<MostSpecializedTypeArgsMap>(RetSym)) {
903     State = State->set<MostSpecializedTypeArgsMap>(RetSym, ResultPtrType);
904     C.addTransition(State, Pred);
905   }
906 }
907 
reportGenericsBug(const ObjCObjectPointerType * From,const ObjCObjectPointerType * To,ExplodedNode * N,SymbolRef Sym,CheckerContext & C,const Stmt * ReportedNode) const908 void DynamicTypePropagation::reportGenericsBug(
909     const ObjCObjectPointerType *From, const ObjCObjectPointerType *To,
910     ExplodedNode *N, SymbolRef Sym, CheckerContext &C,
911     const Stmt *ReportedNode) const {
912   if (!CheckGenerics)
913     return;
914 
915   initBugType();
916   SmallString<192> Buf;
917   llvm::raw_svector_ostream OS(Buf);
918   OS << "Conversion from value of type '";
919   QualType::print(From, Qualifiers(), OS, C.getLangOpts(), llvm::Twine());
920   OS << "' to incompatible type '";
921   QualType::print(To, Qualifiers(), OS, C.getLangOpts(), llvm::Twine());
922   OS << "'";
923   std::unique_ptr<BugReport> R(
924       new BugReport(*ObjCGenericsBugType, OS.str(), N));
925   R->markInteresting(Sym);
926   R->addVisitor(llvm::make_unique<GenericsBugVisitor>(Sym));
927   if (ReportedNode)
928     R->addRange(ReportedNode->getSourceRange());
929   C.emitReport(std::move(R));
930 }
931 
932 std::shared_ptr<PathDiagnosticPiece>
VisitNode(const ExplodedNode * N,BugReporterContext & BRC,BugReport & BR)933 DynamicTypePropagation::GenericsBugVisitor::VisitNode(const ExplodedNode *N,
934                                                       BugReporterContext &BRC,
935                                                       BugReport &BR) {
936   ProgramStateRef state = N->getState();
937   ProgramStateRef statePrev = N->getFirstPred()->getState();
938 
939   const ObjCObjectPointerType *const *TrackedType =
940       state->get<MostSpecializedTypeArgsMap>(Sym);
941   const ObjCObjectPointerType *const *TrackedTypePrev =
942       statePrev->get<MostSpecializedTypeArgsMap>(Sym);
943   if (!TrackedType)
944     return nullptr;
945 
946   if (TrackedTypePrev && *TrackedTypePrev == *TrackedType)
947     return nullptr;
948 
949   // Retrieve the associated statement.
950   const Stmt *S = PathDiagnosticLocation::getStmt(N);
951   if (!S)
952     return nullptr;
953 
954   const LangOptions &LangOpts = BRC.getASTContext().getLangOpts();
955 
956   SmallString<256> Buf;
957   llvm::raw_svector_ostream OS(Buf);
958   OS << "Type '";
959   QualType::print(*TrackedType, Qualifiers(), OS, LangOpts, llvm::Twine());
960   OS << "' is inferred from ";
961 
962   if (const auto *ExplicitCast = dyn_cast<ExplicitCastExpr>(S)) {
963     OS << "explicit cast (from '";
964     QualType::print(ExplicitCast->getSubExpr()->getType().getTypePtr(),
965                     Qualifiers(), OS, LangOpts, llvm::Twine());
966     OS << "' to '";
967     QualType::print(ExplicitCast->getType().getTypePtr(), Qualifiers(), OS,
968                     LangOpts, llvm::Twine());
969     OS << "')";
970   } else if (const auto *ImplicitCast = dyn_cast<ImplicitCastExpr>(S)) {
971     OS << "implicit cast (from '";
972     QualType::print(ImplicitCast->getSubExpr()->getType().getTypePtr(),
973                     Qualifiers(), OS, LangOpts, llvm::Twine());
974     OS << "' to '";
975     QualType::print(ImplicitCast->getType().getTypePtr(), Qualifiers(), OS,
976                     LangOpts, llvm::Twine());
977     OS << "')";
978   } else {
979     OS << "this context";
980   }
981 
982   // Generate the extra diagnostic.
983   PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
984                              N->getLocationContext());
985   return std::make_shared<PathDiagnosticEventPiece>(Pos, OS.str(), true,
986                                                     nullptr);
987 }
988 
989 /// Register checkers.
registerObjCGenericsChecker(CheckerManager & mgr)990 void ento::registerObjCGenericsChecker(CheckerManager &mgr) {
991   DynamicTypePropagation *checker =
992       mgr.registerChecker<DynamicTypePropagation>();
993   checker->CheckGenerics = true;
994 }
995 
registerDynamicTypePropagation(CheckerManager & mgr)996 void ento::registerDynamicTypePropagation(CheckerManager &mgr) {
997   mgr.registerChecker<DynamicTypePropagation>();
998 }
999