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 (specific_attr_iterator<AnnotateAttr> 231 AI = M->specific_attr_begin<AnnotateAttr>(), 232 AE = M->specific_attr_end<AnnotateAttr>(); AI != AE; ++AI) { 233 const AnnotateAttr *Ann = *AI; 234 if (!LookForPartial && 235 Ann->getAnnotation() == "objc_instance_variable_invalidator") 236 return true; 237 if (LookForPartial && 238 Ann->getAnnotation() == "objc_instance_variable_invalidator_partial") 239 return true; 240 } 241 return false; 242 } 243 244 void IvarInvalidationCheckerImpl::containsInvalidationMethod( 245 const ObjCContainerDecl *D, InvalidationInfo &OutInfo, bool Partial) { 246 247 if (!D) 248 return; 249 250 assert(!isa<ObjCImplementationDecl>(D)); 251 // TODO: Cache the results. 252 253 // Check all methods. 254 for (ObjCContainerDecl::method_iterator 255 I = D->meth_begin(), 256 E = D->meth_end(); I != E; ++I) { 257 const ObjCMethodDecl *MDI = *I; 258 if (isInvalidationMethod(MDI, Partial)) 259 OutInfo.addInvalidationMethod( 260 cast<ObjCMethodDecl>(MDI->getCanonicalDecl())); 261 } 262 263 // If interface, check all parent protocols and super. 264 if (const ObjCInterfaceDecl *InterfD = dyn_cast<ObjCInterfaceDecl>(D)) { 265 266 // Visit all protocols. 267 for (ObjCInterfaceDecl::protocol_iterator 268 I = InterfD->protocol_begin(), 269 E = InterfD->protocol_end(); I != E; ++I) { 270 containsInvalidationMethod((*I)->getDefinition(), OutInfo, Partial); 271 } 272 273 // Visit all categories in case the invalidation method is declared in 274 // a category. 275 for (ObjCInterfaceDecl::visible_extensions_iterator 276 Ext = InterfD->visible_extensions_begin(), 277 ExtEnd = InterfD->visible_extensions_end(); 278 Ext != ExtEnd; ++Ext) { 279 containsInvalidationMethod(*Ext, OutInfo, Partial); 280 } 281 282 containsInvalidationMethod(InterfD->getSuperClass(), OutInfo, Partial); 283 return; 284 } 285 286 // If protocol, check all parent protocols. 287 if (const ObjCProtocolDecl *ProtD = dyn_cast<ObjCProtocolDecl>(D)) { 288 for (ObjCInterfaceDecl::protocol_iterator 289 I = ProtD->protocol_begin(), 290 E = ProtD->protocol_end(); I != E; ++I) { 291 containsInvalidationMethod((*I)->getDefinition(), OutInfo, Partial); 292 } 293 return; 294 } 295 296 return; 297 } 298 299 bool IvarInvalidationCheckerImpl::trackIvar(const ObjCIvarDecl *Iv, 300 IvarSet &TrackedIvars, 301 const ObjCIvarDecl **FirstIvarDecl) { 302 QualType IvQTy = Iv->getType(); 303 const ObjCObjectPointerType *IvTy = IvQTy->getAs<ObjCObjectPointerType>(); 304 if (!IvTy) 305 return false; 306 const ObjCInterfaceDecl *IvInterf = IvTy->getInterfaceDecl(); 307 308 InvalidationInfo Info; 309 containsInvalidationMethod(IvInterf, Info, /*LookForPartial*/ false); 310 if (Info.needsInvalidation()) { 311 const ObjCIvarDecl *I = cast<ObjCIvarDecl>(Iv->getCanonicalDecl()); 312 TrackedIvars[I] = Info; 313 if (!*FirstIvarDecl) 314 *FirstIvarDecl = I; 315 return true; 316 } 317 return false; 318 } 319 320 const ObjCIvarDecl *IvarInvalidationCheckerImpl::findPropertyBackingIvar( 321 const ObjCPropertyDecl *Prop, 322 const ObjCInterfaceDecl *InterfaceD, 323 IvarSet &TrackedIvars, 324 const ObjCIvarDecl **FirstIvarDecl) { 325 const ObjCIvarDecl *IvarD = 0; 326 327 // Lookup for the synthesized case. 328 IvarD = Prop->getPropertyIvarDecl(); 329 // We only track the ivars/properties that are defined in the current 330 // class (not the parent). 331 if (IvarD && IvarD->getContainingInterface() == InterfaceD) { 332 if (TrackedIvars.count(IvarD)) { 333 return IvarD; 334 } 335 // If the ivar is synthesized we still want to track it. 336 if (trackIvar(IvarD, TrackedIvars, FirstIvarDecl)) 337 return IvarD; 338 } 339 340 // Lookup IVars named "_PropName"or "PropName" among the tracked Ivars. 341 StringRef PropName = Prop->getIdentifier()->getName(); 342 for (IvarSet::const_iterator I = TrackedIvars.begin(), 343 E = TrackedIvars.end(); I != E; ++I) { 344 const ObjCIvarDecl *Iv = I->first; 345 StringRef IvarName = Iv->getName(); 346 347 if (IvarName == PropName) 348 return Iv; 349 350 SmallString<128> PropNameWithUnderscore; 351 { 352 llvm::raw_svector_ostream os(PropNameWithUnderscore); 353 os << '_' << PropName; 354 } 355 if (IvarName == PropNameWithUnderscore.str()) 356 return Iv; 357 } 358 359 // Note, this is a possible source of false positives. We could look at the 360 // getter implementation to find the ivar when its name is not derived from 361 // the property name. 362 return 0; 363 } 364 365 void IvarInvalidationCheckerImpl::printIvar(llvm::raw_svector_ostream &os, 366 const ObjCIvarDecl *IvarDecl, 367 const IvarToPropMapTy &IvarToPopertyMap) { 368 if (IvarDecl->getSynthesize()) { 369 const ObjCPropertyDecl *PD = IvarToPopertyMap.lookup(IvarDecl); 370 assert(PD &&"Do we synthesize ivars for something other than properties?"); 371 os << "Property "<< PD->getName() << " "; 372 } else { 373 os << "Instance variable "<< IvarDecl->getName() << " "; 374 } 375 } 376 377 // Check that the invalidatable interfaces with ivars/properties implement the 378 // invalidation methods. 379 void IvarInvalidationCheckerImpl:: 380 visit(const ObjCImplementationDecl *ImplD) const { 381 // Collect all ivars that need cleanup. 382 IvarSet Ivars; 383 // Record the first Ivar needing invalidation; used in reporting when only 384 // one ivar is sufficient. Cannot grab the first on the Ivars set to ensure 385 // deterministic output. 386 const ObjCIvarDecl *FirstIvarDecl = 0; 387 const ObjCInterfaceDecl *InterfaceD = ImplD->getClassInterface(); 388 389 // Collect ivars declared in this class, its extensions and its implementation 390 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(InterfaceD); 391 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv; 392 Iv= Iv->getNextIvar()) 393 trackIvar(Iv, Ivars, &FirstIvarDecl); 394 395 // Construct Property/Property Accessor to Ivar maps to assist checking if an 396 // ivar which is backing a property has been reset. 397 MethToIvarMapTy PropSetterToIvarMap; 398 MethToIvarMapTy PropGetterToIvarMap; 399 PropToIvarMapTy PropertyToIvarMap; 400 IvarToPropMapTy IvarToPopertyMap; 401 402 ObjCInterfaceDecl::PropertyMap PropMap; 403 ObjCInterfaceDecl::PropertyDeclOrder PropOrder; 404 InterfaceD->collectPropertiesToImplement(PropMap, PropOrder); 405 406 for (ObjCInterfaceDecl::PropertyMap::iterator 407 I = PropMap.begin(), E = PropMap.end(); I != E; ++I) { 408 const ObjCPropertyDecl *PD = I->second; 409 410 const ObjCIvarDecl *ID = findPropertyBackingIvar(PD, InterfaceD, Ivars, 411 &FirstIvarDecl); 412 if (!ID) 413 continue; 414 415 // Store the mappings. 416 PD = cast<ObjCPropertyDecl>(PD->getCanonicalDecl()); 417 PropertyToIvarMap[PD] = ID; 418 IvarToPopertyMap[ID] = PD; 419 420 // Find the setter and the getter. 421 const ObjCMethodDecl *SetterD = PD->getSetterMethodDecl(); 422 if (SetterD) { 423 SetterD = cast<ObjCMethodDecl>(SetterD->getCanonicalDecl()); 424 PropSetterToIvarMap[SetterD] = ID; 425 } 426 427 const ObjCMethodDecl *GetterD = PD->getGetterMethodDecl(); 428 if (GetterD) { 429 GetterD = cast<ObjCMethodDecl>(GetterD->getCanonicalDecl()); 430 PropGetterToIvarMap[GetterD] = ID; 431 } 432 } 433 434 // If no ivars need invalidation, there is nothing to check here. 435 if (Ivars.empty()) 436 return; 437 438 // Find all partial invalidation methods. 439 InvalidationInfo PartialInfo; 440 containsInvalidationMethod(InterfaceD, PartialInfo, /*LookForPartial*/ true); 441 442 // Remove ivars invalidated by the partial invalidation methods. They do not 443 // need to be invalidated in the regular invalidation methods. 444 bool AtImplementationContainsAtLeastOnePartialInvalidationMethod = false; 445 for (MethodSet::iterator 446 I = PartialInfo.InvalidationMethods.begin(), 447 E = PartialInfo.InvalidationMethods.end(); I != E; ++I) { 448 const ObjCMethodDecl *InterfD = *I; 449 450 // Get the corresponding method in the @implementation. 451 const ObjCMethodDecl *D = ImplD->getMethod(InterfD->getSelector(), 452 InterfD->isInstanceMethod()); 453 if (D && D->hasBody()) { 454 AtImplementationContainsAtLeastOnePartialInvalidationMethod = true; 455 456 bool CalledAnotherInvalidationMethod = false; 457 // The MethodCrowler is going to remove the invalidated ivars. 458 MethodCrawler(Ivars, 459 CalledAnotherInvalidationMethod, 460 PropSetterToIvarMap, 461 PropGetterToIvarMap, 462 PropertyToIvarMap, 463 BR.getContext()).VisitStmt(D->getBody()); 464 // If another invalidation method was called, trust that full invalidation 465 // has occurred. 466 if (CalledAnotherInvalidationMethod) 467 Ivars.clear(); 468 } 469 } 470 471 // If all ivars have been invalidated by partial invalidators, there is 472 // nothing to check here. 473 if (Ivars.empty()) 474 return; 475 476 // Find all invalidation methods in this @interface declaration and parents. 477 InvalidationInfo Info; 478 containsInvalidationMethod(InterfaceD, Info, /*LookForPartial*/ false); 479 480 // Report an error in case none of the invalidation methods are declared. 481 if (!Info.needsInvalidation() && !PartialInfo.needsInvalidation()) { 482 if (Filter.check_MissingInvalidationMethod) 483 reportNoInvalidationMethod(Filter.checkName_MissingInvalidationMethod, 484 FirstIvarDecl, IvarToPopertyMap, InterfaceD, 485 /*MissingDeclaration*/ true); 486 // If there are no invalidation methods, there is no ivar validation work 487 // to be done. 488 return; 489 } 490 491 // Only check if Ivars are invalidated when InstanceVariableInvalidation 492 // has been requested. 493 if (!Filter.check_InstanceVariableInvalidation) 494 return; 495 496 // Check that all ivars are invalidated by the invalidation methods. 497 bool AtImplementationContainsAtLeastOneInvalidationMethod = false; 498 for (MethodSet::iterator I = Info.InvalidationMethods.begin(), 499 E = Info.InvalidationMethods.end(); I != E; ++I) { 500 const ObjCMethodDecl *InterfD = *I; 501 502 // Get the corresponding method in the @implementation. 503 const ObjCMethodDecl *D = ImplD->getMethod(InterfD->getSelector(), 504 InterfD->isInstanceMethod()); 505 if (D && D->hasBody()) { 506 AtImplementationContainsAtLeastOneInvalidationMethod = true; 507 508 // Get a copy of ivars needing invalidation. 509 IvarSet IvarsI = Ivars; 510 511 bool CalledAnotherInvalidationMethod = false; 512 MethodCrawler(IvarsI, 513 CalledAnotherInvalidationMethod, 514 PropSetterToIvarMap, 515 PropGetterToIvarMap, 516 PropertyToIvarMap, 517 BR.getContext()).VisitStmt(D->getBody()); 518 // If another invalidation method was called, trust that full invalidation 519 // has occurred. 520 if (CalledAnotherInvalidationMethod) 521 continue; 522 523 // Warn on the ivars that were not invalidated by the method. 524 for (IvarSet::const_iterator 525 I = IvarsI.begin(), E = IvarsI.end(); I != E; ++I) 526 reportIvarNeedsInvalidation(I->first, IvarToPopertyMap, D); 527 } 528 } 529 530 // Report an error in case none of the invalidation methods are implemented. 531 if (!AtImplementationContainsAtLeastOneInvalidationMethod) { 532 if (AtImplementationContainsAtLeastOnePartialInvalidationMethod) { 533 // Warn on the ivars that were not invalidated by the prrtial 534 // invalidation methods. 535 for (IvarSet::const_iterator 536 I = Ivars.begin(), E = Ivars.end(); I != E; ++I) 537 reportIvarNeedsInvalidation(I->first, IvarToPopertyMap, 0); 538 } else { 539 // Otherwise, no invalidation methods were implemented. 540 reportNoInvalidationMethod(Filter.checkName_InstanceVariableInvalidation, 541 FirstIvarDecl, IvarToPopertyMap, InterfaceD, 542 /*MissingDeclaration*/ false); 543 } 544 } 545 } 546 547 void IvarInvalidationCheckerImpl::reportNoInvalidationMethod( 548 CheckName CheckName, const ObjCIvarDecl *FirstIvarDecl, 549 const IvarToPropMapTy &IvarToPopertyMap, 550 const ObjCInterfaceDecl *InterfaceD, bool MissingDeclaration) const { 551 SmallString<128> sbuf; 552 llvm::raw_svector_ostream os(sbuf); 553 assert(FirstIvarDecl); 554 printIvar(os, FirstIvarDecl, IvarToPopertyMap); 555 os << "needs to be invalidated; "; 556 if (MissingDeclaration) 557 os << "no invalidation method is declared for "; 558 else 559 os << "no invalidation method is defined in the @implementation for "; 560 os << InterfaceD->getName(); 561 562 PathDiagnosticLocation IvarDecLocation = 563 PathDiagnosticLocation::createBegin(FirstIvarDecl, BR.getSourceManager()); 564 565 BR.EmitBasicReport(FirstIvarDecl, CheckName, "Incomplete invalidation", 566 categories::CoreFoundationObjectiveC, os.str(), 567 IvarDecLocation); 568 } 569 570 void IvarInvalidationCheckerImpl:: 571 reportIvarNeedsInvalidation(const ObjCIvarDecl *IvarD, 572 const IvarToPropMapTy &IvarToPopertyMap, 573 const ObjCMethodDecl *MethodD) const { 574 SmallString<128> sbuf; 575 llvm::raw_svector_ostream os(sbuf); 576 printIvar(os, IvarD, IvarToPopertyMap); 577 os << "needs to be invalidated or set to nil"; 578 if (MethodD) { 579 PathDiagnosticLocation MethodDecLocation = 580 PathDiagnosticLocation::createEnd(MethodD->getBody(), 581 BR.getSourceManager(), 582 Mgr.getAnalysisDeclContext(MethodD)); 583 BR.EmitBasicReport(MethodD, Filter.checkName_InstanceVariableInvalidation, 584 "Incomplete invalidation", 585 categories::CoreFoundationObjectiveC, os.str(), 586 MethodDecLocation); 587 } else { 588 BR.EmitBasicReport( 589 IvarD, Filter.checkName_InstanceVariableInvalidation, 590 "Incomplete invalidation", categories::CoreFoundationObjectiveC, 591 os.str(), 592 PathDiagnosticLocation::createBegin(IvarD, BR.getSourceManager())); 593 } 594 } 595 596 void IvarInvalidationCheckerImpl::MethodCrawler::markInvalidated( 597 const ObjCIvarDecl *Iv) { 598 IvarSet::iterator I = IVars.find(Iv); 599 if (I != IVars.end()) { 600 // If InvalidationMethod is present, we are processing the message send and 601 // should ensure we are invalidating with the appropriate method, 602 // otherwise, we are processing setting to 'nil'. 603 if (!InvalidationMethod || 604 (InvalidationMethod && I->second.hasMethod(InvalidationMethod))) 605 IVars.erase(I); 606 } 607 } 608 609 const Expr *IvarInvalidationCheckerImpl::MethodCrawler::peel(const Expr *E) const { 610 E = E->IgnoreParenCasts(); 611 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 612 E = POE->getSyntacticForm()->IgnoreParenCasts(); 613 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) 614 E = OVE->getSourceExpr()->IgnoreParenCasts(); 615 return E; 616 } 617 618 void IvarInvalidationCheckerImpl::MethodCrawler::checkObjCIvarRefExpr( 619 const ObjCIvarRefExpr *IvarRef) { 620 if (const Decl *D = IvarRef->getDecl()) 621 markInvalidated(cast<ObjCIvarDecl>(D->getCanonicalDecl())); 622 } 623 624 void IvarInvalidationCheckerImpl::MethodCrawler::checkObjCMessageExpr( 625 const ObjCMessageExpr *ME) { 626 const ObjCMethodDecl *MD = ME->getMethodDecl(); 627 if (MD) { 628 MD = cast<ObjCMethodDecl>(MD->getCanonicalDecl()); 629 MethToIvarMapTy::const_iterator IvI = PropertyGetterToIvarMap.find(MD); 630 if (IvI != PropertyGetterToIvarMap.end()) 631 markInvalidated(IvI->second); 632 } 633 } 634 635 void IvarInvalidationCheckerImpl::MethodCrawler::checkObjCPropertyRefExpr( 636 const ObjCPropertyRefExpr *PA) { 637 638 if (PA->isExplicitProperty()) { 639 const ObjCPropertyDecl *PD = PA->getExplicitProperty(); 640 if (PD) { 641 PD = cast<ObjCPropertyDecl>(PD->getCanonicalDecl()); 642 PropToIvarMapTy::const_iterator IvI = PropertyToIvarMap.find(PD); 643 if (IvI != PropertyToIvarMap.end()) 644 markInvalidated(IvI->second); 645 return; 646 } 647 } 648 649 if (PA->isImplicitProperty()) { 650 const ObjCMethodDecl *MD = PA->getImplicitPropertySetter(); 651 if (MD) { 652 MD = cast<ObjCMethodDecl>(MD->getCanonicalDecl()); 653 MethToIvarMapTy::const_iterator IvI =PropertyGetterToIvarMap.find(MD); 654 if (IvI != PropertyGetterToIvarMap.end()) 655 markInvalidated(IvI->second); 656 return; 657 } 658 } 659 } 660 661 bool IvarInvalidationCheckerImpl::MethodCrawler::isZero(const Expr *E) const { 662 E = peel(E); 663 664 return (E->isNullPointerConstant(Ctx, Expr::NPC_ValueDependentIsNotNull) 665 != Expr::NPCK_NotNull); 666 } 667 668 void IvarInvalidationCheckerImpl::MethodCrawler::check(const Expr *E) { 669 E = peel(E); 670 671 if (const ObjCIvarRefExpr *IvarRef = dyn_cast<ObjCIvarRefExpr>(E)) { 672 checkObjCIvarRefExpr(IvarRef); 673 return; 674 } 675 676 if (const ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E)) { 677 checkObjCPropertyRefExpr(PropRef); 678 return; 679 } 680 681 if (const ObjCMessageExpr *MsgExpr = dyn_cast<ObjCMessageExpr>(E)) { 682 checkObjCMessageExpr(MsgExpr); 683 return; 684 } 685 } 686 687 void IvarInvalidationCheckerImpl::MethodCrawler::VisitBinaryOperator( 688 const BinaryOperator *BO) { 689 VisitStmt(BO); 690 691 // Do we assign/compare against zero? If yes, check the variable we are 692 // assigning to. 693 BinaryOperatorKind Opcode = BO->getOpcode(); 694 if (Opcode != BO_Assign && 695 Opcode != BO_EQ && 696 Opcode != BO_NE) 697 return; 698 699 if (isZero(BO->getRHS())) { 700 check(BO->getLHS()); 701 return; 702 } 703 704 if (Opcode != BO_Assign && isZero(BO->getLHS())) { 705 check(BO->getRHS()); 706 return; 707 } 708 } 709 710 void IvarInvalidationCheckerImpl::MethodCrawler::VisitObjCMessageExpr( 711 const ObjCMessageExpr *ME) { 712 const ObjCMethodDecl *MD = ME->getMethodDecl(); 713 const Expr *Receiver = ME->getInstanceReceiver(); 714 715 // Stop if we are calling '[self invalidate]'. 716 if (Receiver && isInvalidationMethod(MD, /*LookForPartial*/ false)) 717 if (Receiver->isObjCSelfExpr()) { 718 CalledAnotherInvalidationMethod = true; 719 return; 720 } 721 722 // Check if we call a setter and set the property to 'nil'. 723 if (MD && (ME->getNumArgs() == 1) && isZero(ME->getArg(0))) { 724 MD = cast<ObjCMethodDecl>(MD->getCanonicalDecl()); 725 MethToIvarMapTy::const_iterator IvI = PropertySetterToIvarMap.find(MD); 726 if (IvI != PropertySetterToIvarMap.end()) { 727 markInvalidated(IvI->second); 728 return; 729 } 730 } 731 732 // Check if we call the 'invalidation' routine on the ivar. 733 if (Receiver) { 734 InvalidationMethod = MD; 735 check(Receiver->IgnoreParenCasts()); 736 InvalidationMethod = 0; 737 } 738 739 VisitStmt(ME); 740 } 741 } 742 743 // Register the checkers. 744 namespace { 745 746 class IvarInvalidationChecker : 747 public Checker<check::ASTDecl<ObjCImplementationDecl> > { 748 public: 749 ChecksFilter Filter; 750 public: 751 void checkASTDecl(const ObjCImplementationDecl *D, AnalysisManager& Mgr, 752 BugReporter &BR) const { 753 IvarInvalidationCheckerImpl Walker(Mgr, BR, Filter); 754 Walker.visit(D); 755 } 756 }; 757 } 758 759 #define REGISTER_CHECKER(name) \ 760 void ento::register##name(CheckerManager &mgr) { \ 761 IvarInvalidationChecker *checker = \ 762 mgr.registerChecker<IvarInvalidationChecker>(); \ 763 checker->Filter.check_##name = true; \ 764 checker->Filter.checkName_##name = mgr.getCurrentCheckName(); \ 765 } 766 767 REGISTER_CHECKER(InstanceVariableInvalidation) 768 REGISTER_CHECKER(MissingInvalidationMethod) 769 770