1 //== BasicObjCFoundationChecks.cpp - Simple Apple-Foundation checks -*- C++ -*--
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines BasicObjCFoundationChecks, a class that encapsulates
11 // a set of simple checks to run on Objective-C code using Apple's Foundation
14 //===----------------------------------------------------------------------===//
16 #include "ClangSACheckers.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/Expr.h"
20 #include "clang/AST/ExprObjC.h"
21 #include "clang/AST/StmtObjC.h"
22 #include "clang/Analysis/DomainSpecific/CocoaConventions.h"
23 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
24 #include "clang/StaticAnalyzer/Core/Checker.h"
25 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
26 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
27 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
28 #include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
29 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
30 #include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
31 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
32 #include "llvm/ADT/SmallString.h"
33 #include "llvm/ADT/StringMap.h"
34 #include "llvm/Support/raw_ostream.h"
36 using namespace clang;
40 class APIMisuse : public BugType {
42 APIMisuse(const char* name) : BugType(name, "API Misuse (Apple)") {}
44 } // end anonymous namespace
46 //===----------------------------------------------------------------------===//
48 //===----------------------------------------------------------------------===//
50 static StringRef GetReceiverInterfaceName(const ObjCMethodCall &msg) {
51 if (const ObjCInterfaceDecl *ID = msg.getReceiverInterface())
52 return ID->getIdentifier()->getName();
56 enum FoundationClass {
67 static FoundationClass findKnownClass(const ObjCInterfaceDecl *ID,
68 bool IncludeSuperclasses = true) {
69 static llvm::StringMap<FoundationClass> Classes;
70 if (Classes.empty()) {
71 Classes["NSArray"] = FC_NSArray;
72 Classes["NSDictionary"] = FC_NSDictionary;
73 Classes["NSEnumerator"] = FC_NSEnumerator;
74 Classes["NSNull"] = FC_NSNull;
75 Classes["NSOrderedSet"] = FC_NSOrderedSet;
76 Classes["NSSet"] = FC_NSSet;
77 Classes["NSString"] = FC_NSString;
80 // FIXME: Should we cache this at all?
81 FoundationClass result = Classes.lookup(ID->getIdentifier()->getName());
82 if (result == FC_None && IncludeSuperclasses)
83 if (const ObjCInterfaceDecl *Super = ID->getSuperClass())
84 return findKnownClass(Super);
89 //===----------------------------------------------------------------------===//
90 // NilArgChecker - Check for prohibited nil arguments to ObjC method calls.
91 //===----------------------------------------------------------------------===//
94 class NilArgChecker : public Checker<check::PreObjCMessage,
95 check::PostStmt<ObjCDictionaryLiteral>,
96 check::PostStmt<ObjCArrayLiteral> > {
97 mutable OwningPtr<APIMisuse> BT;
99 void warnIfNilExpr(const Expr *E,
101 CheckerContext &C) const;
103 void warnIfNilArg(CheckerContext &C,
104 const ObjCMethodCall &msg, unsigned Arg,
105 FoundationClass Class,
106 bool CanBeSubscript = false) const;
108 void generateBugReport(ExplodedNode *N,
112 CheckerContext &C) const;
115 void checkPreObjCMessage(const ObjCMethodCall &M, CheckerContext &C) const;
116 void checkPostStmt(const ObjCDictionaryLiteral *DL,
117 CheckerContext &C) const;
118 void checkPostStmt(const ObjCArrayLiteral *AL,
119 CheckerContext &C) const;
123 void NilArgChecker::warnIfNilExpr(const Expr *E,
125 CheckerContext &C) const {
126 ProgramStateRef State = C.getState();
127 if (State->isNull(C.getSVal(E)).isConstrainedTrue()) {
129 if (ExplodedNode *N = C.generateSink()) {
130 generateBugReport(N, Msg, E->getSourceRange(), E, C);
136 void NilArgChecker::warnIfNilArg(CheckerContext &C,
137 const ObjCMethodCall &msg,
139 FoundationClass Class,
140 bool CanBeSubscript) const {
141 // Check if the argument is nil.
142 ProgramStateRef State = C.getState();
143 if (!State->isNull(msg.getArgSVal(Arg)).isConstrainedTrue())
146 if (ExplodedNode *N = C.generateSink()) {
147 SmallString<128> sbuf;
148 llvm::raw_svector_ostream os(sbuf);
150 if (CanBeSubscript && msg.getMessageKind() == OCM_Subscript) {
152 if (Class == FC_NSArray) {
153 os << "Array element cannot be nil";
154 } else if (Class == FC_NSDictionary) {
156 os << "Value stored into '";
157 os << GetReceiverInterfaceName(msg) << "' cannot be nil";
160 os << "'"<< GetReceiverInterfaceName(msg) << "' key cannot be nil";
163 llvm_unreachable("Missing foundation class for the subscript expr");
166 if (Class == FC_NSDictionary) {
168 os << "Value argument ";
171 os << "Key argument ";
173 os << "to '" << msg.getSelector().getAsString() << "' cannot be nil";
175 os << "Argument to '" << GetReceiverInterfaceName(msg) << "' method '"
176 << msg.getSelector().getAsString() << "' cannot be nil";
180 generateBugReport(N, os.str(), msg.getArgSourceRange(Arg),
181 msg.getArgExpr(Arg), C);
185 void NilArgChecker::generateBugReport(ExplodedNode *N,
189 CheckerContext &C) const {
191 BT.reset(new APIMisuse("nil argument"));
193 BugReport *R = new BugReport(*BT, Msg, N);
195 bugreporter::trackNullOrUndefValue(N, E, *R);
199 void NilArgChecker::checkPreObjCMessage(const ObjCMethodCall &msg,
200 CheckerContext &C) const {
201 const ObjCInterfaceDecl *ID = msg.getReceiverInterface();
205 FoundationClass Class = findKnownClass(ID);
207 static const unsigned InvalidArgIndex = UINT_MAX;
208 unsigned Arg = InvalidArgIndex;
209 bool CanBeSubscript = false;
211 if (Class == FC_NSString) {
212 Selector S = msg.getSelector();
214 if (S.isUnarySelector())
217 // FIXME: This is going to be really slow doing these checks with
218 // lexical comparisons.
220 std::string NameStr = S.getAsString();
221 StringRef Name(NameStr);
222 assert(!Name.empty());
224 // FIXME: Checking for initWithFormat: will not work in most cases
225 // yet because [NSString alloc] returns id, not NSString*. We will
226 // need support for tracking expected-type information in the analyzer
227 // to find these errors.
228 if (Name == "caseInsensitiveCompare:" ||
229 Name == "compare:" ||
230 Name == "compare:options:" ||
231 Name == "compare:options:range:" ||
232 Name == "compare:options:range:locale:" ||
233 Name == "componentsSeparatedByCharactersInSet:" ||
234 Name == "initWithFormat:") {
237 } else if (Class == FC_NSArray) {
238 Selector S = msg.getSelector();
240 if (S.isUnarySelector())
243 if (S.getNameForSlot(0).equals("addObject")) {
245 } else if (S.getNameForSlot(0).equals("insertObject") &&
246 S.getNameForSlot(1).equals("atIndex")) {
248 } else if (S.getNameForSlot(0).equals("replaceObjectAtIndex") &&
249 S.getNameForSlot(1).equals("withObject")) {
251 } else if (S.getNameForSlot(0).equals("setObject") &&
252 S.getNameForSlot(1).equals("atIndexedSubscript")) {
254 CanBeSubscript = true;
255 } else if (S.getNameForSlot(0).equals("arrayByAddingObject")) {
258 } else if (Class == FC_NSDictionary) {
259 Selector S = msg.getSelector();
261 if (S.isUnarySelector())
264 if (S.getNameForSlot(0).equals("dictionaryWithObject") &&
265 S.getNameForSlot(1).equals("forKey")) {
267 warnIfNilArg(C, msg, /* Arg */1, Class);
268 } else if (S.getNameForSlot(0).equals("setObject") &&
269 S.getNameForSlot(1).equals("forKey")) {
271 warnIfNilArg(C, msg, /* Arg */1, Class);
272 } else if (S.getNameForSlot(0).equals("setObject") &&
273 S.getNameForSlot(1).equals("forKeyedSubscript")) {
274 CanBeSubscript = true;
276 warnIfNilArg(C, msg, /* Arg */1, Class, CanBeSubscript);
277 } else if (S.getNameForSlot(0).equals("removeObjectForKey")) {
282 // If argument is '0', report a warning.
283 if ((Arg != InvalidArgIndex))
284 warnIfNilArg(C, msg, Arg, Class, CanBeSubscript);
288 void NilArgChecker::checkPostStmt(const ObjCArrayLiteral *AL,
289 CheckerContext &C) const {
290 unsigned NumOfElements = AL->getNumElements();
291 for (unsigned i = 0; i < NumOfElements; ++i) {
292 warnIfNilExpr(AL->getElement(i), "Array element cannot be nil", C);
296 void NilArgChecker::checkPostStmt(const ObjCDictionaryLiteral *DL,
297 CheckerContext &C) const {
298 unsigned NumOfElements = DL->getNumElements();
299 for (unsigned i = 0; i < NumOfElements; ++i) {
300 ObjCDictionaryElement Element = DL->getKeyValueElement(i);
301 warnIfNilExpr(Element.Key, "Dictionary key cannot be nil", C);
302 warnIfNilExpr(Element.Value, "Dictionary value cannot be nil", C);
306 //===----------------------------------------------------------------------===//
308 //===----------------------------------------------------------------------===//
311 class CFNumberCreateChecker : public Checker< check::PreStmt<CallExpr> > {
312 mutable OwningPtr<APIMisuse> BT;
313 mutable IdentifierInfo* II;
315 CFNumberCreateChecker() : II(0) {}
317 void checkPreStmt(const CallExpr *CE, CheckerContext &C) const;
320 void EmitError(const TypedRegion* R, const Expr *Ex,
321 uint64_t SourceSize, uint64_t TargetSize, uint64_t NumberKind);
323 } // end anonymous namespace
326 kCFNumberSInt8Type = 1,
327 kCFNumberSInt16Type = 2,
328 kCFNumberSInt32Type = 3,
329 kCFNumberSInt64Type = 4,
330 kCFNumberFloat32Type = 5,
331 kCFNumberFloat64Type = 6,
332 kCFNumberCharType = 7,
333 kCFNumberShortType = 8,
334 kCFNumberIntType = 9,
335 kCFNumberLongType = 10,
336 kCFNumberLongLongType = 11,
337 kCFNumberFloatType = 12,
338 kCFNumberDoubleType = 13,
339 kCFNumberCFIndexType = 14,
340 kCFNumberNSIntegerType = 15,
341 kCFNumberCGFloatType = 16
344 static Optional<uint64_t> GetCFNumberSize(ASTContext &Ctx, uint64_t i) {
345 static const unsigned char FixedSize[] = { 8, 16, 32, 64, 32, 64 };
347 if (i < kCFNumberCharType)
348 return FixedSize[i-1];
353 case kCFNumberCharType: T = Ctx.CharTy; break;
354 case kCFNumberShortType: T = Ctx.ShortTy; break;
355 case kCFNumberIntType: T = Ctx.IntTy; break;
356 case kCFNumberLongType: T = Ctx.LongTy; break;
357 case kCFNumberLongLongType: T = Ctx.LongLongTy; break;
358 case kCFNumberFloatType: T = Ctx.FloatTy; break;
359 case kCFNumberDoubleType: T = Ctx.DoubleTy; break;
360 case kCFNumberCFIndexType:
361 case kCFNumberNSIntegerType:
362 case kCFNumberCGFloatType:
363 // FIXME: We need a way to map from names to Type*.
368 return Ctx.getTypeSize(T);
372 static const char* GetCFNumberTypeStr(uint64_t i) {
373 static const char* Names[] = {
374 "kCFNumberSInt8Type",
375 "kCFNumberSInt16Type",
376 "kCFNumberSInt32Type",
377 "kCFNumberSInt64Type",
378 "kCFNumberFloat32Type",
379 "kCFNumberFloat64Type",
381 "kCFNumberShortType",
384 "kCFNumberLongLongType",
385 "kCFNumberFloatType",
386 "kCFNumberDoubleType",
387 "kCFNumberCFIndexType",
388 "kCFNumberNSIntegerType",
389 "kCFNumberCGFloatType"
392 return i <= kCFNumberCGFloatType ? Names[i-1] : "Invalid CFNumberType";
396 void CFNumberCreateChecker::checkPreStmt(const CallExpr *CE,
397 CheckerContext &C) const {
398 ProgramStateRef state = C.getState();
399 const FunctionDecl *FD = C.getCalleeDecl(CE);
403 ASTContext &Ctx = C.getASTContext();
405 II = &Ctx.Idents.get("CFNumberCreate");
407 if (FD->getIdentifier() != II || CE->getNumArgs() != 3)
410 // Get the value of the "theType" argument.
411 const LocationContext *LCtx = C.getLocationContext();
412 SVal TheTypeVal = state->getSVal(CE->getArg(1), LCtx);
414 // FIXME: We really should allow ranges of valid theType values, and
415 // bifurcate the state appropriately.
416 Optional<nonloc::ConcreteInt> V = TheTypeVal.getAs<nonloc::ConcreteInt>();
420 uint64_t NumberKind = V->getValue().getLimitedValue();
421 Optional<uint64_t> OptTargetSize = GetCFNumberSize(Ctx, NumberKind);
423 // FIXME: In some cases we can emit an error.
427 uint64_t TargetSize = *OptTargetSize;
429 // Look at the value of the integer being passed by reference. Essentially
430 // we want to catch cases where the value passed in is not equal to the
431 // size of the type being created.
432 SVal TheValueExpr = state->getSVal(CE->getArg(2), LCtx);
434 // FIXME: Eventually we should handle arbitrary locations. We can do this
435 // by having an enhanced memory model that does low-level typing.
436 Optional<loc::MemRegionVal> LV = TheValueExpr.getAs<loc::MemRegionVal>();
440 const TypedValueRegion* R = dyn_cast<TypedValueRegion>(LV->stripCasts());
444 QualType T = Ctx.getCanonicalType(R->getValueType());
446 // FIXME: If the pointee isn't an integer type, should we flag a warning?
447 // People can do weird stuff with pointers.
449 if (!T->isIntegralOrEnumerationType())
452 uint64_t SourceSize = Ctx.getTypeSize(T);
454 // CHECK: is SourceSize == TargetSize
455 if (SourceSize == TargetSize)
458 // Generate an error. Only generate a sink if 'SourceSize < TargetSize';
459 // otherwise generate a regular node.
461 // FIXME: We can actually create an abstract "CFNumber" object that has
462 // the bits initialized to the provided values.
464 if (ExplodedNode *N = SourceSize < TargetSize ? C.generateSink()
465 : C.addTransition()) {
466 SmallString<128> sbuf;
467 llvm::raw_svector_ostream os(sbuf);
469 os << (SourceSize == 8 ? "An " : "A ")
470 << SourceSize << " bit integer is used to initialize a CFNumber "
471 "object that represents "
472 << (TargetSize == 8 ? "an " : "a ")
473 << TargetSize << " bit integer. ";
475 if (SourceSize < TargetSize)
476 os << (TargetSize - SourceSize)
477 << " bits of the CFNumber value will be garbage." ;
479 os << (SourceSize - TargetSize)
480 << " bits of the input integer will be lost.";
483 BT.reset(new APIMisuse("Bad use of CFNumberCreate"));
485 BugReport *report = new BugReport(*BT, os.str(), N);
486 report->addRange(CE->getArg(2)->getSourceRange());
487 C.emitReport(report);
491 //===----------------------------------------------------------------------===//
492 // CFRetain/CFRelease/CFMakeCollectable checking for null arguments.
493 //===----------------------------------------------------------------------===//
496 class CFRetainReleaseChecker : public Checker< check::PreStmt<CallExpr> > {
497 mutable OwningPtr<APIMisuse> BT;
498 mutable IdentifierInfo *Retain, *Release, *MakeCollectable;
500 CFRetainReleaseChecker(): Retain(0), Release(0), MakeCollectable(0) {}
501 void checkPreStmt(const CallExpr *CE, CheckerContext &C) const;
503 } // end anonymous namespace
506 void CFRetainReleaseChecker::checkPreStmt(const CallExpr *CE,
507 CheckerContext &C) const {
508 // If the CallExpr doesn't have exactly 1 argument just give up checking.
509 if (CE->getNumArgs() != 1)
512 ProgramStateRef state = C.getState();
513 const FunctionDecl *FD = C.getCalleeDecl(CE);
518 ASTContext &Ctx = C.getASTContext();
519 Retain = &Ctx.Idents.get("CFRetain");
520 Release = &Ctx.Idents.get("CFRelease");
521 MakeCollectable = &Ctx.Idents.get("CFMakeCollectable");
523 new APIMisuse("null passed to CFRetain/CFRelease/CFMakeCollectable"));
526 // Check if we called CFRetain/CFRelease/CFMakeCollectable.
527 const IdentifierInfo *FuncII = FD->getIdentifier();
528 if (!(FuncII == Retain || FuncII == Release || FuncII == MakeCollectable))
531 // FIXME: The rest of this just checks that the argument is non-null.
532 // It should probably be refactored and combined with NonNullParamChecker.
534 // Get the argument's value.
535 const Expr *Arg = CE->getArg(0);
536 SVal ArgVal = state->getSVal(Arg, C.getLocationContext());
537 Optional<DefinedSVal> DefArgVal = ArgVal.getAs<DefinedSVal>();
542 SValBuilder &svalBuilder = C.getSValBuilder();
544 svalBuilder.makeZeroVal(Arg->getType()).castAs<DefinedSVal>();
546 // Make an expression asserting that they're equal.
547 DefinedOrUnknownSVal ArgIsNull = svalBuilder.evalEQ(state, zero, *DefArgVal);
550 ProgramStateRef stateTrue, stateFalse;
551 llvm::tie(stateTrue, stateFalse) = state->assume(ArgIsNull);
553 if (stateTrue && !stateFalse) {
554 ExplodedNode *N = C.generateSink(stateTrue);
558 const char *description;
559 if (FuncII == Retain)
560 description = "Null pointer argument in call to CFRetain";
561 else if (FuncII == Release)
562 description = "Null pointer argument in call to CFRelease";
563 else if (FuncII == MakeCollectable)
564 description = "Null pointer argument in call to CFMakeCollectable";
566 llvm_unreachable("impossible case");
568 BugReport *report = new BugReport(*BT, description, N);
569 report->addRange(Arg->getSourceRange());
570 bugreporter::trackNullOrUndefValue(N, Arg, *report);
571 C.emitReport(report);
575 // From here on, we know the argument is non-null.
576 C.addTransition(stateFalse);
579 //===----------------------------------------------------------------------===//
580 // Check for sending 'retain', 'release', or 'autorelease' directly to a Class.
581 //===----------------------------------------------------------------------===//
584 class ClassReleaseChecker : public Checker<check::PreObjCMessage> {
585 mutable Selector releaseS;
586 mutable Selector retainS;
587 mutable Selector autoreleaseS;
588 mutable Selector drainS;
589 mutable OwningPtr<BugType> BT;
592 void checkPreObjCMessage(const ObjCMethodCall &msg, CheckerContext &C) const;
596 void ClassReleaseChecker::checkPreObjCMessage(const ObjCMethodCall &msg,
597 CheckerContext &C) const {
600 BT.reset(new APIMisuse("message incorrectly sent to class instead of class "
603 ASTContext &Ctx = C.getASTContext();
604 releaseS = GetNullarySelector("release", Ctx);
605 retainS = GetNullarySelector("retain", Ctx);
606 autoreleaseS = GetNullarySelector("autorelease", Ctx);
607 drainS = GetNullarySelector("drain", Ctx);
610 if (msg.isInstanceMessage())
612 const ObjCInterfaceDecl *Class = msg.getReceiverInterface();
615 Selector S = msg.getSelector();
616 if (!(S == releaseS || S == retainS || S == autoreleaseS || S == drainS))
619 if (ExplodedNode *N = C.addTransition()) {
620 SmallString<200> buf;
621 llvm::raw_svector_ostream os(buf);
623 os << "The '" << S.getAsString() << "' message should be sent to instances "
624 "of class '" << Class->getName()
625 << "' and not the class directly";
627 BugReport *report = new BugReport(*BT, os.str(), N);
628 report->addRange(msg.getSourceRange());
629 C.emitReport(report);
633 //===----------------------------------------------------------------------===//
634 // Check for passing non-Objective-C types to variadic methods that expect
635 // only Objective-C types.
636 //===----------------------------------------------------------------------===//
639 class VariadicMethodTypeChecker : public Checker<check::PreObjCMessage> {
640 mutable Selector arrayWithObjectsS;
641 mutable Selector dictionaryWithObjectsAndKeysS;
642 mutable Selector setWithObjectsS;
643 mutable Selector orderedSetWithObjectsS;
644 mutable Selector initWithObjectsS;
645 mutable Selector initWithObjectsAndKeysS;
646 mutable OwningPtr<BugType> BT;
648 bool isVariadicMessage(const ObjCMethodCall &msg) const;
651 void checkPreObjCMessage(const ObjCMethodCall &msg, CheckerContext &C) const;
655 /// isVariadicMessage - Returns whether the given message is a variadic message,
656 /// where all arguments must be Objective-C types.
658 VariadicMethodTypeChecker::isVariadicMessage(const ObjCMethodCall &msg) const {
659 const ObjCMethodDecl *MD = msg.getDecl();
661 if (!MD || !MD->isVariadic() || isa<ObjCProtocolDecl>(MD->getDeclContext()))
664 Selector S = msg.getSelector();
666 if (msg.isInstanceMessage()) {
667 // FIXME: Ideally we'd look at the receiver interface here, but that's not
668 // useful for init, because alloc returns 'id'. In theory, this could lead
669 // to false positives, for example if there existed a class that had an
670 // initWithObjects: implementation that does accept non-Objective-C pointer
671 // types, but the chance of that happening is pretty small compared to the
672 // gains that this analysis gives.
673 const ObjCInterfaceDecl *Class = MD->getClassInterface();
675 switch (findKnownClass(Class)) {
677 case FC_NSOrderedSet:
679 return S == initWithObjectsS;
680 case FC_NSDictionary:
681 return S == initWithObjectsAndKeysS;
686 const ObjCInterfaceDecl *Class = msg.getReceiverInterface();
688 switch (findKnownClass(Class)) {
690 return S == arrayWithObjectsS;
691 case FC_NSOrderedSet:
692 return S == orderedSetWithObjectsS;
694 return S == setWithObjectsS;
695 case FC_NSDictionary:
696 return S == dictionaryWithObjectsAndKeysS;
703 void VariadicMethodTypeChecker::checkPreObjCMessage(const ObjCMethodCall &msg,
704 CheckerContext &C) const {
706 BT.reset(new APIMisuse("Arguments passed to variadic method aren't all "
707 "Objective-C pointer types"));
709 ASTContext &Ctx = C.getASTContext();
710 arrayWithObjectsS = GetUnarySelector("arrayWithObjects", Ctx);
711 dictionaryWithObjectsAndKeysS =
712 GetUnarySelector("dictionaryWithObjectsAndKeys", Ctx);
713 setWithObjectsS = GetUnarySelector("setWithObjects", Ctx);
714 orderedSetWithObjectsS = GetUnarySelector("orderedSetWithObjects", Ctx);
716 initWithObjectsS = GetUnarySelector("initWithObjects", Ctx);
717 initWithObjectsAndKeysS = GetUnarySelector("initWithObjectsAndKeys", Ctx);
720 if (!isVariadicMessage(msg))
723 // We are not interested in the selector arguments since they have
724 // well-defined types, so the compiler will issue a warning for them.
725 unsigned variadicArgsBegin = msg.getSelector().getNumArgs();
727 // We're not interested in the last argument since it has to be nil or the
728 // compiler would have issued a warning for it elsewhere.
729 unsigned variadicArgsEnd = msg.getNumArgs() - 1;
731 if (variadicArgsEnd <= variadicArgsBegin)
734 // Verify that all arguments have Objective-C types.
735 Optional<ExplodedNode*> errorNode;
736 ProgramStateRef state = C.getState();
738 for (unsigned I = variadicArgsBegin; I != variadicArgsEnd; ++I) {
739 QualType ArgTy = msg.getArgExpr(I)->getType();
740 if (ArgTy->isObjCObjectPointerType())
743 // Block pointers are treaded as Objective-C pointers.
744 if (ArgTy->isBlockPointerType())
747 // Ignore pointer constants.
748 if (msg.getArgSVal(I).getAs<loc::ConcreteInt>())
751 // Ignore pointer types annotated with 'NSObject' attribute.
752 if (C.getASTContext().isObjCNSObjectType(ArgTy))
755 // Ignore CF references, which can be toll-free bridged.
756 if (coreFoundation::isCFObjectRef(ArgTy))
759 // Generate only one error node to use for all bug reports.
760 if (!errorNode.hasValue())
761 errorNode = C.addTransition();
763 if (!errorNode.getValue())
766 SmallString<128> sbuf;
767 llvm::raw_svector_ostream os(sbuf);
769 StringRef TypeName = GetReceiverInterfaceName(msg);
770 if (!TypeName.empty())
771 os << "Argument to '" << TypeName << "' method '";
773 os << "Argument to method '";
775 os << msg.getSelector().getAsString()
776 << "' should be an Objective-C pointer type, not '";
777 ArgTy.print(os, C.getLangOpts());
780 BugReport *R = new BugReport(*BT, os.str(), errorNode.getValue());
781 R->addRange(msg.getArgSourceRange(I));
786 //===----------------------------------------------------------------------===//
787 // Improves the modeling of loops over Cocoa collections.
788 //===----------------------------------------------------------------------===//
790 // The map from container symbol to the container count symbol.
791 // We currently will remember the last countainer count symbol encountered.
792 REGISTER_MAP_WITH_PROGRAMSTATE(ContainerCountMap, SymbolRef, SymbolRef)
793 REGISTER_MAP_WITH_PROGRAMSTATE(ContainerNonEmptyMap, SymbolRef, bool)
796 class ObjCLoopChecker
797 : public Checker<check::PostStmt<ObjCForCollectionStmt>,
798 check::PostObjCMessage,
800 check::PointerEscape > {
801 mutable IdentifierInfo *CountSelectorII;
803 bool isCollectionCountMethod(const ObjCMethodCall &M,
804 CheckerContext &C) const;
807 ObjCLoopChecker() : CountSelectorII(0) {}
808 void checkPostStmt(const ObjCForCollectionStmt *FCS, CheckerContext &C) const;
809 void checkPostObjCMessage(const ObjCMethodCall &M, CheckerContext &C) const;
810 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
811 ProgramStateRef checkPointerEscape(ProgramStateRef State,
812 const InvalidatedSymbols &Escaped,
813 const CallEvent *Call,
814 PointerEscapeKind Kind) const;
818 static bool isKnownNonNilCollectionType(QualType T) {
819 const ObjCObjectPointerType *PT = T->getAs<ObjCObjectPointerType>();
823 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
827 switch (findKnownClass(ID)) {
829 case FC_NSDictionary:
830 case FC_NSEnumerator:
831 case FC_NSOrderedSet:
839 /// Assumes that the collection is non-nil.
841 /// If the collection is known to be nil, returns NULL to indicate an infeasible
843 static ProgramStateRef checkCollectionNonNil(CheckerContext &C,
844 ProgramStateRef State,
845 const ObjCForCollectionStmt *FCS) {
849 SVal CollectionVal = C.getSVal(FCS->getCollection());
850 Optional<DefinedSVal> KnownCollection = CollectionVal.getAs<DefinedSVal>();
851 if (!KnownCollection)
854 ProgramStateRef StNonNil, StNil;
855 llvm::tie(StNonNil, StNil) = State->assume(*KnownCollection);
856 if (StNil && !StNonNil) {
857 // The collection is nil. This path is infeasible.
864 /// Assumes that the collection elements are non-nil.
866 /// This only applies if the collection is one of those known not to contain
868 static ProgramStateRef checkElementNonNil(CheckerContext &C,
869 ProgramStateRef State,
870 const ObjCForCollectionStmt *FCS) {
874 // See if the collection is one where we /know/ the elements are non-nil.
875 if (!isKnownNonNilCollectionType(FCS->getCollection()->getType()))
878 const LocationContext *LCtx = C.getLocationContext();
879 const Stmt *Element = FCS->getElement();
881 // FIXME: Copied from ExprEngineObjC.
882 Optional<Loc> ElementLoc;
883 if (const DeclStmt *DS = dyn_cast<DeclStmt>(Element)) {
884 const VarDecl *ElemDecl = cast<VarDecl>(DS->getSingleDecl());
885 assert(ElemDecl->getInit() == 0);
886 ElementLoc = State->getLValue(ElemDecl, LCtx);
888 ElementLoc = State->getSVal(Element, LCtx).getAs<Loc>();
894 // Go ahead and assume the value is non-nil.
895 SVal Val = State->getSVal(*ElementLoc);
896 return State->assume(Val.castAs<DefinedOrUnknownSVal>(), true);
899 /// Returns NULL state if the collection is known to contain elements
900 /// (or is known not to contain elements if the Assumption parameter is false.)
901 static ProgramStateRef
902 assumeCollectionNonEmpty(CheckerContext &C, ProgramStateRef State,
903 SymbolRef CollectionS, bool Assumption) {
904 if (!State || !CollectionS)
907 const SymbolRef *CountS = State->get<ContainerCountMap>(CollectionS);
909 const bool *KnownNonEmpty = State->get<ContainerNonEmptyMap>(CollectionS);
911 return State->set<ContainerNonEmptyMap>(CollectionS, Assumption);
912 return (Assumption == *KnownNonEmpty) ? State : NULL;
915 SValBuilder &SvalBuilder = C.getSValBuilder();
916 SVal CountGreaterThanZeroVal =
917 SvalBuilder.evalBinOp(State, BO_GT,
918 nonloc::SymbolVal(*CountS),
919 SvalBuilder.makeIntVal(0, (*CountS)->getType()),
920 SvalBuilder.getConditionType());
921 Optional<DefinedSVal> CountGreaterThanZero =
922 CountGreaterThanZeroVal.getAs<DefinedSVal>();
923 if (!CountGreaterThanZero) {
924 // The SValBuilder cannot construct a valid SVal for this condition.
925 // This means we cannot properly reason about it.
929 return State->assume(*CountGreaterThanZero, Assumption);
932 static ProgramStateRef
933 assumeCollectionNonEmpty(CheckerContext &C, ProgramStateRef State,
934 const ObjCForCollectionStmt *FCS,
939 SymbolRef CollectionS =
940 State->getSVal(FCS->getCollection(), C.getLocationContext()).getAsSymbol();
941 return assumeCollectionNonEmpty(C, State, CollectionS, Assumption);
945 /// If the fist block edge is a back edge, we are reentering the loop.
946 static bool alreadyExecutedAtLeastOneLoopIteration(const ExplodedNode *N,
947 const ObjCForCollectionStmt *FCS) {
951 ProgramPoint P = N->getLocation();
952 if (Optional<BlockEdge> BE = P.getAs<BlockEdge>()) {
953 if (BE->getSrc()->getLoopTarget() == FCS)
958 // Keep looking for a block edge.
959 for (ExplodedNode::const_pred_iterator I = N->pred_begin(),
960 E = N->pred_end(); I != E; ++I) {
961 if (alreadyExecutedAtLeastOneLoopIteration(*I, FCS))
968 void ObjCLoopChecker::checkPostStmt(const ObjCForCollectionStmt *FCS,
969 CheckerContext &C) const {
970 ProgramStateRef State = C.getState();
972 // Check if this is the branch for the end of the loop.
973 SVal CollectionSentinel = C.getSVal(FCS);
974 if (CollectionSentinel.isZeroConstant()) {
975 if (!alreadyExecutedAtLeastOneLoopIteration(C.getPredecessor(), FCS))
976 State = assumeCollectionNonEmpty(C, State, FCS, /*Assumption*/false);
978 // Otherwise, this is a branch that goes through the loop body.
980 State = checkCollectionNonNil(C, State, FCS);
981 State = checkElementNonNil(C, State, FCS);
982 State = assumeCollectionNonEmpty(C, State, FCS, /*Assumption*/true);
987 else if (State != C.getState())
988 C.addTransition(State);
991 bool ObjCLoopChecker::isCollectionCountMethod(const ObjCMethodCall &M,
992 CheckerContext &C) const {
993 Selector S = M.getSelector();
994 // Initialize the identifiers on first use.
995 if (!CountSelectorII)
996 CountSelectorII = &C.getASTContext().Idents.get("count");
998 // If the method returns collection count, record the value.
999 if (S.isUnarySelector() &&
1000 (S.getIdentifierInfoForSlot(0) == CountSelectorII))
1006 void ObjCLoopChecker::checkPostObjCMessage(const ObjCMethodCall &M,
1007 CheckerContext &C) const {
1008 if (!M.isInstanceMessage())
1011 const ObjCInterfaceDecl *ClassID = M.getReceiverInterface();
1015 FoundationClass Class = findKnownClass(ClassID);
1016 if (Class != FC_NSDictionary &&
1017 Class != FC_NSArray &&
1018 Class != FC_NSSet &&
1019 Class != FC_NSOrderedSet)
1022 SymbolRef ContainerS = M.getReceiverSVal().getAsSymbol();
1026 // If we are processing a call to "count", get the symbolic value returned by
1027 // a call to "count" and add it to the map.
1028 if (!isCollectionCountMethod(M, C))
1031 const Expr *MsgExpr = M.getOriginExpr();
1032 SymbolRef CountS = C.getSVal(MsgExpr).getAsSymbol();
1034 ProgramStateRef State = C.getState();
1036 C.getSymbolManager().addSymbolDependency(ContainerS, CountS);
1037 State = State->set<ContainerCountMap>(ContainerS, CountS);
1039 if (const bool *NonEmpty = State->get<ContainerNonEmptyMap>(ContainerS)) {
1040 State = State->remove<ContainerNonEmptyMap>(ContainerS);
1041 State = assumeCollectionNonEmpty(C, State, ContainerS, *NonEmpty);
1044 C.addTransition(State);
1049 static SymbolRef getMethodReceiverIfKnownImmutable(const CallEvent *Call) {
1050 const ObjCMethodCall *Message = dyn_cast_or_null<ObjCMethodCall>(Call);
1054 const ObjCMethodDecl *MD = Message->getDecl();
1058 const ObjCInterfaceDecl *StaticClass;
1059 if (isa<ObjCProtocolDecl>(MD->getDeclContext())) {
1060 // We can't find out where the method was declared without doing more work.
1061 // Instead, see if the receiver is statically typed as a known immutable
1063 StaticClass = Message->getOriginExpr()->getReceiverInterface();
1065 StaticClass = MD->getClassInterface();
1071 switch (findKnownClass(StaticClass, /*IncludeSuper=*/false)) {
1075 case FC_NSDictionary:
1076 case FC_NSEnumerator:
1078 case FC_NSOrderedSet:
1084 return Message->getReceiverSVal().getAsSymbol();
1088 ObjCLoopChecker::checkPointerEscape(ProgramStateRef State,
1089 const InvalidatedSymbols &Escaped,
1090 const CallEvent *Call,
1091 PointerEscapeKind Kind) const {
1092 SymbolRef ImmutableReceiver = getMethodReceiverIfKnownImmutable(Call);
1094 // Remove the invalidated symbols form the collection count map.
1095 for (InvalidatedSymbols::const_iterator I = Escaped.begin(),
1100 // Don't invalidate this symbol's count if we know the method being called
1101 // is declared on an immutable class. This isn't completely correct if the
1102 // receiver is also passed as an argument, but in most uses of NSArray,
1103 // NSDictionary, etc. this isn't likely to happen in a dangerous way.
1104 if (Sym == ImmutableReceiver)
1107 // The symbol escaped. Pessimistically, assume that the count could have
1109 State = State->remove<ContainerCountMap>(Sym);
1110 State = State->remove<ContainerNonEmptyMap>(Sym);
1115 void ObjCLoopChecker::checkDeadSymbols(SymbolReaper &SymReaper,
1116 CheckerContext &C) const {
1117 ProgramStateRef State = C.getState();
1119 // Remove the dead symbols from the collection count map.
1120 ContainerCountMapTy Tracked = State->get<ContainerCountMap>();
1121 for (ContainerCountMapTy::iterator I = Tracked.begin(),
1122 E = Tracked.end(); I != E; ++I) {
1123 SymbolRef Sym = I->first;
1124 if (SymReaper.isDead(Sym)) {
1125 State = State->remove<ContainerCountMap>(Sym);
1126 State = State->remove<ContainerNonEmptyMap>(Sym);
1130 C.addTransition(State);
1134 /// \class ObjCNonNilReturnValueChecker
1135 /// \brief The checker restricts the return values of APIs known to
1136 /// never (or almost never) return 'nil'.
1137 class ObjCNonNilReturnValueChecker
1138 : public Checker<check::PostObjCMessage> {
1139 mutable bool Initialized;
1140 mutable Selector ObjectAtIndex;
1141 mutable Selector ObjectAtIndexedSubscript;
1142 mutable Selector NullSelector;
1145 ObjCNonNilReturnValueChecker() : Initialized(false) {}
1146 void checkPostObjCMessage(const ObjCMethodCall &M, CheckerContext &C) const;
1150 static ProgramStateRef assumeExprIsNonNull(const Expr *NonNullExpr,
1151 ProgramStateRef State,
1152 CheckerContext &C) {
1153 SVal Val = State->getSVal(NonNullExpr, C.getLocationContext());
1154 if (Optional<DefinedOrUnknownSVal> DV = Val.getAs<DefinedOrUnknownSVal>())
1155 return State->assume(*DV, true);
1159 void ObjCNonNilReturnValueChecker::checkPostObjCMessage(const ObjCMethodCall &M,
1162 ProgramStateRef State = C.getState();
1165 ASTContext &Ctx = C.getASTContext();
1166 ObjectAtIndex = GetUnarySelector("objectAtIndex", Ctx);
1167 ObjectAtIndexedSubscript = GetUnarySelector("objectAtIndexedSubscript", Ctx);
1168 NullSelector = GetNullarySelector("null", Ctx);
1171 // Check the receiver type.
1172 if (const ObjCInterfaceDecl *Interface = M.getReceiverInterface()) {
1174 // Assume that object returned from '[self init]' or '[super init]' is not
1175 // 'nil' if we are processing an inlined function/method.
1177 // A defensive callee will (and should) check if the object returned by
1178 // '[super init]' is 'nil' before doing it's own initialization. However,
1179 // since 'nil' is rarely returned in practice, we should not warn when the
1180 // caller to the defensive constructor uses the object in contexts where
1181 // 'nil' is not accepted.
1182 if (!C.inTopFrame() && M.getDecl() &&
1183 M.getDecl()->getMethodFamily() == OMF_init &&
1184 M.isReceiverSelfOrSuper()) {
1185 State = assumeExprIsNonNull(M.getOriginExpr(), State, C);
1188 FoundationClass Cl = findKnownClass(Interface);
1190 // Objects returned from
1191 // [NSArray|NSOrderedSet]::[ObjectAtIndex|ObjectAtIndexedSubscript]
1193 if (Cl == FC_NSArray || Cl == FC_NSOrderedSet) {
1194 Selector Sel = M.getSelector();
1195 if (Sel == ObjectAtIndex || Sel == ObjectAtIndexedSubscript) {
1196 // Go ahead and assume the value is non-nil.
1197 State = assumeExprIsNonNull(M.getOriginExpr(), State, C);
1201 // Objects returned from [NSNull null] are not nil.
1202 if (Cl == FC_NSNull) {
1203 if (M.getSelector() == NullSelector) {
1204 // Go ahead and assume the value is non-nil.
1205 State = assumeExprIsNonNull(M.getOriginExpr(), State, C);
1209 C.addTransition(State);
1212 //===----------------------------------------------------------------------===//
1213 // Check registration.
1214 //===----------------------------------------------------------------------===//
1216 void ento::registerNilArgChecker(CheckerManager &mgr) {
1217 mgr.registerChecker<NilArgChecker>();
1220 void ento::registerCFNumberCreateChecker(CheckerManager &mgr) {
1221 mgr.registerChecker<CFNumberCreateChecker>();
1224 void ento::registerCFRetainReleaseChecker(CheckerManager &mgr) {
1225 mgr.registerChecker<CFRetainReleaseChecker>();
1228 void ento::registerClassReleaseChecker(CheckerManager &mgr) {
1229 mgr.registerChecker<ClassReleaseChecker>();
1232 void ento::registerVariadicMethodTypeChecker(CheckerManager &mgr) {
1233 mgr.registerChecker<VariadicMethodTypeChecker>();
1236 void ento::registerObjCLoopChecker(CheckerManager &mgr) {
1237 mgr.registerChecker<ObjCLoopChecker>();
1240 void ento::registerObjCNonNilReturnValueChecker(CheckerManager &mgr) {
1241 mgr.registerChecker<ObjCNonNilReturnValueChecker>();