1 //=- IvarInvalidationChecker.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 checker implements annotation driven invalidation checking. If a class 11 // contains a method annotated with 'objc_instance_variable_invalidator', 12 // - (void) foo 13 // __attribute__((annotate("objc_instance_variable_invalidator"))); 14 // all the "ivalidatable" instance variables of this class should be 15 // invalidated. We call an instance variable ivalidatable if it is an object of 16 // a class which contains an invalidation method. There could be multiple 17 // methods annotated with such annotations per class, either one can be used 18 // to invalidate the ivar. An ivar or property are considered to be 19 // invalidated if they are being assigned 'nil' or an invalidation method has 20 // been called on them. An invalidation method should either invalidate all 21 // the ivars or call another invalidation method (on self). 22 // 23 // Partial invalidor annotation allows to addess cases when ivars are 24 // invalidated by other methods, which might or might not be called from 25 // the invalidation method. The checker checks that each invalidation 26 // method and all the partial methods cumulatively invalidate all ivars. 27 // __attribute__((annotate("objc_instance_variable_invalidator_partial"))); 28 // 29 //===----------------------------------------------------------------------===// 30 31 #include "ClangSACheckers.h" 32 #include "clang/AST/Attr.h" 33 #include "clang/AST/DeclObjC.h" 34 #include "clang/AST/StmtVisitor.h" 35 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h" 36 #include "clang/StaticAnalyzer/Core/Checker.h" 37 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h" 38 #include "llvm/ADT/DenseMap.h" 39 #include "llvm/ADT/SetVector.h" 40 #include "llvm/ADT/SmallString.h" 41 42 using namespace clang; 43 using namespace ento; 44 45 namespace { 46 47 struct ChecksFilter { 48 /// Check for missing invalidation method declarations. 49 DefaultBool check_MissingInvalidationMethod; 50 /// Check that all ivars are invalidated. 51 DefaultBool check_InstanceVariableInvalidation; 52 53 CheckName checkName_MissingInvalidationMethod; 54 CheckName checkName_InstanceVariableInvalidation; 55 }; 56 57 class IvarInvalidationCheckerImpl { 58 59 typedef llvm::SmallSetVector<const ObjCMethodDecl*, 2> MethodSet; 60 typedef llvm::DenseMap<const ObjCMethodDecl*, 61 const ObjCIvarDecl*> MethToIvarMapTy; 62 typedef llvm::DenseMap<const ObjCPropertyDecl*, 63 const ObjCIvarDecl*> PropToIvarMapTy; 64 typedef llvm::DenseMap<const ObjCIvarDecl*, 65 const ObjCPropertyDecl*> IvarToPropMapTy; 66 67 68 struct InvalidationInfo { 69 /// Has the ivar been invalidated? 70 bool IsInvalidated; 71 72 /// The methods which can be used to invalidate the ivar. 73 MethodSet InvalidationMethods; 74 75 InvalidationInfo() : IsInvalidated(false) {} 76 void addInvalidationMethod(const ObjCMethodDecl *MD) { 77 InvalidationMethods.insert(MD); 78 } 79 80 bool needsInvalidation() const { 81 return !InvalidationMethods.empty(); 82 } 83 84 bool hasMethod(const ObjCMethodDecl *MD) { 85 if (IsInvalidated) 86 return true; 87 for (MethodSet::iterator I = InvalidationMethods.begin(), 88 E = InvalidationMethods.end(); I != E; ++I) { 89 if (*I == MD) { 90 IsInvalidated = true; 91 return true; 92 } 93 } 94 return false; 95 } 96 }; 97 98 typedef llvm::DenseMap<const ObjCIvarDecl*, InvalidationInfo> IvarSet; 99 100 /// Statement visitor, which walks the method body and flags the ivars 101 /// referenced in it (either directly or via property). 102 class MethodCrawler : public ConstStmtVisitor<MethodCrawler> { 103 /// The set of Ivars which need to be invalidated. 104 IvarSet &IVars; 105 106 /// Flag is set as the result of a message send to another 107 /// invalidation method. 108 bool &CalledAnotherInvalidationMethod; 109 110 /// Property setter to ivar mapping. 111 const MethToIvarMapTy &PropertySetterToIvarMap; 112 113 /// Property getter to ivar mapping. 114 const MethToIvarMapTy &PropertyGetterToIvarMap; 115 116 /// Property to ivar mapping. 117 const PropToIvarMapTy &PropertyToIvarMap; 118 119 /// The invalidation method being currently processed. 120 const ObjCMethodDecl *InvalidationMethod; 121 122 ASTContext &Ctx; 123 124 /// Peel off parens, casts, OpaqueValueExpr, and PseudoObjectExpr. 125 const Expr *peel(const Expr *E) const; 126 127 /// Does this expression represent zero: '0'? 128 bool isZero(const Expr *E) const; 129 130 /// Mark the given ivar as invalidated. 131 void markInvalidated(const ObjCIvarDecl *Iv); 132 133 /// Checks if IvarRef refers to the tracked IVar, if yes, marks it as 134 /// invalidated. 135 void checkObjCIvarRefExpr(const ObjCIvarRefExpr *IvarRef); 136 137 /// Checks if ObjCPropertyRefExpr refers to the tracked IVar, if yes, marks 138 /// it as invalidated. 139 void checkObjCPropertyRefExpr(const ObjCPropertyRefExpr *PA); 140 141 /// Checks if ObjCMessageExpr refers to (is a getter for) the tracked IVar, 142 /// if yes, marks it as invalidated. 143 void checkObjCMessageExpr(const ObjCMessageExpr *ME); 144 145 /// Checks if the Expr refers to an ivar, if yes, marks it as invalidated. 146 void check(const Expr *E); 147 148 public: 149 MethodCrawler(IvarSet &InIVars, 150 bool &InCalledAnotherInvalidationMethod, 151 const MethToIvarMapTy &InPropertySetterToIvarMap, 152 const MethToIvarMapTy &InPropertyGetterToIvarMap, 153 const PropToIvarMapTy &InPropertyToIvarMap, 154 ASTContext &InCtx) 155 : IVars(InIVars), 156 CalledAnotherInvalidationMethod(InCalledAnotherInvalidationMethod), 157 PropertySetterToIvarMap(InPropertySetterToIvarMap), 158 PropertyGetterToIvarMap(InPropertyGetterToIvarMap), 159 PropertyToIvarMap(InPropertyToIvarMap), 160 InvalidationMethod(0), 161 Ctx(InCtx) {} 162 163 void VisitStmt(const Stmt *S) { VisitChildren(S); } 164 165 void VisitBinaryOperator(const BinaryOperator *BO); 166 167 void VisitObjCMessageExpr(const ObjCMessageExpr *ME); 168 169 void VisitChildren(const Stmt *S) { 170 for (Stmt::const_child_range I = S->children(); I; ++I) { 171 if (*I) 172 this->Visit(*I); 173 if (CalledAnotherInvalidationMethod) 174 return; 175 } 176 } 177 }; 178 179 /// Check if the any of the methods inside the interface are annotated with 180 /// the invalidation annotation, update the IvarInfo accordingly. 181 /// \param LookForPartial is set when we are searching for partial 182 /// invalidators. 183 static void containsInvalidationMethod(const ObjCContainerDecl *D, 184 InvalidationInfo &Out, 185 bool LookForPartial); 186 187 /// Check if ivar should be tracked and add to TrackedIvars if positive. 188 /// Returns true if ivar should be tracked. 189 static bool trackIvar(const ObjCIvarDecl *Iv, IvarSet &TrackedIvars, 190 const ObjCIvarDecl **FirstIvarDecl); 191 192 /// Given the property declaration, and the list of tracked ivars, finds 193 /// the ivar backing the property when possible. Returns '0' when no such 194 /// ivar could be found. 195 static const ObjCIvarDecl *findPropertyBackingIvar( 196 const ObjCPropertyDecl *Prop, 197 const ObjCInterfaceDecl *InterfaceD, 198 IvarSet &TrackedIvars, 199 const ObjCIvarDecl **FirstIvarDecl); 200 201 /// Print ivar name or the property if the given ivar backs a property. 202 static void printIvar(llvm::raw_svector_ostream &os, 203 const ObjCIvarDecl *IvarDecl, 204 const IvarToPropMapTy &IvarToPopertyMap); 205 206 void reportNoInvalidationMethod(CheckName CheckName, 207 const ObjCIvarDecl *FirstIvarDecl, 208 const IvarToPropMapTy &IvarToPopertyMap, 209 const ObjCInterfaceDecl *InterfaceD, 210 bool MissingDeclaration) const; 211 void reportIvarNeedsInvalidation(const ObjCIvarDecl *IvarD, 212 const IvarToPropMapTy &IvarToPopertyMap, 213 const ObjCMethodDecl *MethodD) const; 214 215 AnalysisManager& Mgr; 216 BugReporter &BR; 217 /// Filter on the checks performed. 218 const ChecksFilter &Filter; 219 220 public: 221 IvarInvalidationCheckerImpl(AnalysisManager& InMgr, 222 BugReporter &InBR, 223 const ChecksFilter &InFilter) : 224 Mgr (InMgr), BR(InBR), Filter(InFilter) {} 225 226 void visit(const ObjCImplementationDecl *D) const; 227 }; 228 229 static bool isInvalidationMethod(const ObjCMethodDecl *M, bool LookForPartial) { 230 for (const auto *Ann : M->specific_attrs<AnnotateAttr>()) { 231 if (!LookForPartial && 232 Ann->getAnnotation() == "objc_instance_variable_invalidator") 233 return true; 234 if (LookForPartial && 235 Ann->getAnnotation() == "objc_instance_variable_invalidator_partial") 236 return true; 237 } 238 return false; 239 } 240 241 void IvarInvalidationCheckerImpl::containsInvalidationMethod( 242 const ObjCContainerDecl *D, InvalidationInfo &OutInfo, bool Partial) { 243 244 if (!D) 245 return; 246 247 assert(!isa<ObjCImplementationDecl>(D)); 248 // TODO: Cache the results. 249 250 // Check all methods. 251 for (const auto *MDI : D->methods()) 252 if (isInvalidationMethod(MDI, Partial)) 253 OutInfo.addInvalidationMethod( 254 cast<ObjCMethodDecl>(MDI->getCanonicalDecl())); 255 256 // If interface, check all parent protocols and super. 257 if (const ObjCInterfaceDecl *InterfD = dyn_cast<ObjCInterfaceDecl>(D)) { 258 259 // Visit all protocols. 260 for (ObjCInterfaceDecl::protocol_iterator 261 I = InterfD->protocol_begin(), 262 E = InterfD->protocol_end(); I != E; ++I) { 263 containsInvalidationMethod((*I)->getDefinition(), OutInfo, Partial); 264 } 265 266 // Visit all categories in case the invalidation method is declared in 267 // a category. 268 for (ObjCInterfaceDecl::visible_extensions_iterator 269 Ext = InterfD->visible_extensions_begin(), 270 ExtEnd = InterfD->visible_extensions_end(); 271 Ext != ExtEnd; ++Ext) { 272 containsInvalidationMethod(*Ext, OutInfo, Partial); 273 } 274 275 containsInvalidationMethod(InterfD->getSuperClass(), OutInfo, Partial); 276 return; 277 } 278 279 // If protocol, check all parent protocols. 280 if (const ObjCProtocolDecl *ProtD = dyn_cast<ObjCProtocolDecl>(D)) { 281 for (ObjCInterfaceDecl::protocol_iterator 282 I = ProtD->protocol_begin(), 283 E = ProtD->protocol_end(); I != E; ++I) { 284 containsInvalidationMethod((*I)->getDefinition(), OutInfo, Partial); 285 } 286 return; 287 } 288 289 return; 290 } 291 292 bool IvarInvalidationCheckerImpl::trackIvar(const ObjCIvarDecl *Iv, 293 IvarSet &TrackedIvars, 294 const ObjCIvarDecl **FirstIvarDecl) { 295 QualType IvQTy = Iv->getType(); 296 const ObjCObjectPointerType *IvTy = IvQTy->getAs<ObjCObjectPointerType>(); 297 if (!IvTy) 298 return false; 299 const ObjCInterfaceDecl *IvInterf = IvTy->getInterfaceDecl(); 300 301 InvalidationInfo Info; 302 containsInvalidationMethod(IvInterf, Info, /*LookForPartial*/ false); 303 if (Info.needsInvalidation()) { 304 const ObjCIvarDecl *I = cast<ObjCIvarDecl>(Iv->getCanonicalDecl()); 305 TrackedIvars[I] = Info; 306 if (!*FirstIvarDecl) 307 *FirstIvarDecl = I; 308 return true; 309 } 310 return false; 311 } 312 313 const ObjCIvarDecl *IvarInvalidationCheckerImpl::findPropertyBackingIvar( 314 const ObjCPropertyDecl *Prop, 315 const ObjCInterfaceDecl *InterfaceD, 316 IvarSet &TrackedIvars, 317 const ObjCIvarDecl **FirstIvarDecl) { 318 const ObjCIvarDecl *IvarD = 0; 319 320 // Lookup for the synthesized case. 321 IvarD = Prop->getPropertyIvarDecl(); 322 // We only track the ivars/properties that are defined in the current 323 // class (not the parent). 324 if (IvarD && IvarD->getContainingInterface() == InterfaceD) { 325 if (TrackedIvars.count(IvarD)) { 326 return IvarD; 327 } 328 // If the ivar is synthesized we still want to track it. 329 if (trackIvar(IvarD, TrackedIvars, FirstIvarDecl)) 330 return IvarD; 331 } 332 333 // Lookup IVars named "_PropName"or "PropName" among the tracked Ivars. 334 StringRef PropName = Prop->getIdentifier()->getName(); 335 for (IvarSet::const_iterator I = TrackedIvars.begin(), 336 E = TrackedIvars.end(); I != E; ++I) { 337 const ObjCIvarDecl *Iv = I->first; 338 StringRef IvarName = Iv->getName(); 339 340 if (IvarName == PropName) 341 return Iv; 342 343 SmallString<128> PropNameWithUnderscore; 344 { 345 llvm::raw_svector_ostream os(PropNameWithUnderscore); 346 os << '_' << PropName; 347 } 348 if (IvarName == PropNameWithUnderscore.str()) 349 return Iv; 350 } 351 352 // Note, this is a possible source of false positives. We could look at the 353 // getter implementation to find the ivar when its name is not derived from 354 // the property name. 355 return 0; 356 } 357 358 void IvarInvalidationCheckerImpl::printIvar(llvm::raw_svector_ostream &os, 359 const ObjCIvarDecl *IvarDecl, 360 const IvarToPropMapTy &IvarToPopertyMap) { 361 if (IvarDecl->getSynthesize()) { 362 const ObjCPropertyDecl *PD = IvarToPopertyMap.lookup(IvarDecl); 363 assert(PD &&"Do we synthesize ivars for something other than properties?"); 364 os << "Property "<< PD->getName() << " "; 365 } else { 366 os << "Instance variable "<< IvarDecl->getName() << " "; 367 } 368 } 369 370 // Check that the invalidatable interfaces with ivars/properties implement the 371 // invalidation methods. 372 void IvarInvalidationCheckerImpl:: 373 visit(const ObjCImplementationDecl *ImplD) const { 374 // Collect all ivars that need cleanup. 375 IvarSet Ivars; 376 // Record the first Ivar needing invalidation; used in reporting when only 377 // one ivar is sufficient. Cannot grab the first on the Ivars set to ensure 378 // deterministic output. 379 const ObjCIvarDecl *FirstIvarDecl = 0; 380 const ObjCInterfaceDecl *InterfaceD = ImplD->getClassInterface(); 381 382 // Collect ivars declared in this class, its extensions and its implementation 383 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(InterfaceD); 384 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv; 385 Iv= Iv->getNextIvar()) 386 trackIvar(Iv, Ivars, &FirstIvarDecl); 387 388 // Construct Property/Property Accessor to Ivar maps to assist checking if an 389 // ivar which is backing a property has been reset. 390 MethToIvarMapTy PropSetterToIvarMap; 391 MethToIvarMapTy PropGetterToIvarMap; 392 PropToIvarMapTy PropertyToIvarMap; 393 IvarToPropMapTy IvarToPopertyMap; 394 395 ObjCInterfaceDecl::PropertyMap PropMap; 396 ObjCInterfaceDecl::PropertyDeclOrder PropOrder; 397 InterfaceD->collectPropertiesToImplement(PropMap, PropOrder); 398 399 for (ObjCInterfaceDecl::PropertyMap::iterator 400 I = PropMap.begin(), E = PropMap.end(); I != E; ++I) { 401 const ObjCPropertyDecl *PD = I->second; 402 403 const ObjCIvarDecl *ID = findPropertyBackingIvar(PD, InterfaceD, Ivars, 404 &FirstIvarDecl); 405 if (!ID) 406 continue; 407 408 // Store the mappings. 409 PD = cast<ObjCPropertyDecl>(PD->getCanonicalDecl()); 410 PropertyToIvarMap[PD] = ID; 411 IvarToPopertyMap[ID] = PD; 412 413 // Find the setter and the getter. 414 const ObjCMethodDecl *SetterD = PD->getSetterMethodDecl(); 415 if (SetterD) { 416 SetterD = cast<ObjCMethodDecl>(SetterD->getCanonicalDecl()); 417 PropSetterToIvarMap[SetterD] = ID; 418 } 419 420 const ObjCMethodDecl *GetterD = PD->getGetterMethodDecl(); 421 if (GetterD) { 422 GetterD = cast<ObjCMethodDecl>(GetterD->getCanonicalDecl()); 423 PropGetterToIvarMap[GetterD] = ID; 424 } 425 } 426 427 // If no ivars need invalidation, there is nothing to check here. 428 if (Ivars.empty()) 429 return; 430 431 // Find all partial invalidation methods. 432 InvalidationInfo PartialInfo; 433 containsInvalidationMethod(InterfaceD, PartialInfo, /*LookForPartial*/ true); 434 435 // Remove ivars invalidated by the partial invalidation methods. They do not 436 // need to be invalidated in the regular invalidation methods. 437 bool AtImplementationContainsAtLeastOnePartialInvalidationMethod = false; 438 for (MethodSet::iterator 439 I = PartialInfo.InvalidationMethods.begin(), 440 E = PartialInfo.InvalidationMethods.end(); I != E; ++I) { 441 const ObjCMethodDecl *InterfD = *I; 442 443 // Get the corresponding method in the @implementation. 444 const ObjCMethodDecl *D = ImplD->getMethod(InterfD->getSelector(), 445 InterfD->isInstanceMethod()); 446 if (D && D->hasBody()) { 447 AtImplementationContainsAtLeastOnePartialInvalidationMethod = true; 448 449 bool CalledAnotherInvalidationMethod = false; 450 // The MethodCrowler is going to remove the invalidated ivars. 451 MethodCrawler(Ivars, 452 CalledAnotherInvalidationMethod, 453 PropSetterToIvarMap, 454 PropGetterToIvarMap, 455 PropertyToIvarMap, 456 BR.getContext()).VisitStmt(D->getBody()); 457 // If another invalidation method was called, trust that full invalidation 458 // has occurred. 459 if (CalledAnotherInvalidationMethod) 460 Ivars.clear(); 461 } 462 } 463 464 // If all ivars have been invalidated by partial invalidators, there is 465 // nothing to check here. 466 if (Ivars.empty()) 467 return; 468 469 // Find all invalidation methods in this @interface declaration and parents. 470 InvalidationInfo Info; 471 containsInvalidationMethod(InterfaceD, Info, /*LookForPartial*/ false); 472 473 // Report an error in case none of the invalidation methods are declared. 474 if (!Info.needsInvalidation() && !PartialInfo.needsInvalidation()) { 475 if (Filter.check_MissingInvalidationMethod) 476 reportNoInvalidationMethod(Filter.checkName_MissingInvalidationMethod, 477 FirstIvarDecl, IvarToPopertyMap, InterfaceD, 478 /*MissingDeclaration*/ true); 479 // If there are no invalidation methods, there is no ivar validation work 480 // to be done. 481 return; 482 } 483 484 // Only check if Ivars are invalidated when InstanceVariableInvalidation 485 // has been requested. 486 if (!Filter.check_InstanceVariableInvalidation) 487 return; 488 489 // Check that all ivars are invalidated by the invalidation methods. 490 bool AtImplementationContainsAtLeastOneInvalidationMethod = false; 491 for (MethodSet::iterator I = Info.InvalidationMethods.begin(), 492 E = Info.InvalidationMethods.end(); I != E; ++I) { 493 const ObjCMethodDecl *InterfD = *I; 494 495 // Get the corresponding method in the @implementation. 496 const ObjCMethodDecl *D = ImplD->getMethod(InterfD->getSelector(), 497 InterfD->isInstanceMethod()); 498 if (D && D->hasBody()) { 499 AtImplementationContainsAtLeastOneInvalidationMethod = true; 500 501 // Get a copy of ivars needing invalidation. 502 IvarSet IvarsI = Ivars; 503 504 bool CalledAnotherInvalidationMethod = false; 505 MethodCrawler(IvarsI, 506 CalledAnotherInvalidationMethod, 507 PropSetterToIvarMap, 508 PropGetterToIvarMap, 509 PropertyToIvarMap, 510 BR.getContext()).VisitStmt(D->getBody()); 511 // If another invalidation method was called, trust that full invalidation 512 // has occurred. 513 if (CalledAnotherInvalidationMethod) 514 continue; 515 516 // Warn on the ivars that were not invalidated by the method. 517 for (IvarSet::const_iterator 518 I = IvarsI.begin(), E = IvarsI.end(); I != E; ++I) 519 reportIvarNeedsInvalidation(I->first, IvarToPopertyMap, D); 520 } 521 } 522 523 // Report an error in case none of the invalidation methods are implemented. 524 if (!AtImplementationContainsAtLeastOneInvalidationMethod) { 525 if (AtImplementationContainsAtLeastOnePartialInvalidationMethod) { 526 // Warn on the ivars that were not invalidated by the prrtial 527 // invalidation methods. 528 for (IvarSet::const_iterator 529 I = Ivars.begin(), E = Ivars.end(); I != E; ++I) 530 reportIvarNeedsInvalidation(I->first, IvarToPopertyMap, 0); 531 } else { 532 // Otherwise, no invalidation methods were implemented. 533 reportNoInvalidationMethod(Filter.checkName_InstanceVariableInvalidation, 534 FirstIvarDecl, IvarToPopertyMap, InterfaceD, 535 /*MissingDeclaration*/ false); 536 } 537 } 538 } 539 540 void IvarInvalidationCheckerImpl::reportNoInvalidationMethod( 541 CheckName CheckName, const ObjCIvarDecl *FirstIvarDecl, 542 const IvarToPropMapTy &IvarToPopertyMap, 543 const ObjCInterfaceDecl *InterfaceD, bool MissingDeclaration) const { 544 SmallString<128> sbuf; 545 llvm::raw_svector_ostream os(sbuf); 546 assert(FirstIvarDecl); 547 printIvar(os, FirstIvarDecl, IvarToPopertyMap); 548 os << "needs to be invalidated; "; 549 if (MissingDeclaration) 550 os << "no invalidation method is declared for "; 551 else 552 os << "no invalidation method is defined in the @implementation for "; 553 os << InterfaceD->getName(); 554 555 PathDiagnosticLocation IvarDecLocation = 556 PathDiagnosticLocation::createBegin(FirstIvarDecl, BR.getSourceManager()); 557 558 BR.EmitBasicReport(FirstIvarDecl, CheckName, "Incomplete invalidation", 559 categories::CoreFoundationObjectiveC, os.str(), 560 IvarDecLocation); 561 } 562 563 void IvarInvalidationCheckerImpl:: 564 reportIvarNeedsInvalidation(const ObjCIvarDecl *IvarD, 565 const IvarToPropMapTy &IvarToPopertyMap, 566 const ObjCMethodDecl *MethodD) const { 567 SmallString<128> sbuf; 568 llvm::raw_svector_ostream os(sbuf); 569 printIvar(os, IvarD, IvarToPopertyMap); 570 os << "needs to be invalidated or set to nil"; 571 if (MethodD) { 572 PathDiagnosticLocation MethodDecLocation = 573 PathDiagnosticLocation::createEnd(MethodD->getBody(), 574 BR.getSourceManager(), 575 Mgr.getAnalysisDeclContext(MethodD)); 576 BR.EmitBasicReport(MethodD, Filter.checkName_InstanceVariableInvalidation, 577 "Incomplete invalidation", 578 categories::CoreFoundationObjectiveC, os.str(), 579 MethodDecLocation); 580 } else { 581 BR.EmitBasicReport( 582 IvarD, Filter.checkName_InstanceVariableInvalidation, 583 "Incomplete invalidation", categories::CoreFoundationObjectiveC, 584 os.str(), 585 PathDiagnosticLocation::createBegin(IvarD, BR.getSourceManager())); 586 } 587 } 588 589 void IvarInvalidationCheckerImpl::MethodCrawler::markInvalidated( 590 const ObjCIvarDecl *Iv) { 591 IvarSet::iterator I = IVars.find(Iv); 592 if (I != IVars.end()) { 593 // If InvalidationMethod is present, we are processing the message send and 594 // should ensure we are invalidating with the appropriate method, 595 // otherwise, we are processing setting to 'nil'. 596 if (!InvalidationMethod || 597 (InvalidationMethod && I->second.hasMethod(InvalidationMethod))) 598 IVars.erase(I); 599 } 600 } 601 602 const Expr *IvarInvalidationCheckerImpl::MethodCrawler::peel(const Expr *E) const { 603 E = E->IgnoreParenCasts(); 604 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 605 E = POE->getSyntacticForm()->IgnoreParenCasts(); 606 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) 607 E = OVE->getSourceExpr()->IgnoreParenCasts(); 608 return E; 609 } 610 611 void IvarInvalidationCheckerImpl::MethodCrawler::checkObjCIvarRefExpr( 612 const ObjCIvarRefExpr *IvarRef) { 613 if (const Decl *D = IvarRef->getDecl()) 614 markInvalidated(cast<ObjCIvarDecl>(D->getCanonicalDecl())); 615 } 616 617 void IvarInvalidationCheckerImpl::MethodCrawler::checkObjCMessageExpr( 618 const ObjCMessageExpr *ME) { 619 const ObjCMethodDecl *MD = ME->getMethodDecl(); 620 if (MD) { 621 MD = cast<ObjCMethodDecl>(MD->getCanonicalDecl()); 622 MethToIvarMapTy::const_iterator IvI = PropertyGetterToIvarMap.find(MD); 623 if (IvI != PropertyGetterToIvarMap.end()) 624 markInvalidated(IvI->second); 625 } 626 } 627 628 void IvarInvalidationCheckerImpl::MethodCrawler::checkObjCPropertyRefExpr( 629 const ObjCPropertyRefExpr *PA) { 630 631 if (PA->isExplicitProperty()) { 632 const ObjCPropertyDecl *PD = PA->getExplicitProperty(); 633 if (PD) { 634 PD = cast<ObjCPropertyDecl>(PD->getCanonicalDecl()); 635 PropToIvarMapTy::const_iterator IvI = PropertyToIvarMap.find(PD); 636 if (IvI != PropertyToIvarMap.end()) 637 markInvalidated(IvI->second); 638 return; 639 } 640 } 641 642 if (PA->isImplicitProperty()) { 643 const ObjCMethodDecl *MD = PA->getImplicitPropertySetter(); 644 if (MD) { 645 MD = cast<ObjCMethodDecl>(MD->getCanonicalDecl()); 646 MethToIvarMapTy::const_iterator IvI =PropertyGetterToIvarMap.find(MD); 647 if (IvI != PropertyGetterToIvarMap.end()) 648 markInvalidated(IvI->second); 649 return; 650 } 651 } 652 } 653 654 bool IvarInvalidationCheckerImpl::MethodCrawler::isZero(const Expr *E) const { 655 E = peel(E); 656 657 return (E->isNullPointerConstant(Ctx, Expr::NPC_ValueDependentIsNotNull) 658 != Expr::NPCK_NotNull); 659 } 660 661 void IvarInvalidationCheckerImpl::MethodCrawler::check(const Expr *E) { 662 E = peel(E); 663 664 if (const ObjCIvarRefExpr *IvarRef = dyn_cast<ObjCIvarRefExpr>(E)) { 665 checkObjCIvarRefExpr(IvarRef); 666 return; 667 } 668 669 if (const ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E)) { 670 checkObjCPropertyRefExpr(PropRef); 671 return; 672 } 673 674 if (const ObjCMessageExpr *MsgExpr = dyn_cast<ObjCMessageExpr>(E)) { 675 checkObjCMessageExpr(MsgExpr); 676 return; 677 } 678 } 679 680 void IvarInvalidationCheckerImpl::MethodCrawler::VisitBinaryOperator( 681 const BinaryOperator *BO) { 682 VisitStmt(BO); 683 684 // Do we assign/compare against zero? If yes, check the variable we are 685 // assigning to. 686 BinaryOperatorKind Opcode = BO->getOpcode(); 687 if (Opcode != BO_Assign && 688 Opcode != BO_EQ && 689 Opcode != BO_NE) 690 return; 691 692 if (isZero(BO->getRHS())) { 693 check(BO->getLHS()); 694 return; 695 } 696 697 if (Opcode != BO_Assign && isZero(BO->getLHS())) { 698 check(BO->getRHS()); 699 return; 700 } 701 } 702 703 void IvarInvalidationCheckerImpl::MethodCrawler::VisitObjCMessageExpr( 704 const ObjCMessageExpr *ME) { 705 const ObjCMethodDecl *MD = ME->getMethodDecl(); 706 const Expr *Receiver = ME->getInstanceReceiver(); 707 708 // Stop if we are calling '[self invalidate]'. 709 if (Receiver && isInvalidationMethod(MD, /*LookForPartial*/ false)) 710 if (Receiver->isObjCSelfExpr()) { 711 CalledAnotherInvalidationMethod = true; 712 return; 713 } 714 715 // Check if we call a setter and set the property to 'nil'. 716 if (MD && (ME->getNumArgs() == 1) && isZero(ME->getArg(0))) { 717 MD = cast<ObjCMethodDecl>(MD->getCanonicalDecl()); 718 MethToIvarMapTy::const_iterator IvI = PropertySetterToIvarMap.find(MD); 719 if (IvI != PropertySetterToIvarMap.end()) { 720 markInvalidated(IvI->second); 721 return; 722 } 723 } 724 725 // Check if we call the 'invalidation' routine on the ivar. 726 if (Receiver) { 727 InvalidationMethod = MD; 728 check(Receiver->IgnoreParenCasts()); 729 InvalidationMethod = 0; 730 } 731 732 VisitStmt(ME); 733 } 734 } 735 736 // Register the checkers. 737 namespace { 738 739 class IvarInvalidationChecker : 740 public Checker<check::ASTDecl<ObjCImplementationDecl> > { 741 public: 742 ChecksFilter Filter; 743 public: 744 void checkASTDecl(const ObjCImplementationDecl *D, AnalysisManager& Mgr, 745 BugReporter &BR) const { 746 IvarInvalidationCheckerImpl Walker(Mgr, BR, Filter); 747 Walker.visit(D); 748 } 749 }; 750 } 751 752 #define REGISTER_CHECKER(name) \ 753 void ento::register##name(CheckerManager &mgr) { \ 754 IvarInvalidationChecker *checker = \ 755 mgr.registerChecker<IvarInvalidationChecker>(); \ 756 checker->Filter.check_##name = true; \ 757 checker->Filter.checkName_##name = mgr.getCurrentCheckName(); \ 758 } 759 760 REGISTER_CHECKER(InstanceVariableInvalidation) 761 REGISTER_CHECKER(MissingInvalidationMethod) 762 763