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 "SelectorExtras.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/Expr.h"
21 #include "clang/AST/ExprObjC.h"
22 #include "clang/AST/StmtObjC.h"
23 #include "clang/Analysis/DomainSpecific/CocoaConventions.h"
24 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
25 #include "clang/StaticAnalyzer/Core/Checker.h"
26 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
27 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
28 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
29 #include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
30 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
31 #include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
32 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
33 #include "llvm/ADT/SmallString.h"
34 #include "llvm/ADT/StringMap.h"
35 #include "llvm/Support/raw_ostream.h"
37 using namespace clang;
41 class APIMisuse : public BugType {
43 APIMisuse(const CheckerBase *checker, const char *name)
44 : BugType(checker, name, "API Misuse (Apple)") {}
46 } // end anonymous namespace
48 //===----------------------------------------------------------------------===//
50 //===----------------------------------------------------------------------===//
52 static StringRef GetReceiverInterfaceName(const ObjCMethodCall &msg) {
53 if (const ObjCInterfaceDecl *ID = msg.getReceiverInterface())
54 return ID->getIdentifier()->getName();
58 enum FoundationClass {
69 static FoundationClass findKnownClass(const ObjCInterfaceDecl *ID,
70 bool IncludeSuperclasses = true) {
71 static llvm::StringMap<FoundationClass> Classes;
72 if (Classes.empty()) {
73 Classes["NSArray"] = FC_NSArray;
74 Classes["NSDictionary"] = FC_NSDictionary;
75 Classes["NSEnumerator"] = FC_NSEnumerator;
76 Classes["NSNull"] = FC_NSNull;
77 Classes["NSOrderedSet"] = FC_NSOrderedSet;
78 Classes["NSSet"] = FC_NSSet;
79 Classes["NSString"] = FC_NSString;
82 // FIXME: Should we cache this at all?
83 FoundationClass result = Classes.lookup(ID->getIdentifier()->getName());
84 if (result == FC_None && IncludeSuperclasses)
85 if (const ObjCInterfaceDecl *Super = ID->getSuperClass())
86 return findKnownClass(Super);
91 //===----------------------------------------------------------------------===//
92 // NilArgChecker - Check for prohibited nil arguments to ObjC method calls.
93 //===----------------------------------------------------------------------===//
96 class NilArgChecker : public Checker<check::PreObjCMessage,
97 check::PostStmt<ObjCDictionaryLiteral>,
98 check::PostStmt<ObjCArrayLiteral> > {
99 mutable std::unique_ptr<APIMisuse> BT;
101 mutable llvm::SmallDenseMap<Selector, unsigned, 16> StringSelectors;
102 mutable Selector ArrayWithObjectSel;
103 mutable Selector AddObjectSel;
104 mutable Selector InsertObjectAtIndexSel;
105 mutable Selector ReplaceObjectAtIndexWithObjectSel;
106 mutable Selector SetObjectAtIndexedSubscriptSel;
107 mutable Selector ArrayByAddingObjectSel;
108 mutable Selector DictionaryWithObjectForKeySel;
109 mutable Selector SetObjectForKeySel;
110 mutable Selector SetObjectForKeyedSubscriptSel;
111 mutable Selector RemoveObjectForKeySel;
113 void warnIfNilExpr(const Expr *E,
115 CheckerContext &C) const;
117 void warnIfNilArg(CheckerContext &C,
118 const ObjCMethodCall &msg, unsigned Arg,
119 FoundationClass Class,
120 bool CanBeSubscript = false) const;
122 void generateBugReport(ExplodedNode *N,
126 CheckerContext &C) const;
129 void checkPreObjCMessage(const ObjCMethodCall &M, CheckerContext &C) const;
130 void checkPostStmt(const ObjCDictionaryLiteral *DL,
131 CheckerContext &C) const;
132 void checkPostStmt(const ObjCArrayLiteral *AL,
133 CheckerContext &C) const;
135 } // end anonymous namespace
137 void NilArgChecker::warnIfNilExpr(const Expr *E,
139 CheckerContext &C) const {
140 ProgramStateRef State = C.getState();
141 if (State->isNull(C.getSVal(E)).isConstrainedTrue()) {
143 if (ExplodedNode *N = C.generateErrorNode()) {
144 generateBugReport(N, Msg, E->getSourceRange(), E, C);
149 void NilArgChecker::warnIfNilArg(CheckerContext &C,
150 const ObjCMethodCall &msg,
152 FoundationClass Class,
153 bool CanBeSubscript) const {
154 // Check if the argument is nil.
155 ProgramStateRef State = C.getState();
156 if (!State->isNull(msg.getArgSVal(Arg)).isConstrainedTrue())
159 if (ExplodedNode *N = C.generateErrorNode()) {
160 SmallString<128> sbuf;
161 llvm::raw_svector_ostream os(sbuf);
163 if (CanBeSubscript && msg.getMessageKind() == OCM_Subscript) {
165 if (Class == FC_NSArray) {
166 os << "Array element cannot be nil";
167 } else if (Class == FC_NSDictionary) {
169 os << "Value stored into '";
170 os << GetReceiverInterfaceName(msg) << "' cannot be nil";
173 os << "'"<< GetReceiverInterfaceName(msg) << "' key cannot be nil";
176 llvm_unreachable("Missing foundation class for the subscript expr");
179 if (Class == FC_NSDictionary) {
181 os << "Value argument ";
184 os << "Key argument ";
187 msg.getSelector().print(os);
188 os << "' cannot be nil";
190 os << "Argument to '" << GetReceiverInterfaceName(msg) << "' method '";
191 msg.getSelector().print(os);
192 os << "' cannot be nil";
196 generateBugReport(N, os.str(), msg.getArgSourceRange(Arg),
197 msg.getArgExpr(Arg), C);
201 void NilArgChecker::generateBugReport(ExplodedNode *N,
205 CheckerContext &C) const {
207 BT.reset(new APIMisuse(this, "nil argument"));
209 auto R = llvm::make_unique<BugReport>(*BT, Msg, N);
211 bugreporter::trackNullOrUndefValue(N, E, *R);
212 C.emitReport(std::move(R));
215 void NilArgChecker::checkPreObjCMessage(const ObjCMethodCall &msg,
216 CheckerContext &C) const {
217 const ObjCInterfaceDecl *ID = msg.getReceiverInterface();
221 FoundationClass Class = findKnownClass(ID);
223 static const unsigned InvalidArgIndex = UINT_MAX;
224 unsigned Arg = InvalidArgIndex;
225 bool CanBeSubscript = false;
227 if (Class == FC_NSString) {
228 Selector S = msg.getSelector();
230 if (S.isUnarySelector())
233 if (StringSelectors.empty()) {
234 ASTContext &Ctx = C.getASTContext();
236 getKeywordSelector(Ctx, "caseInsensitiveCompare"),
237 getKeywordSelector(Ctx, "compare"),
238 getKeywordSelector(Ctx, "compare", "options"),
239 getKeywordSelector(Ctx, "compare", "options", "range"),
240 getKeywordSelector(Ctx, "compare", "options", "range", "locale"),
241 getKeywordSelector(Ctx, "componentsSeparatedByCharactersInSet"),
242 getKeywordSelector(Ctx, "initWithFormat"),
243 getKeywordSelector(Ctx, "localizedCaseInsensitiveCompare"),
244 getKeywordSelector(Ctx, "localizedCompare"),
245 getKeywordSelector(Ctx, "localizedStandardCompare"),
247 for (Selector KnownSel : Sels)
248 StringSelectors[KnownSel] = 0;
250 auto I = StringSelectors.find(S);
251 if (I == StringSelectors.end())
254 } else if (Class == FC_NSArray) {
255 Selector S = msg.getSelector();
257 if (S.isUnarySelector())
260 if (ArrayWithObjectSel.isNull()) {
261 ASTContext &Ctx = C.getASTContext();
262 ArrayWithObjectSel = getKeywordSelector(Ctx, "arrayWithObject");
263 AddObjectSel = getKeywordSelector(Ctx, "addObject");
264 InsertObjectAtIndexSel =
265 getKeywordSelector(Ctx, "insertObject", "atIndex");
266 ReplaceObjectAtIndexWithObjectSel =
267 getKeywordSelector(Ctx, "replaceObjectAtIndex", "withObject");
268 SetObjectAtIndexedSubscriptSel =
269 getKeywordSelector(Ctx, "setObject", "atIndexedSubscript");
270 ArrayByAddingObjectSel = getKeywordSelector(Ctx, "arrayByAddingObject");
273 if (S == ArrayWithObjectSel || S == AddObjectSel ||
274 S == InsertObjectAtIndexSel || S == ArrayByAddingObjectSel) {
276 } else if (S == SetObjectAtIndexedSubscriptSel) {
278 CanBeSubscript = true;
279 } else if (S == ReplaceObjectAtIndexWithObjectSel) {
282 } else if (Class == FC_NSDictionary) {
283 Selector S = msg.getSelector();
285 if (S.isUnarySelector())
288 if (DictionaryWithObjectForKeySel.isNull()) {
289 ASTContext &Ctx = C.getASTContext();
290 DictionaryWithObjectForKeySel =
291 getKeywordSelector(Ctx, "dictionaryWithObject", "forKey");
292 SetObjectForKeySel = getKeywordSelector(Ctx, "setObject", "forKey");
293 SetObjectForKeyedSubscriptSel =
294 getKeywordSelector(Ctx, "setObject", "forKeyedSubscript");
295 RemoveObjectForKeySel = getKeywordSelector(Ctx, "removeObjectForKey");
298 if (S == DictionaryWithObjectForKeySel || S == SetObjectForKeySel) {
300 warnIfNilArg(C, msg, /* Arg */1, Class);
301 } else if (S == SetObjectForKeyedSubscriptSel) {
302 CanBeSubscript = true;
304 } else if (S == RemoveObjectForKeySel) {
309 // If argument is '0', report a warning.
310 if ((Arg != InvalidArgIndex))
311 warnIfNilArg(C, msg, Arg, Class, CanBeSubscript);
314 void NilArgChecker::checkPostStmt(const ObjCArrayLiteral *AL,
315 CheckerContext &C) const {
316 unsigned NumOfElements = AL->getNumElements();
317 for (unsigned i = 0; i < NumOfElements; ++i) {
318 warnIfNilExpr(AL->getElement(i), "Array element cannot be nil", C);
322 void NilArgChecker::checkPostStmt(const ObjCDictionaryLiteral *DL,
323 CheckerContext &C) const {
324 unsigned NumOfElements = DL->getNumElements();
325 for (unsigned i = 0; i < NumOfElements; ++i) {
326 ObjCDictionaryElement Element = DL->getKeyValueElement(i);
327 warnIfNilExpr(Element.Key, "Dictionary key cannot be nil", C);
328 warnIfNilExpr(Element.Value, "Dictionary value cannot be nil", C);
332 //===----------------------------------------------------------------------===//
333 // Checking for mismatched types passed to CFNumberCreate/CFNumberGetValue.
334 //===----------------------------------------------------------------------===//
337 class CFNumberChecker : public Checker< check::PreStmt<CallExpr> > {
338 mutable std::unique_ptr<APIMisuse> BT;
339 mutable IdentifierInfo *ICreate, *IGetValue;
341 CFNumberChecker() : ICreate(nullptr), IGetValue(nullptr) {}
343 void checkPreStmt(const CallExpr *CE, CheckerContext &C) const;
346 void EmitError(const TypedRegion* R, const Expr *Ex,
347 uint64_t SourceSize, uint64_t TargetSize, uint64_t NumberKind);
349 } // end anonymous namespace
352 kCFNumberSInt8Type = 1,
353 kCFNumberSInt16Type = 2,
354 kCFNumberSInt32Type = 3,
355 kCFNumberSInt64Type = 4,
356 kCFNumberFloat32Type = 5,
357 kCFNumberFloat64Type = 6,
358 kCFNumberCharType = 7,
359 kCFNumberShortType = 8,
360 kCFNumberIntType = 9,
361 kCFNumberLongType = 10,
362 kCFNumberLongLongType = 11,
363 kCFNumberFloatType = 12,
364 kCFNumberDoubleType = 13,
365 kCFNumberCFIndexType = 14,
366 kCFNumberNSIntegerType = 15,
367 kCFNumberCGFloatType = 16
370 static Optional<uint64_t> GetCFNumberSize(ASTContext &Ctx, uint64_t i) {
371 static const unsigned char FixedSize[] = { 8, 16, 32, 64, 32, 64 };
373 if (i < kCFNumberCharType)
374 return FixedSize[i-1];
379 case kCFNumberCharType: T = Ctx.CharTy; break;
380 case kCFNumberShortType: T = Ctx.ShortTy; break;
381 case kCFNumberIntType: T = Ctx.IntTy; break;
382 case kCFNumberLongType: T = Ctx.LongTy; break;
383 case kCFNumberLongLongType: T = Ctx.LongLongTy; break;
384 case kCFNumberFloatType: T = Ctx.FloatTy; break;
385 case kCFNumberDoubleType: T = Ctx.DoubleTy; break;
386 case kCFNumberCFIndexType:
387 case kCFNumberNSIntegerType:
388 case kCFNumberCGFloatType:
389 // FIXME: We need a way to map from names to Type*.
394 return Ctx.getTypeSize(T);
398 static const char* GetCFNumberTypeStr(uint64_t i) {
399 static const char* Names[] = {
400 "kCFNumberSInt8Type",
401 "kCFNumberSInt16Type",
402 "kCFNumberSInt32Type",
403 "kCFNumberSInt64Type",
404 "kCFNumberFloat32Type",
405 "kCFNumberFloat64Type",
407 "kCFNumberShortType",
410 "kCFNumberLongLongType",
411 "kCFNumberFloatType",
412 "kCFNumberDoubleType",
413 "kCFNumberCFIndexType",
414 "kCFNumberNSIntegerType",
415 "kCFNumberCGFloatType"
418 return i <= kCFNumberCGFloatType ? Names[i-1] : "Invalid CFNumberType";
422 void CFNumberChecker::checkPreStmt(const CallExpr *CE,
423 CheckerContext &C) const {
424 ProgramStateRef state = C.getState();
425 const FunctionDecl *FD = C.getCalleeDecl(CE);
429 ASTContext &Ctx = C.getASTContext();
431 ICreate = &Ctx.Idents.get("CFNumberCreate");
432 IGetValue = &Ctx.Idents.get("CFNumberGetValue");
434 if (!(FD->getIdentifier() == ICreate || FD->getIdentifier() == IGetValue) ||
435 CE->getNumArgs() != 3)
438 // Get the value of the "theType" argument.
439 SVal TheTypeVal = C.getSVal(CE->getArg(1));
441 // FIXME: We really should allow ranges of valid theType values, and
442 // bifurcate the state appropriately.
443 Optional<nonloc::ConcreteInt> V = TheTypeVal.getAs<nonloc::ConcreteInt>();
447 uint64_t NumberKind = V->getValue().getLimitedValue();
448 Optional<uint64_t> OptCFNumberSize = GetCFNumberSize(Ctx, NumberKind);
450 // FIXME: In some cases we can emit an error.
451 if (!OptCFNumberSize)
454 uint64_t CFNumberSize = *OptCFNumberSize;
456 // Look at the value of the integer being passed by reference. Essentially
457 // we want to catch cases where the value passed in is not equal to the
458 // size of the type being created.
459 SVal TheValueExpr = C.getSVal(CE->getArg(2));
461 // FIXME: Eventually we should handle arbitrary locations. We can do this
462 // by having an enhanced memory model that does low-level typing.
463 Optional<loc::MemRegionVal> LV = TheValueExpr.getAs<loc::MemRegionVal>();
467 const TypedValueRegion* R = dyn_cast<TypedValueRegion>(LV->stripCasts());
471 QualType T = Ctx.getCanonicalType(R->getValueType());
473 // FIXME: If the pointee isn't an integer type, should we flag a warning?
474 // People can do weird stuff with pointers.
476 if (!T->isIntegralOrEnumerationType())
479 uint64_t PrimitiveTypeSize = Ctx.getTypeSize(T);
481 if (PrimitiveTypeSize == CFNumberSize)
484 // FIXME: We can actually create an abstract "CFNumber" object that has
485 // the bits initialized to the provided values.
486 ExplodedNode *N = C.generateNonFatalErrorNode();
488 SmallString<128> sbuf;
489 llvm::raw_svector_ostream os(sbuf);
490 bool isCreate = (FD->getIdentifier() == ICreate);
493 os << (PrimitiveTypeSize == 8 ? "An " : "A ")
494 << PrimitiveTypeSize << "-bit integer is used to initialize a "
495 << "CFNumber object that represents "
496 << (CFNumberSize == 8 ? "an " : "a ")
497 << CFNumberSize << "-bit integer; ";
499 os << "A CFNumber object that represents "
500 << (CFNumberSize == 8 ? "an " : "a ")
501 << CFNumberSize << "-bit integer is used to initialize "
502 << (PrimitiveTypeSize == 8 ? "an " : "a ")
503 << PrimitiveTypeSize << "-bit integer; ";
506 if (PrimitiveTypeSize < CFNumberSize)
507 os << (CFNumberSize - PrimitiveTypeSize)
508 << " bits of the CFNumber value will "
509 << (isCreate ? "be garbage." : "overwrite adjacent storage.");
511 os << (PrimitiveTypeSize - CFNumberSize)
512 << " bits of the integer value will be "
513 << (isCreate ? "lost." : "garbage.");
516 BT.reset(new APIMisuse(this, "Bad use of CFNumber APIs"));
518 auto report = llvm::make_unique<BugReport>(*BT, os.str(), N);
519 report->addRange(CE->getArg(2)->getSourceRange());
520 C.emitReport(std::move(report));
524 //===----------------------------------------------------------------------===//
525 // CFRetain/CFRelease/CFMakeCollectable/CFAutorelease checking for null arguments.
526 //===----------------------------------------------------------------------===//
529 class CFRetainReleaseChecker : public Checker< check::PreStmt<CallExpr> > {
530 mutable std::unique_ptr<APIMisuse> BT;
531 mutable IdentifierInfo *Retain, *Release, *MakeCollectable, *Autorelease;
534 CFRetainReleaseChecker()
535 : Retain(nullptr), Release(nullptr), MakeCollectable(nullptr),
536 Autorelease(nullptr) {}
537 void checkPreStmt(const CallExpr *CE, CheckerContext &C) const;
539 } // end anonymous namespace
541 void CFRetainReleaseChecker::checkPreStmt(const CallExpr *CE,
542 CheckerContext &C) const {
543 // If the CallExpr doesn't have exactly 1 argument just give up checking.
544 if (CE->getNumArgs() != 1)
547 ProgramStateRef state = C.getState();
548 const FunctionDecl *FD = C.getCalleeDecl(CE);
553 ASTContext &Ctx = C.getASTContext();
554 Retain = &Ctx.Idents.get("CFRetain");
555 Release = &Ctx.Idents.get("CFRelease");
556 MakeCollectable = &Ctx.Idents.get("CFMakeCollectable");
557 Autorelease = &Ctx.Idents.get("CFAutorelease");
558 BT.reset(new APIMisuse(
559 this, "null passed to CF memory management function"));
562 // Check if we called CFRetain/CFRelease/CFMakeCollectable/CFAutorelease.
563 const IdentifierInfo *FuncII = FD->getIdentifier();
564 if (!(FuncII == Retain || FuncII == Release || FuncII == MakeCollectable ||
565 FuncII == Autorelease))
568 // FIXME: The rest of this just checks that the argument is non-null.
569 // It should probably be refactored and combined with NonNullParamChecker.
571 // Get the argument's value.
572 const Expr *Arg = CE->getArg(0);
573 SVal ArgVal = C.getSVal(Arg);
574 Optional<DefinedSVal> DefArgVal = ArgVal.getAs<DefinedSVal>();
579 SValBuilder &svalBuilder = C.getSValBuilder();
581 svalBuilder.makeZeroVal(Arg->getType()).castAs<DefinedSVal>();
583 // Make an expression asserting that they're equal.
584 DefinedOrUnknownSVal ArgIsNull = svalBuilder.evalEQ(state, zero, *DefArgVal);
587 ProgramStateRef stateTrue, stateFalse;
588 std::tie(stateTrue, stateFalse) = state->assume(ArgIsNull);
590 if (stateTrue && !stateFalse) {
591 ExplodedNode *N = C.generateErrorNode(stateTrue);
595 const char *description;
596 if (FuncII == Retain)
597 description = "Null pointer argument in call to CFRetain";
598 else if (FuncII == Release)
599 description = "Null pointer argument in call to CFRelease";
600 else if (FuncII == MakeCollectable)
601 description = "Null pointer argument in call to CFMakeCollectable";
602 else if (FuncII == Autorelease)
603 description = "Null pointer argument in call to CFAutorelease";
605 llvm_unreachable("impossible case");
607 auto report = llvm::make_unique<BugReport>(*BT, description, N);
608 report->addRange(Arg->getSourceRange());
609 bugreporter::trackNullOrUndefValue(N, Arg, *report);
610 C.emitReport(std::move(report));
614 // From here on, we know the argument is non-null.
615 C.addTransition(stateFalse);
618 //===----------------------------------------------------------------------===//
619 // Check for sending 'retain', 'release', or 'autorelease' directly to a Class.
620 //===----------------------------------------------------------------------===//
623 class ClassReleaseChecker : public Checker<check::PreObjCMessage> {
624 mutable Selector releaseS;
625 mutable Selector retainS;
626 mutable Selector autoreleaseS;
627 mutable Selector drainS;
628 mutable std::unique_ptr<BugType> BT;
631 void checkPreObjCMessage(const ObjCMethodCall &msg, CheckerContext &C) const;
633 } // end anonymous namespace
635 void ClassReleaseChecker::checkPreObjCMessage(const ObjCMethodCall &msg,
636 CheckerContext &C) const {
638 BT.reset(new APIMisuse(
639 this, "message incorrectly sent to class instead of class instance"));
641 ASTContext &Ctx = C.getASTContext();
642 releaseS = GetNullarySelector("release", Ctx);
643 retainS = GetNullarySelector("retain", Ctx);
644 autoreleaseS = GetNullarySelector("autorelease", Ctx);
645 drainS = GetNullarySelector("drain", Ctx);
648 if (msg.isInstanceMessage())
650 const ObjCInterfaceDecl *Class = msg.getReceiverInterface();
653 Selector S = msg.getSelector();
654 if (!(S == releaseS || S == retainS || S == autoreleaseS || S == drainS))
657 if (ExplodedNode *N = C.generateNonFatalErrorNode()) {
658 SmallString<200> buf;
659 llvm::raw_svector_ostream os(buf);
663 os << "' message should be sent to instances "
664 "of class '" << Class->getName()
665 << "' and not the class directly";
667 auto report = llvm::make_unique<BugReport>(*BT, os.str(), N);
668 report->addRange(msg.getSourceRange());
669 C.emitReport(std::move(report));
673 //===----------------------------------------------------------------------===//
674 // Check for passing non-Objective-C types to variadic methods that expect
675 // only Objective-C types.
676 //===----------------------------------------------------------------------===//
679 class VariadicMethodTypeChecker : public Checker<check::PreObjCMessage> {
680 mutable Selector arrayWithObjectsS;
681 mutable Selector dictionaryWithObjectsAndKeysS;
682 mutable Selector setWithObjectsS;
683 mutable Selector orderedSetWithObjectsS;
684 mutable Selector initWithObjectsS;
685 mutable Selector initWithObjectsAndKeysS;
686 mutable std::unique_ptr<BugType> BT;
688 bool isVariadicMessage(const ObjCMethodCall &msg) const;
691 void checkPreObjCMessage(const ObjCMethodCall &msg, CheckerContext &C) const;
693 } // end anonymous namespace
695 /// isVariadicMessage - Returns whether the given message is a variadic message,
696 /// where all arguments must be Objective-C types.
698 VariadicMethodTypeChecker::isVariadicMessage(const ObjCMethodCall &msg) const {
699 const ObjCMethodDecl *MD = msg.getDecl();
701 if (!MD || !MD->isVariadic() || isa<ObjCProtocolDecl>(MD->getDeclContext()))
704 Selector S = msg.getSelector();
706 if (msg.isInstanceMessage()) {
707 // FIXME: Ideally we'd look at the receiver interface here, but that's not
708 // useful for init, because alloc returns 'id'. In theory, this could lead
709 // to false positives, for example if there existed a class that had an
710 // initWithObjects: implementation that does accept non-Objective-C pointer
711 // types, but the chance of that happening is pretty small compared to the
712 // gains that this analysis gives.
713 const ObjCInterfaceDecl *Class = MD->getClassInterface();
715 switch (findKnownClass(Class)) {
717 case FC_NSOrderedSet:
719 return S == initWithObjectsS;
720 case FC_NSDictionary:
721 return S == initWithObjectsAndKeysS;
726 const ObjCInterfaceDecl *Class = msg.getReceiverInterface();
728 switch (findKnownClass(Class)) {
730 return S == arrayWithObjectsS;
731 case FC_NSOrderedSet:
732 return S == orderedSetWithObjectsS;
734 return S == setWithObjectsS;
735 case FC_NSDictionary:
736 return S == dictionaryWithObjectsAndKeysS;
743 void VariadicMethodTypeChecker::checkPreObjCMessage(const ObjCMethodCall &msg,
744 CheckerContext &C) const {
746 BT.reset(new APIMisuse(this,
747 "Arguments passed to variadic method aren't all "
748 "Objective-C pointer types"));
750 ASTContext &Ctx = C.getASTContext();
751 arrayWithObjectsS = GetUnarySelector("arrayWithObjects", Ctx);
752 dictionaryWithObjectsAndKeysS =
753 GetUnarySelector("dictionaryWithObjectsAndKeys", Ctx);
754 setWithObjectsS = GetUnarySelector("setWithObjects", Ctx);
755 orderedSetWithObjectsS = GetUnarySelector("orderedSetWithObjects", Ctx);
757 initWithObjectsS = GetUnarySelector("initWithObjects", Ctx);
758 initWithObjectsAndKeysS = GetUnarySelector("initWithObjectsAndKeys", Ctx);
761 if (!isVariadicMessage(msg))
764 // We are not interested in the selector arguments since they have
765 // well-defined types, so the compiler will issue a warning for them.
766 unsigned variadicArgsBegin = msg.getSelector().getNumArgs();
768 // We're not interested in the last argument since it has to be nil or the
769 // compiler would have issued a warning for it elsewhere.
770 unsigned variadicArgsEnd = msg.getNumArgs() - 1;
772 if (variadicArgsEnd <= variadicArgsBegin)
775 // Verify that all arguments have Objective-C types.
776 Optional<ExplodedNode*> errorNode;
778 for (unsigned I = variadicArgsBegin; I != variadicArgsEnd; ++I) {
779 QualType ArgTy = msg.getArgExpr(I)->getType();
780 if (ArgTy->isObjCObjectPointerType())
783 // Block pointers are treaded as Objective-C pointers.
784 if (ArgTy->isBlockPointerType())
787 // Ignore pointer constants.
788 if (msg.getArgSVal(I).getAs<loc::ConcreteInt>())
791 // Ignore pointer types annotated with 'NSObject' attribute.
792 if (C.getASTContext().isObjCNSObjectType(ArgTy))
795 // Ignore CF references, which can be toll-free bridged.
796 if (coreFoundation::isCFObjectRef(ArgTy))
799 // Generate only one error node to use for all bug reports.
800 if (!errorNode.hasValue())
801 errorNode = C.generateNonFatalErrorNode();
803 if (!errorNode.getValue())
806 SmallString<128> sbuf;
807 llvm::raw_svector_ostream os(sbuf);
809 StringRef TypeName = GetReceiverInterfaceName(msg);
810 if (!TypeName.empty())
811 os << "Argument to '" << TypeName << "' method '";
813 os << "Argument to method '";
815 msg.getSelector().print(os);
816 os << "' should be an Objective-C pointer type, not '";
817 ArgTy.print(os, C.getLangOpts());
820 auto R = llvm::make_unique<BugReport>(*BT, os.str(), errorNode.getValue());
821 R->addRange(msg.getArgSourceRange(I));
822 C.emitReport(std::move(R));
826 //===----------------------------------------------------------------------===//
827 // Improves the modeling of loops over Cocoa collections.
828 //===----------------------------------------------------------------------===//
830 // The map from container symbol to the container count symbol.
831 // We currently will remember the last countainer count symbol encountered.
832 REGISTER_MAP_WITH_PROGRAMSTATE(ContainerCountMap, SymbolRef, SymbolRef)
833 REGISTER_MAP_WITH_PROGRAMSTATE(ContainerNonEmptyMap, SymbolRef, bool)
836 class ObjCLoopChecker
837 : public Checker<check::PostStmt<ObjCForCollectionStmt>,
838 check::PostObjCMessage,
840 check::PointerEscape > {
841 mutable IdentifierInfo *CountSelectorII;
843 bool isCollectionCountMethod(const ObjCMethodCall &M,
844 CheckerContext &C) const;
847 ObjCLoopChecker() : CountSelectorII(nullptr) {}
848 void checkPostStmt(const ObjCForCollectionStmt *FCS, CheckerContext &C) const;
849 void checkPostObjCMessage(const ObjCMethodCall &M, CheckerContext &C) const;
850 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
851 ProgramStateRef checkPointerEscape(ProgramStateRef State,
852 const InvalidatedSymbols &Escaped,
853 const CallEvent *Call,
854 PointerEscapeKind Kind) const;
856 } // end anonymous namespace
858 static bool isKnownNonNilCollectionType(QualType T) {
859 const ObjCObjectPointerType *PT = T->getAs<ObjCObjectPointerType>();
863 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
867 switch (findKnownClass(ID)) {
869 case FC_NSDictionary:
870 case FC_NSEnumerator:
871 case FC_NSOrderedSet:
879 /// Assumes that the collection is non-nil.
881 /// If the collection is known to be nil, returns NULL to indicate an infeasible
883 static ProgramStateRef checkCollectionNonNil(CheckerContext &C,
884 ProgramStateRef State,
885 const ObjCForCollectionStmt *FCS) {
889 SVal CollectionVal = C.getSVal(FCS->getCollection());
890 Optional<DefinedSVal> KnownCollection = CollectionVal.getAs<DefinedSVal>();
891 if (!KnownCollection)
894 ProgramStateRef StNonNil, StNil;
895 std::tie(StNonNil, StNil) = State->assume(*KnownCollection);
896 if (StNil && !StNonNil) {
897 // The collection is nil. This path is infeasible.
904 /// Assumes that the collection elements are non-nil.
906 /// This only applies if the collection is one of those known not to contain
908 static ProgramStateRef checkElementNonNil(CheckerContext &C,
909 ProgramStateRef State,
910 const ObjCForCollectionStmt *FCS) {
914 // See if the collection is one where we /know/ the elements are non-nil.
915 if (!isKnownNonNilCollectionType(FCS->getCollection()->getType()))
918 const LocationContext *LCtx = C.getLocationContext();
919 const Stmt *Element = FCS->getElement();
921 // FIXME: Copied from ExprEngineObjC.
922 Optional<Loc> ElementLoc;
923 if (const DeclStmt *DS = dyn_cast<DeclStmt>(Element)) {
924 const VarDecl *ElemDecl = cast<VarDecl>(DS->getSingleDecl());
925 assert(ElemDecl->getInit() == nullptr);
926 ElementLoc = State->getLValue(ElemDecl, LCtx);
928 ElementLoc = State->getSVal(Element, LCtx).getAs<Loc>();
934 // Go ahead and assume the value is non-nil.
935 SVal Val = State->getSVal(*ElementLoc);
936 return State->assume(Val.castAs<DefinedOrUnknownSVal>(), true);
939 /// Returns NULL state if the collection is known to contain elements
940 /// (or is known not to contain elements if the Assumption parameter is false.)
941 static ProgramStateRef
942 assumeCollectionNonEmpty(CheckerContext &C, ProgramStateRef State,
943 SymbolRef CollectionS, bool Assumption) {
944 if (!State || !CollectionS)
947 const SymbolRef *CountS = State->get<ContainerCountMap>(CollectionS);
949 const bool *KnownNonEmpty = State->get<ContainerNonEmptyMap>(CollectionS);
951 return State->set<ContainerNonEmptyMap>(CollectionS, Assumption);
952 return (Assumption == *KnownNonEmpty) ? State : nullptr;
955 SValBuilder &SvalBuilder = C.getSValBuilder();
956 SVal CountGreaterThanZeroVal =
957 SvalBuilder.evalBinOp(State, BO_GT,
958 nonloc::SymbolVal(*CountS),
959 SvalBuilder.makeIntVal(0, (*CountS)->getType()),
960 SvalBuilder.getConditionType());
961 Optional<DefinedSVal> CountGreaterThanZero =
962 CountGreaterThanZeroVal.getAs<DefinedSVal>();
963 if (!CountGreaterThanZero) {
964 // The SValBuilder cannot construct a valid SVal for this condition.
965 // This means we cannot properly reason about it.
969 return State->assume(*CountGreaterThanZero, Assumption);
972 static ProgramStateRef
973 assumeCollectionNonEmpty(CheckerContext &C, ProgramStateRef State,
974 const ObjCForCollectionStmt *FCS,
979 SymbolRef CollectionS = C.getSVal(FCS->getCollection()).getAsSymbol();
980 return assumeCollectionNonEmpty(C, State, CollectionS, Assumption);
983 /// If the fist block edge is a back edge, we are reentering the loop.
984 static bool alreadyExecutedAtLeastOneLoopIteration(const ExplodedNode *N,
985 const ObjCForCollectionStmt *FCS) {
989 ProgramPoint P = N->getLocation();
990 if (Optional<BlockEdge> BE = P.getAs<BlockEdge>()) {
991 return BE->getSrc()->getLoopTarget() == FCS;
994 // Keep looking for a block edge.
995 for (ExplodedNode::const_pred_iterator I = N->pred_begin(),
996 E = N->pred_end(); I != E; ++I) {
997 if (alreadyExecutedAtLeastOneLoopIteration(*I, FCS))
1004 void ObjCLoopChecker::checkPostStmt(const ObjCForCollectionStmt *FCS,
1005 CheckerContext &C) const {
1006 ProgramStateRef State = C.getState();
1008 // Check if this is the branch for the end of the loop.
1009 SVal CollectionSentinel = C.getSVal(FCS);
1010 if (CollectionSentinel.isZeroConstant()) {
1011 if (!alreadyExecutedAtLeastOneLoopIteration(C.getPredecessor(), FCS))
1012 State = assumeCollectionNonEmpty(C, State, FCS, /*Assumption*/false);
1014 // Otherwise, this is a branch that goes through the loop body.
1016 State = checkCollectionNonNil(C, State, FCS);
1017 State = checkElementNonNil(C, State, FCS);
1018 State = assumeCollectionNonEmpty(C, State, FCS, /*Assumption*/true);
1022 C.generateSink(C.getState(), C.getPredecessor());
1023 else if (State != C.getState())
1024 C.addTransition(State);
1027 bool ObjCLoopChecker::isCollectionCountMethod(const ObjCMethodCall &M,
1028 CheckerContext &C) const {
1029 Selector S = M.getSelector();
1030 // Initialize the identifiers on first use.
1031 if (!CountSelectorII)
1032 CountSelectorII = &C.getASTContext().Idents.get("count");
1034 // If the method returns collection count, record the value.
1035 return S.isUnarySelector() &&
1036 (S.getIdentifierInfoForSlot(0) == CountSelectorII);
1039 void ObjCLoopChecker::checkPostObjCMessage(const ObjCMethodCall &M,
1040 CheckerContext &C) const {
1041 if (!M.isInstanceMessage())
1044 const ObjCInterfaceDecl *ClassID = M.getReceiverInterface();
1048 FoundationClass Class = findKnownClass(ClassID);
1049 if (Class != FC_NSDictionary &&
1050 Class != FC_NSArray &&
1051 Class != FC_NSSet &&
1052 Class != FC_NSOrderedSet)
1055 SymbolRef ContainerS = M.getReceiverSVal().getAsSymbol();
1059 // If we are processing a call to "count", get the symbolic value returned by
1060 // a call to "count" and add it to the map.
1061 if (!isCollectionCountMethod(M, C))
1064 const Expr *MsgExpr = M.getOriginExpr();
1065 SymbolRef CountS = C.getSVal(MsgExpr).getAsSymbol();
1067 ProgramStateRef State = C.getState();
1069 C.getSymbolManager().addSymbolDependency(ContainerS, CountS);
1070 State = State->set<ContainerCountMap>(ContainerS, CountS);
1072 if (const bool *NonEmpty = State->get<ContainerNonEmptyMap>(ContainerS)) {
1073 State = State->remove<ContainerNonEmptyMap>(ContainerS);
1074 State = assumeCollectionNonEmpty(C, State, ContainerS, *NonEmpty);
1077 C.addTransition(State);
1081 static SymbolRef getMethodReceiverIfKnownImmutable(const CallEvent *Call) {
1082 const ObjCMethodCall *Message = dyn_cast_or_null<ObjCMethodCall>(Call);
1086 const ObjCMethodDecl *MD = Message->getDecl();
1090 const ObjCInterfaceDecl *StaticClass;
1091 if (isa<ObjCProtocolDecl>(MD->getDeclContext())) {
1092 // We can't find out where the method was declared without doing more work.
1093 // Instead, see if the receiver is statically typed as a known immutable
1095 StaticClass = Message->getOriginExpr()->getReceiverInterface();
1097 StaticClass = MD->getClassInterface();
1103 switch (findKnownClass(StaticClass, /*IncludeSuper=*/false)) {
1107 case FC_NSDictionary:
1108 case FC_NSEnumerator:
1110 case FC_NSOrderedSet:
1116 return Message->getReceiverSVal().getAsSymbol();
1120 ObjCLoopChecker::checkPointerEscape(ProgramStateRef State,
1121 const InvalidatedSymbols &Escaped,
1122 const CallEvent *Call,
1123 PointerEscapeKind Kind) const {
1124 SymbolRef ImmutableReceiver = getMethodReceiverIfKnownImmutable(Call);
1126 // Remove the invalidated symbols form the collection count map.
1127 for (InvalidatedSymbols::const_iterator I = Escaped.begin(),
1132 // Don't invalidate this symbol's count if we know the method being called
1133 // is declared on an immutable class. This isn't completely correct if the
1134 // receiver is also passed as an argument, but in most uses of NSArray,
1135 // NSDictionary, etc. this isn't likely to happen in a dangerous way.
1136 if (Sym == ImmutableReceiver)
1139 // The symbol escaped. Pessimistically, assume that the count could have
1141 State = State->remove<ContainerCountMap>(Sym);
1142 State = State->remove<ContainerNonEmptyMap>(Sym);
1147 void ObjCLoopChecker::checkDeadSymbols(SymbolReaper &SymReaper,
1148 CheckerContext &C) const {
1149 ProgramStateRef State = C.getState();
1151 // Remove the dead symbols from the collection count map.
1152 ContainerCountMapTy Tracked = State->get<ContainerCountMap>();
1153 for (ContainerCountMapTy::iterator I = Tracked.begin(),
1154 E = Tracked.end(); I != E; ++I) {
1155 SymbolRef Sym = I->first;
1156 if (SymReaper.isDead(Sym)) {
1157 State = State->remove<ContainerCountMap>(Sym);
1158 State = State->remove<ContainerNonEmptyMap>(Sym);
1162 C.addTransition(State);
1166 /// \class ObjCNonNilReturnValueChecker
1167 /// The checker restricts the return values of APIs known to
1168 /// never (or almost never) return 'nil'.
1169 class ObjCNonNilReturnValueChecker
1170 : public Checker<check::PostObjCMessage,
1171 check::PostStmt<ObjCArrayLiteral>,
1172 check::PostStmt<ObjCDictionaryLiteral>,
1173 check::PostStmt<ObjCBoxedExpr> > {
1174 mutable bool Initialized;
1175 mutable Selector ObjectAtIndex;
1176 mutable Selector ObjectAtIndexedSubscript;
1177 mutable Selector NullSelector;
1180 ObjCNonNilReturnValueChecker() : Initialized(false) {}
1182 ProgramStateRef assumeExprIsNonNull(const Expr *NonNullExpr,
1183 ProgramStateRef State,
1184 CheckerContext &C) const;
1185 void assumeExprIsNonNull(const Expr *E, CheckerContext &C) const {
1186 C.addTransition(assumeExprIsNonNull(E, C.getState(), C));
1189 void checkPostStmt(const ObjCArrayLiteral *E, CheckerContext &C) const {
1190 assumeExprIsNonNull(E, C);
1192 void checkPostStmt(const ObjCDictionaryLiteral *E, CheckerContext &C) const {
1193 assumeExprIsNonNull(E, C);
1195 void checkPostStmt(const ObjCBoxedExpr *E, CheckerContext &C) const {
1196 assumeExprIsNonNull(E, C);
1199 void checkPostObjCMessage(const ObjCMethodCall &M, CheckerContext &C) const;
1201 } // end anonymous namespace
1204 ObjCNonNilReturnValueChecker::assumeExprIsNonNull(const Expr *NonNullExpr,
1205 ProgramStateRef State,
1206 CheckerContext &C) const {
1207 SVal Val = C.getSVal(NonNullExpr);
1208 if (Optional<DefinedOrUnknownSVal> DV = Val.getAs<DefinedOrUnknownSVal>())
1209 return State->assume(*DV, true);
1213 void ObjCNonNilReturnValueChecker::checkPostObjCMessage(const ObjCMethodCall &M,
1216 ProgramStateRef State = C.getState();
1219 ASTContext &Ctx = C.getASTContext();
1220 ObjectAtIndex = GetUnarySelector("objectAtIndex", Ctx);
1221 ObjectAtIndexedSubscript = GetUnarySelector("objectAtIndexedSubscript", Ctx);
1222 NullSelector = GetNullarySelector("null", Ctx);
1225 // Check the receiver type.
1226 if (const ObjCInterfaceDecl *Interface = M.getReceiverInterface()) {
1228 // Assume that object returned from '[self init]' or '[super init]' is not
1229 // 'nil' if we are processing an inlined function/method.
1231 // A defensive callee will (and should) check if the object returned by
1232 // '[super init]' is 'nil' before doing it's own initialization. However,
1233 // since 'nil' is rarely returned in practice, we should not warn when the
1234 // caller to the defensive constructor uses the object in contexts where
1235 // 'nil' is not accepted.
1236 if (!C.inTopFrame() && M.getDecl() &&
1237 M.getDecl()->getMethodFamily() == OMF_init &&
1238 M.isReceiverSelfOrSuper()) {
1239 State = assumeExprIsNonNull(M.getOriginExpr(), State, C);
1242 FoundationClass Cl = findKnownClass(Interface);
1244 // Objects returned from
1245 // [NSArray|NSOrderedSet]::[ObjectAtIndex|ObjectAtIndexedSubscript]
1247 if (Cl == FC_NSArray || Cl == FC_NSOrderedSet) {
1248 Selector Sel = M.getSelector();
1249 if (Sel == ObjectAtIndex || Sel == ObjectAtIndexedSubscript) {
1250 // Go ahead and assume the value is non-nil.
1251 State = assumeExprIsNonNull(M.getOriginExpr(), State, C);
1255 // Objects returned from [NSNull null] are not nil.
1256 if (Cl == FC_NSNull) {
1257 if (M.getSelector() == NullSelector) {
1258 // Go ahead and assume the value is non-nil.
1259 State = assumeExprIsNonNull(M.getOriginExpr(), State, C);
1263 C.addTransition(State);
1266 //===----------------------------------------------------------------------===//
1267 // Check registration.
1268 //===----------------------------------------------------------------------===//
1270 void ento::registerNilArgChecker(CheckerManager &mgr) {
1271 mgr.registerChecker<NilArgChecker>();
1274 void ento::registerCFNumberChecker(CheckerManager &mgr) {
1275 mgr.registerChecker<CFNumberChecker>();
1278 void ento::registerCFRetainReleaseChecker(CheckerManager &mgr) {
1279 mgr.registerChecker<CFRetainReleaseChecker>();
1282 void ento::registerClassReleaseChecker(CheckerManager &mgr) {
1283 mgr.registerChecker<ClassReleaseChecker>();
1286 void ento::registerVariadicMethodTypeChecker(CheckerManager &mgr) {
1287 mgr.registerChecker<VariadicMethodTypeChecker>();
1290 void ento::registerObjCLoopChecker(CheckerManager &mgr) {
1291 mgr.registerChecker<ObjCLoopChecker>();
1295 ento::registerObjCNonNilReturnValueChecker(CheckerManager &mgr) {
1296 mgr.registerChecker<ObjCNonNilReturnValueChecker>();