xref: /freebsd/contrib/llvm-project/clang/lib/StaticAnalyzer/Checkers/BasicObjCFoundationChecks.cpp (revision 06c3fb2749bda94cb5201f81ffdb8fa6c3161b2e)
10b57cec5SDimitry Andric //== BasicObjCFoundationChecks.cpp - Simple Apple-Foundation checks -*- C++ -*--
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric //  This file defines BasicObjCFoundationChecks, a class that encapsulates
100b57cec5SDimitry Andric //  a set of simple checks to run on Objective-C code using Apple's Foundation
110b57cec5SDimitry Andric //  classes.
120b57cec5SDimitry Andric //
130b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
140b57cec5SDimitry Andric 
150b57cec5SDimitry Andric #include "clang/AST/ASTContext.h"
160b57cec5SDimitry Andric #include "clang/AST/DeclObjC.h"
170b57cec5SDimitry Andric #include "clang/AST/Expr.h"
180b57cec5SDimitry Andric #include "clang/AST/ExprObjC.h"
190b57cec5SDimitry Andric #include "clang/AST/StmtObjC.h"
200b57cec5SDimitry Andric #include "clang/Analysis/DomainSpecific/CocoaConventions.h"
210b57cec5SDimitry Andric #include "clang/Analysis/SelectorExtras.h"
22349cc55cSDimitry Andric #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
230b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
240b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/Checker.h"
250b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/CheckerManager.h"
26349cc55cSDimitry Andric #include "clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h"
270b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
280b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
290b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
300b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
310b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
320b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
33*06c3fb27SDimitry Andric #include "llvm/ADT/STLExtras.h"
340b57cec5SDimitry Andric #include "llvm/ADT/SmallString.h"
350b57cec5SDimitry Andric #include "llvm/ADT/StringMap.h"
360b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
37bdd1243dSDimitry Andric #include <optional>
380b57cec5SDimitry Andric 
390b57cec5SDimitry Andric using namespace clang;
400b57cec5SDimitry Andric using namespace ento;
410b57cec5SDimitry Andric using namespace llvm;
420b57cec5SDimitry Andric 
430b57cec5SDimitry Andric namespace {
440b57cec5SDimitry Andric class APIMisuse : public BugType {
450b57cec5SDimitry Andric public:
460b57cec5SDimitry Andric   APIMisuse(const CheckerBase *checker, const char *name)
470b57cec5SDimitry Andric       : BugType(checker, name, "API Misuse (Apple)") {}
480b57cec5SDimitry Andric };
490b57cec5SDimitry Andric } // end anonymous namespace
500b57cec5SDimitry Andric 
510b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
520b57cec5SDimitry Andric // Utility functions.
530b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
540b57cec5SDimitry Andric 
550b57cec5SDimitry Andric static StringRef GetReceiverInterfaceName(const ObjCMethodCall &msg) {
560b57cec5SDimitry Andric   if (const ObjCInterfaceDecl *ID = msg.getReceiverInterface())
570b57cec5SDimitry Andric     return ID->getIdentifier()->getName();
580b57cec5SDimitry Andric   return StringRef();
590b57cec5SDimitry Andric }
600b57cec5SDimitry Andric 
610b57cec5SDimitry Andric enum FoundationClass {
620b57cec5SDimitry Andric   FC_None,
630b57cec5SDimitry Andric   FC_NSArray,
640b57cec5SDimitry Andric   FC_NSDictionary,
650b57cec5SDimitry Andric   FC_NSEnumerator,
660b57cec5SDimitry Andric   FC_NSNull,
670b57cec5SDimitry Andric   FC_NSOrderedSet,
680b57cec5SDimitry Andric   FC_NSSet,
690b57cec5SDimitry Andric   FC_NSString
700b57cec5SDimitry Andric };
710b57cec5SDimitry Andric 
720b57cec5SDimitry Andric static FoundationClass findKnownClass(const ObjCInterfaceDecl *ID,
730b57cec5SDimitry Andric                                       bool IncludeSuperclasses = true) {
740b57cec5SDimitry Andric   static llvm::StringMap<FoundationClass> Classes;
750b57cec5SDimitry Andric   if (Classes.empty()) {
760b57cec5SDimitry Andric     Classes["NSArray"] = FC_NSArray;
770b57cec5SDimitry Andric     Classes["NSDictionary"] = FC_NSDictionary;
780b57cec5SDimitry Andric     Classes["NSEnumerator"] = FC_NSEnumerator;
790b57cec5SDimitry Andric     Classes["NSNull"] = FC_NSNull;
800b57cec5SDimitry Andric     Classes["NSOrderedSet"] = FC_NSOrderedSet;
810b57cec5SDimitry Andric     Classes["NSSet"] = FC_NSSet;
820b57cec5SDimitry Andric     Classes["NSString"] = FC_NSString;
830b57cec5SDimitry Andric   }
840b57cec5SDimitry Andric 
850b57cec5SDimitry Andric   // FIXME: Should we cache this at all?
860b57cec5SDimitry Andric   FoundationClass result = Classes.lookup(ID->getIdentifier()->getName());
870b57cec5SDimitry Andric   if (result == FC_None && IncludeSuperclasses)
880b57cec5SDimitry Andric     if (const ObjCInterfaceDecl *Super = ID->getSuperClass())
890b57cec5SDimitry Andric       return findKnownClass(Super);
900b57cec5SDimitry Andric 
910b57cec5SDimitry Andric   return result;
920b57cec5SDimitry Andric }
930b57cec5SDimitry Andric 
940b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
950b57cec5SDimitry Andric // NilArgChecker - Check for prohibited nil arguments to ObjC method calls.
960b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
970b57cec5SDimitry Andric 
980b57cec5SDimitry Andric namespace {
990b57cec5SDimitry Andric class NilArgChecker : public Checker<check::PreObjCMessage,
1000b57cec5SDimitry Andric                                      check::PostStmt<ObjCDictionaryLiteral>,
101*06c3fb27SDimitry Andric                                      check::PostStmt<ObjCArrayLiteral>,
102*06c3fb27SDimitry Andric                                      EventDispatcher<ImplicitNullDerefEvent>> {
1030b57cec5SDimitry Andric   mutable std::unique_ptr<APIMisuse> BT;
1040b57cec5SDimitry Andric 
1050b57cec5SDimitry Andric   mutable llvm::SmallDenseMap<Selector, unsigned, 16> StringSelectors;
1060b57cec5SDimitry Andric   mutable Selector ArrayWithObjectSel;
1070b57cec5SDimitry Andric   mutable Selector AddObjectSel;
1080b57cec5SDimitry Andric   mutable Selector InsertObjectAtIndexSel;
1090b57cec5SDimitry Andric   mutable Selector ReplaceObjectAtIndexWithObjectSel;
1100b57cec5SDimitry Andric   mutable Selector SetObjectAtIndexedSubscriptSel;
1110b57cec5SDimitry Andric   mutable Selector ArrayByAddingObjectSel;
1120b57cec5SDimitry Andric   mutable Selector DictionaryWithObjectForKeySel;
1130b57cec5SDimitry Andric   mutable Selector SetObjectForKeySel;
1140b57cec5SDimitry Andric   mutable Selector SetObjectForKeyedSubscriptSel;
1150b57cec5SDimitry Andric   mutable Selector RemoveObjectForKeySel;
1160b57cec5SDimitry Andric 
117*06c3fb27SDimitry Andric   void warnIfNilExpr(const Expr *E, const char *Msg, CheckerContext &C) const;
1180b57cec5SDimitry Andric 
119*06c3fb27SDimitry Andric   void warnIfNilArg(CheckerContext &C, const ObjCMethodCall &msg, unsigned Arg,
120*06c3fb27SDimitry Andric                     FoundationClass Class, bool CanBeSubscript = false) const;
1210b57cec5SDimitry Andric 
122*06c3fb27SDimitry Andric   void generateBugReport(ExplodedNode *N, StringRef Msg, SourceRange Range,
123*06c3fb27SDimitry Andric                          const Expr *Expr, CheckerContext &C) const;
1240b57cec5SDimitry Andric 
1250b57cec5SDimitry Andric public:
1260b57cec5SDimitry Andric   void checkPreObjCMessage(const ObjCMethodCall &M, CheckerContext &C) const;
127*06c3fb27SDimitry Andric   void checkPostStmt(const ObjCDictionaryLiteral *DL, CheckerContext &C) const;
128*06c3fb27SDimitry Andric   void checkPostStmt(const ObjCArrayLiteral *AL, CheckerContext &C) const;
1290b57cec5SDimitry Andric };
1300b57cec5SDimitry Andric } // end anonymous namespace
1310b57cec5SDimitry Andric 
1320b57cec5SDimitry Andric void NilArgChecker::warnIfNilExpr(const Expr *E,
1330b57cec5SDimitry Andric                                   const char *Msg,
1340b57cec5SDimitry Andric                                   CheckerContext &C) const {
135*06c3fb27SDimitry Andric   auto Location = C.getSVal(E).getAs<Loc>();
136*06c3fb27SDimitry Andric   if (!Location)
137*06c3fb27SDimitry Andric     return;
1380b57cec5SDimitry Andric 
139*06c3fb27SDimitry Andric   auto [NonNull, Null] = C.getState()->assume(*Location);
140*06c3fb27SDimitry Andric 
141*06c3fb27SDimitry Andric   // If it's known to be null.
142*06c3fb27SDimitry Andric   if (!NonNull && Null) {
1430b57cec5SDimitry Andric     if (ExplodedNode *N = C.generateErrorNode()) {
1440b57cec5SDimitry Andric       generateBugReport(N, Msg, E->getSourceRange(), E, C);
145*06c3fb27SDimitry Andric       return;
1460b57cec5SDimitry Andric     }
1470b57cec5SDimitry Andric   }
148*06c3fb27SDimitry Andric 
149*06c3fb27SDimitry Andric   // If it might be null, assume that it cannot after this operation.
150*06c3fb27SDimitry Andric   if (Null) {
151*06c3fb27SDimitry Andric     // One needs to make sure the pointer is non-null to be used here.
152*06c3fb27SDimitry Andric     if (ExplodedNode *N = C.generateSink(Null, C.getPredecessor())) {
153*06c3fb27SDimitry Andric       dispatchEvent({*Location, /*IsLoad=*/false, N, &C.getBugReporter(),
154*06c3fb27SDimitry Andric                      /*IsDirectDereference=*/false});
155*06c3fb27SDimitry Andric     }
156*06c3fb27SDimitry Andric     C.addTransition(NonNull);
157*06c3fb27SDimitry Andric   }
1580b57cec5SDimitry Andric }
1590b57cec5SDimitry Andric 
1600b57cec5SDimitry Andric void NilArgChecker::warnIfNilArg(CheckerContext &C,
1610b57cec5SDimitry Andric                                  const ObjCMethodCall &msg,
1620b57cec5SDimitry Andric                                  unsigned int Arg,
1630b57cec5SDimitry Andric                                  FoundationClass Class,
1640b57cec5SDimitry Andric                                  bool CanBeSubscript) const {
1650b57cec5SDimitry Andric   // Check if the argument is nil.
1660b57cec5SDimitry Andric   ProgramStateRef State = C.getState();
1670b57cec5SDimitry Andric   if (!State->isNull(msg.getArgSVal(Arg)).isConstrainedTrue())
1680b57cec5SDimitry Andric       return;
1690b57cec5SDimitry Andric 
1700b57cec5SDimitry Andric   // NOTE: We cannot throw non-fatal errors from warnIfNilExpr,
1710b57cec5SDimitry Andric   // because it's called multiple times from some callers, so it'd cause
1720b57cec5SDimitry Andric   // an unwanted state split if two or more non-fatal errors are thrown
1730b57cec5SDimitry Andric   // within the same checker callback. For now we don't want to, but
1740b57cec5SDimitry Andric   // it'll need to be fixed if we ever want to.
1750b57cec5SDimitry Andric   if (ExplodedNode *N = C.generateErrorNode()) {
1760b57cec5SDimitry Andric     SmallString<128> sbuf;
1770b57cec5SDimitry Andric     llvm::raw_svector_ostream os(sbuf);
1780b57cec5SDimitry Andric 
1790b57cec5SDimitry Andric     if (CanBeSubscript && msg.getMessageKind() == OCM_Subscript) {
1800b57cec5SDimitry Andric 
1810b57cec5SDimitry Andric       if (Class == FC_NSArray) {
1820b57cec5SDimitry Andric         os << "Array element cannot be nil";
1830b57cec5SDimitry Andric       } else if (Class == FC_NSDictionary) {
1840b57cec5SDimitry Andric         if (Arg == 0) {
1850b57cec5SDimitry Andric           os << "Value stored into '";
1860b57cec5SDimitry Andric           os << GetReceiverInterfaceName(msg) << "' cannot be nil";
1870b57cec5SDimitry Andric         } else {
1880b57cec5SDimitry Andric           assert(Arg == 1);
1890b57cec5SDimitry Andric           os << "'"<< GetReceiverInterfaceName(msg) << "' key cannot be nil";
1900b57cec5SDimitry Andric         }
1910b57cec5SDimitry Andric       } else
1920b57cec5SDimitry Andric         llvm_unreachable("Missing foundation class for the subscript expr");
1930b57cec5SDimitry Andric 
1940b57cec5SDimitry Andric     } else {
1950b57cec5SDimitry Andric       if (Class == FC_NSDictionary) {
1960b57cec5SDimitry Andric         if (Arg == 0)
1970b57cec5SDimitry Andric           os << "Value argument ";
1980b57cec5SDimitry Andric         else {
1990b57cec5SDimitry Andric           assert(Arg == 1);
2000b57cec5SDimitry Andric           os << "Key argument ";
2010b57cec5SDimitry Andric         }
2020b57cec5SDimitry Andric         os << "to '";
2030b57cec5SDimitry Andric         msg.getSelector().print(os);
2040b57cec5SDimitry Andric         os << "' cannot be nil";
2050b57cec5SDimitry Andric       } else {
2060b57cec5SDimitry Andric         os << "Argument to '" << GetReceiverInterfaceName(msg) << "' method '";
2070b57cec5SDimitry Andric         msg.getSelector().print(os);
2080b57cec5SDimitry Andric         os << "' cannot be nil";
2090b57cec5SDimitry Andric       }
2100b57cec5SDimitry Andric     }
2110b57cec5SDimitry Andric 
2120b57cec5SDimitry Andric     generateBugReport(N, os.str(), msg.getArgSourceRange(Arg),
2130b57cec5SDimitry Andric                       msg.getArgExpr(Arg), C);
2140b57cec5SDimitry Andric   }
2150b57cec5SDimitry Andric }
2160b57cec5SDimitry Andric 
2170b57cec5SDimitry Andric void NilArgChecker::generateBugReport(ExplodedNode *N,
2180b57cec5SDimitry Andric                                       StringRef Msg,
2190b57cec5SDimitry Andric                                       SourceRange Range,
2200b57cec5SDimitry Andric                                       const Expr *E,
2210b57cec5SDimitry Andric                                       CheckerContext &C) const {
2220b57cec5SDimitry Andric   if (!BT)
2230b57cec5SDimitry Andric     BT.reset(new APIMisuse(this, "nil argument"));
2240b57cec5SDimitry Andric 
225a7dea167SDimitry Andric   auto R = std::make_unique<PathSensitiveBugReport>(*BT, Msg, N);
2260b57cec5SDimitry Andric   R->addRange(Range);
2270b57cec5SDimitry Andric   bugreporter::trackExpressionValue(N, E, *R);
2280b57cec5SDimitry Andric   C.emitReport(std::move(R));
2290b57cec5SDimitry Andric }
2300b57cec5SDimitry Andric 
2310b57cec5SDimitry Andric void NilArgChecker::checkPreObjCMessage(const ObjCMethodCall &msg,
2320b57cec5SDimitry Andric                                         CheckerContext &C) const {
2330b57cec5SDimitry Andric   const ObjCInterfaceDecl *ID = msg.getReceiverInterface();
2340b57cec5SDimitry Andric   if (!ID)
2350b57cec5SDimitry Andric     return;
2360b57cec5SDimitry Andric 
2370b57cec5SDimitry Andric   FoundationClass Class = findKnownClass(ID);
2380b57cec5SDimitry Andric 
2390b57cec5SDimitry Andric   static const unsigned InvalidArgIndex = UINT_MAX;
2400b57cec5SDimitry Andric   unsigned Arg = InvalidArgIndex;
2410b57cec5SDimitry Andric   bool CanBeSubscript = false;
2420b57cec5SDimitry Andric 
2430b57cec5SDimitry Andric   if (Class == FC_NSString) {
2440b57cec5SDimitry Andric     Selector S = msg.getSelector();
2450b57cec5SDimitry Andric 
2460b57cec5SDimitry Andric     if (S.isUnarySelector())
2470b57cec5SDimitry Andric       return;
2480b57cec5SDimitry Andric 
2490b57cec5SDimitry Andric     if (StringSelectors.empty()) {
2500b57cec5SDimitry Andric       ASTContext &Ctx = C.getASTContext();
2510b57cec5SDimitry Andric       Selector Sels[] = {
2520b57cec5SDimitry Andric           getKeywordSelector(Ctx, "caseInsensitiveCompare"),
2530b57cec5SDimitry Andric           getKeywordSelector(Ctx, "compare"),
2540b57cec5SDimitry Andric           getKeywordSelector(Ctx, "compare", "options"),
2550b57cec5SDimitry Andric           getKeywordSelector(Ctx, "compare", "options", "range"),
2560b57cec5SDimitry Andric           getKeywordSelector(Ctx, "compare", "options", "range", "locale"),
2570b57cec5SDimitry Andric           getKeywordSelector(Ctx, "componentsSeparatedByCharactersInSet"),
2580b57cec5SDimitry Andric           getKeywordSelector(Ctx, "initWithFormat"),
2590b57cec5SDimitry Andric           getKeywordSelector(Ctx, "localizedCaseInsensitiveCompare"),
2600b57cec5SDimitry Andric           getKeywordSelector(Ctx, "localizedCompare"),
2610b57cec5SDimitry Andric           getKeywordSelector(Ctx, "localizedStandardCompare"),
2620b57cec5SDimitry Andric       };
2630b57cec5SDimitry Andric       for (Selector KnownSel : Sels)
2640b57cec5SDimitry Andric         StringSelectors[KnownSel] = 0;
2650b57cec5SDimitry Andric     }
2660b57cec5SDimitry Andric     auto I = StringSelectors.find(S);
2670b57cec5SDimitry Andric     if (I == StringSelectors.end())
2680b57cec5SDimitry Andric       return;
2690b57cec5SDimitry Andric     Arg = I->second;
2700b57cec5SDimitry Andric   } else if (Class == FC_NSArray) {
2710b57cec5SDimitry Andric     Selector S = msg.getSelector();
2720b57cec5SDimitry Andric 
2730b57cec5SDimitry Andric     if (S.isUnarySelector())
2740b57cec5SDimitry Andric       return;
2750b57cec5SDimitry Andric 
2760b57cec5SDimitry Andric     if (ArrayWithObjectSel.isNull()) {
2770b57cec5SDimitry Andric       ASTContext &Ctx = C.getASTContext();
2780b57cec5SDimitry Andric       ArrayWithObjectSel = getKeywordSelector(Ctx, "arrayWithObject");
2790b57cec5SDimitry Andric       AddObjectSel = getKeywordSelector(Ctx, "addObject");
2800b57cec5SDimitry Andric       InsertObjectAtIndexSel =
2810b57cec5SDimitry Andric           getKeywordSelector(Ctx, "insertObject", "atIndex");
2820b57cec5SDimitry Andric       ReplaceObjectAtIndexWithObjectSel =
2830b57cec5SDimitry Andric           getKeywordSelector(Ctx, "replaceObjectAtIndex", "withObject");
2840b57cec5SDimitry Andric       SetObjectAtIndexedSubscriptSel =
2850b57cec5SDimitry Andric           getKeywordSelector(Ctx, "setObject", "atIndexedSubscript");
2860b57cec5SDimitry Andric       ArrayByAddingObjectSel = getKeywordSelector(Ctx, "arrayByAddingObject");
2870b57cec5SDimitry Andric     }
2880b57cec5SDimitry Andric 
2890b57cec5SDimitry Andric     if (S == ArrayWithObjectSel || S == AddObjectSel ||
2900b57cec5SDimitry Andric         S == InsertObjectAtIndexSel || S == ArrayByAddingObjectSel) {
2910b57cec5SDimitry Andric       Arg = 0;
2920b57cec5SDimitry Andric     } else if (S == SetObjectAtIndexedSubscriptSel) {
2930b57cec5SDimitry Andric       Arg = 0;
2940b57cec5SDimitry Andric       CanBeSubscript = true;
2950b57cec5SDimitry Andric     } else if (S == ReplaceObjectAtIndexWithObjectSel) {
2960b57cec5SDimitry Andric       Arg = 1;
2970b57cec5SDimitry Andric     }
2980b57cec5SDimitry Andric   } else if (Class == FC_NSDictionary) {
2990b57cec5SDimitry Andric     Selector S = msg.getSelector();
3000b57cec5SDimitry Andric 
3010b57cec5SDimitry Andric     if (S.isUnarySelector())
3020b57cec5SDimitry Andric       return;
3030b57cec5SDimitry Andric 
3040b57cec5SDimitry Andric     if (DictionaryWithObjectForKeySel.isNull()) {
3050b57cec5SDimitry Andric       ASTContext &Ctx = C.getASTContext();
3060b57cec5SDimitry Andric       DictionaryWithObjectForKeySel =
3070b57cec5SDimitry Andric           getKeywordSelector(Ctx, "dictionaryWithObject", "forKey");
3080b57cec5SDimitry Andric       SetObjectForKeySel = getKeywordSelector(Ctx, "setObject", "forKey");
3090b57cec5SDimitry Andric       SetObjectForKeyedSubscriptSel =
3100b57cec5SDimitry Andric           getKeywordSelector(Ctx, "setObject", "forKeyedSubscript");
3110b57cec5SDimitry Andric       RemoveObjectForKeySel = getKeywordSelector(Ctx, "removeObjectForKey");
3120b57cec5SDimitry Andric     }
3130b57cec5SDimitry Andric 
3140b57cec5SDimitry Andric     if (S == DictionaryWithObjectForKeySel || S == SetObjectForKeySel) {
3150b57cec5SDimitry Andric       Arg = 0;
3160b57cec5SDimitry Andric       warnIfNilArg(C, msg, /* Arg */1, Class);
3170b57cec5SDimitry Andric     } else if (S == SetObjectForKeyedSubscriptSel) {
3180b57cec5SDimitry Andric       CanBeSubscript = true;
3190b57cec5SDimitry Andric       Arg = 1;
3200b57cec5SDimitry Andric     } else if (S == RemoveObjectForKeySel) {
3210b57cec5SDimitry Andric       Arg = 0;
3220b57cec5SDimitry Andric     }
3230b57cec5SDimitry Andric   }
3240b57cec5SDimitry Andric 
3250b57cec5SDimitry Andric   // If argument is '0', report a warning.
3260b57cec5SDimitry Andric   if ((Arg != InvalidArgIndex))
3270b57cec5SDimitry Andric     warnIfNilArg(C, msg, Arg, Class, CanBeSubscript);
3280b57cec5SDimitry Andric }
3290b57cec5SDimitry Andric 
3300b57cec5SDimitry Andric void NilArgChecker::checkPostStmt(const ObjCArrayLiteral *AL,
3310b57cec5SDimitry Andric                                   CheckerContext &C) const {
3320b57cec5SDimitry Andric   unsigned NumOfElements = AL->getNumElements();
3330b57cec5SDimitry Andric   for (unsigned i = 0; i < NumOfElements; ++i) {
3340b57cec5SDimitry Andric     warnIfNilExpr(AL->getElement(i), "Array element cannot be nil", C);
3350b57cec5SDimitry Andric   }
3360b57cec5SDimitry Andric }
3370b57cec5SDimitry Andric 
3380b57cec5SDimitry Andric void NilArgChecker::checkPostStmt(const ObjCDictionaryLiteral *DL,
3390b57cec5SDimitry Andric                                   CheckerContext &C) const {
3400b57cec5SDimitry Andric   unsigned NumOfElements = DL->getNumElements();
3410b57cec5SDimitry Andric   for (unsigned i = 0; i < NumOfElements; ++i) {
3420b57cec5SDimitry Andric     ObjCDictionaryElement Element = DL->getKeyValueElement(i);
3430b57cec5SDimitry Andric     warnIfNilExpr(Element.Key, "Dictionary key cannot be nil", C);
3440b57cec5SDimitry Andric     warnIfNilExpr(Element.Value, "Dictionary value cannot be nil", C);
3450b57cec5SDimitry Andric   }
3460b57cec5SDimitry Andric }
3470b57cec5SDimitry Andric 
3480b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
3490b57cec5SDimitry Andric // Checking for mismatched types passed to CFNumberCreate/CFNumberGetValue.
3500b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
3510b57cec5SDimitry Andric 
3520b57cec5SDimitry Andric namespace {
3530b57cec5SDimitry Andric class CFNumberChecker : public Checker< check::PreStmt<CallExpr> > {
3540b57cec5SDimitry Andric   mutable std::unique_ptr<APIMisuse> BT;
3550b57cec5SDimitry Andric   mutable IdentifierInfo *ICreate, *IGetValue;
3560b57cec5SDimitry Andric public:
3570b57cec5SDimitry Andric   CFNumberChecker() : ICreate(nullptr), IGetValue(nullptr) {}
3580b57cec5SDimitry Andric 
3590b57cec5SDimitry Andric   void checkPreStmt(const CallExpr *CE, CheckerContext &C) const;
3600b57cec5SDimitry Andric };
3610b57cec5SDimitry Andric } // end anonymous namespace
3620b57cec5SDimitry Andric 
3630b57cec5SDimitry Andric enum CFNumberType {
3640b57cec5SDimitry Andric   kCFNumberSInt8Type = 1,
3650b57cec5SDimitry Andric   kCFNumberSInt16Type = 2,
3660b57cec5SDimitry Andric   kCFNumberSInt32Type = 3,
3670b57cec5SDimitry Andric   kCFNumberSInt64Type = 4,
3680b57cec5SDimitry Andric   kCFNumberFloat32Type = 5,
3690b57cec5SDimitry Andric   kCFNumberFloat64Type = 6,
3700b57cec5SDimitry Andric   kCFNumberCharType = 7,
3710b57cec5SDimitry Andric   kCFNumberShortType = 8,
3720b57cec5SDimitry Andric   kCFNumberIntType = 9,
3730b57cec5SDimitry Andric   kCFNumberLongType = 10,
3740b57cec5SDimitry Andric   kCFNumberLongLongType = 11,
3750b57cec5SDimitry Andric   kCFNumberFloatType = 12,
3760b57cec5SDimitry Andric   kCFNumberDoubleType = 13,
3770b57cec5SDimitry Andric   kCFNumberCFIndexType = 14,
3780b57cec5SDimitry Andric   kCFNumberNSIntegerType = 15,
3790b57cec5SDimitry Andric   kCFNumberCGFloatType = 16
3800b57cec5SDimitry Andric };
3810b57cec5SDimitry Andric 
382bdd1243dSDimitry Andric static std::optional<uint64_t> GetCFNumberSize(ASTContext &Ctx, uint64_t i) {
3830b57cec5SDimitry Andric   static const unsigned char FixedSize[] = { 8, 16, 32, 64, 32, 64 };
3840b57cec5SDimitry Andric 
3850b57cec5SDimitry Andric   if (i < kCFNumberCharType)
3860b57cec5SDimitry Andric     return FixedSize[i-1];
3870b57cec5SDimitry Andric 
3880b57cec5SDimitry Andric   QualType T;
3890b57cec5SDimitry Andric 
3900b57cec5SDimitry Andric   switch (i) {
3910b57cec5SDimitry Andric     case kCFNumberCharType:     T = Ctx.CharTy;     break;
3920b57cec5SDimitry Andric     case kCFNumberShortType:    T = Ctx.ShortTy;    break;
3930b57cec5SDimitry Andric     case kCFNumberIntType:      T = Ctx.IntTy;      break;
3940b57cec5SDimitry Andric     case kCFNumberLongType:     T = Ctx.LongTy;     break;
3950b57cec5SDimitry Andric     case kCFNumberLongLongType: T = Ctx.LongLongTy; break;
3960b57cec5SDimitry Andric     case kCFNumberFloatType:    T = Ctx.FloatTy;    break;
3970b57cec5SDimitry Andric     case kCFNumberDoubleType:   T = Ctx.DoubleTy;   break;
3980b57cec5SDimitry Andric     case kCFNumberCFIndexType:
3990b57cec5SDimitry Andric     case kCFNumberNSIntegerType:
4000b57cec5SDimitry Andric     case kCFNumberCGFloatType:
4010b57cec5SDimitry Andric       // FIXME: We need a way to map from names to Type*.
4020b57cec5SDimitry Andric     default:
403bdd1243dSDimitry Andric       return std::nullopt;
4040b57cec5SDimitry Andric   }
4050b57cec5SDimitry Andric 
4060b57cec5SDimitry Andric   return Ctx.getTypeSize(T);
4070b57cec5SDimitry Andric }
4080b57cec5SDimitry Andric 
4090b57cec5SDimitry Andric #if 0
4100b57cec5SDimitry Andric static const char* GetCFNumberTypeStr(uint64_t i) {
4110b57cec5SDimitry Andric   static const char* Names[] = {
4120b57cec5SDimitry Andric     "kCFNumberSInt8Type",
4130b57cec5SDimitry Andric     "kCFNumberSInt16Type",
4140b57cec5SDimitry Andric     "kCFNumberSInt32Type",
4150b57cec5SDimitry Andric     "kCFNumberSInt64Type",
4160b57cec5SDimitry Andric     "kCFNumberFloat32Type",
4170b57cec5SDimitry Andric     "kCFNumberFloat64Type",
4180b57cec5SDimitry Andric     "kCFNumberCharType",
4190b57cec5SDimitry Andric     "kCFNumberShortType",
4200b57cec5SDimitry Andric     "kCFNumberIntType",
4210b57cec5SDimitry Andric     "kCFNumberLongType",
4220b57cec5SDimitry Andric     "kCFNumberLongLongType",
4230b57cec5SDimitry Andric     "kCFNumberFloatType",
4240b57cec5SDimitry Andric     "kCFNumberDoubleType",
4250b57cec5SDimitry Andric     "kCFNumberCFIndexType",
4260b57cec5SDimitry Andric     "kCFNumberNSIntegerType",
4270b57cec5SDimitry Andric     "kCFNumberCGFloatType"
4280b57cec5SDimitry Andric   };
4290b57cec5SDimitry Andric 
4300b57cec5SDimitry Andric   return i <= kCFNumberCGFloatType ? Names[i-1] : "Invalid CFNumberType";
4310b57cec5SDimitry Andric }
4320b57cec5SDimitry Andric #endif
4330b57cec5SDimitry Andric 
4340b57cec5SDimitry Andric void CFNumberChecker::checkPreStmt(const CallExpr *CE,
4350b57cec5SDimitry Andric                                          CheckerContext &C) const {
4360b57cec5SDimitry Andric   ProgramStateRef state = C.getState();
4370b57cec5SDimitry Andric   const FunctionDecl *FD = C.getCalleeDecl(CE);
4380b57cec5SDimitry Andric   if (!FD)
4390b57cec5SDimitry Andric     return;
4400b57cec5SDimitry Andric 
4410b57cec5SDimitry Andric   ASTContext &Ctx = C.getASTContext();
4420b57cec5SDimitry Andric   if (!ICreate) {
4430b57cec5SDimitry Andric     ICreate = &Ctx.Idents.get("CFNumberCreate");
4440b57cec5SDimitry Andric     IGetValue = &Ctx.Idents.get("CFNumberGetValue");
4450b57cec5SDimitry Andric   }
4460b57cec5SDimitry Andric   if (!(FD->getIdentifier() == ICreate || FD->getIdentifier() == IGetValue) ||
4470b57cec5SDimitry Andric       CE->getNumArgs() != 3)
4480b57cec5SDimitry Andric     return;
4490b57cec5SDimitry Andric 
4500b57cec5SDimitry Andric   // Get the value of the "theType" argument.
4510b57cec5SDimitry Andric   SVal TheTypeVal = C.getSVal(CE->getArg(1));
4520b57cec5SDimitry Andric 
4530b57cec5SDimitry Andric   // FIXME: We really should allow ranges of valid theType values, and
4540b57cec5SDimitry Andric   //   bifurcate the state appropriately.
455bdd1243dSDimitry Andric   std::optional<nonloc::ConcreteInt> V =
456bdd1243dSDimitry Andric       dyn_cast<nonloc::ConcreteInt>(TheTypeVal);
4570b57cec5SDimitry Andric   if (!V)
4580b57cec5SDimitry Andric     return;
4590b57cec5SDimitry Andric 
4600b57cec5SDimitry Andric   uint64_t NumberKind = V->getValue().getLimitedValue();
461bdd1243dSDimitry Andric   std::optional<uint64_t> OptCFNumberSize = GetCFNumberSize(Ctx, NumberKind);
4620b57cec5SDimitry Andric 
4630b57cec5SDimitry Andric   // FIXME: In some cases we can emit an error.
4640b57cec5SDimitry Andric   if (!OptCFNumberSize)
4650b57cec5SDimitry Andric     return;
4660b57cec5SDimitry Andric 
4670b57cec5SDimitry Andric   uint64_t CFNumberSize = *OptCFNumberSize;
4680b57cec5SDimitry Andric 
4690b57cec5SDimitry Andric   // Look at the value of the integer being passed by reference.  Essentially
4700b57cec5SDimitry Andric   // we want to catch cases where the value passed in is not equal to the
4710b57cec5SDimitry Andric   // size of the type being created.
4720b57cec5SDimitry Andric   SVal TheValueExpr = C.getSVal(CE->getArg(2));
4730b57cec5SDimitry Andric 
4740b57cec5SDimitry Andric   // FIXME: Eventually we should handle arbitrary locations.  We can do this
4750b57cec5SDimitry Andric   //  by having an enhanced memory model that does low-level typing.
476bdd1243dSDimitry Andric   std::optional<loc::MemRegionVal> LV = TheValueExpr.getAs<loc::MemRegionVal>();
4770b57cec5SDimitry Andric   if (!LV)
4780b57cec5SDimitry Andric     return;
4790b57cec5SDimitry Andric 
4800b57cec5SDimitry Andric   const TypedValueRegion* R = dyn_cast<TypedValueRegion>(LV->stripCasts());
4810b57cec5SDimitry Andric   if (!R)
4820b57cec5SDimitry Andric     return;
4830b57cec5SDimitry Andric 
4840b57cec5SDimitry Andric   QualType T = Ctx.getCanonicalType(R->getValueType());
4850b57cec5SDimitry Andric 
4860b57cec5SDimitry Andric   // FIXME: If the pointee isn't an integer type, should we flag a warning?
4870b57cec5SDimitry Andric   //  People can do weird stuff with pointers.
4880b57cec5SDimitry Andric 
4890b57cec5SDimitry Andric   if (!T->isIntegralOrEnumerationType())
4900b57cec5SDimitry Andric     return;
4910b57cec5SDimitry Andric 
4920b57cec5SDimitry Andric   uint64_t PrimitiveTypeSize = Ctx.getTypeSize(T);
4930b57cec5SDimitry Andric 
4940b57cec5SDimitry Andric   if (PrimitiveTypeSize == CFNumberSize)
4950b57cec5SDimitry Andric     return;
4960b57cec5SDimitry Andric 
4970b57cec5SDimitry Andric   // FIXME: We can actually create an abstract "CFNumber" object that has
4980b57cec5SDimitry Andric   //  the bits initialized to the provided values.
4990b57cec5SDimitry Andric   ExplodedNode *N = C.generateNonFatalErrorNode();
5000b57cec5SDimitry Andric   if (N) {
5010b57cec5SDimitry Andric     SmallString<128> sbuf;
5020b57cec5SDimitry Andric     llvm::raw_svector_ostream os(sbuf);
5030b57cec5SDimitry Andric     bool isCreate = (FD->getIdentifier() == ICreate);
5040b57cec5SDimitry Andric 
5050b57cec5SDimitry Andric     if (isCreate) {
5060b57cec5SDimitry Andric       os << (PrimitiveTypeSize == 8 ? "An " : "A ")
5070b57cec5SDimitry Andric          << PrimitiveTypeSize << "-bit integer is used to initialize a "
5080b57cec5SDimitry Andric          << "CFNumber object that represents "
5090b57cec5SDimitry Andric          << (CFNumberSize == 8 ? "an " : "a ")
5100b57cec5SDimitry Andric          << CFNumberSize << "-bit integer; ";
5110b57cec5SDimitry Andric     } else {
5120b57cec5SDimitry Andric       os << "A CFNumber object that represents "
5130b57cec5SDimitry Andric          << (CFNumberSize == 8 ? "an " : "a ")
5140b57cec5SDimitry Andric          << CFNumberSize << "-bit integer is used to initialize "
5150b57cec5SDimitry Andric          << (PrimitiveTypeSize == 8 ? "an " : "a ")
5160b57cec5SDimitry Andric          << PrimitiveTypeSize << "-bit integer; ";
5170b57cec5SDimitry Andric     }
5180b57cec5SDimitry Andric 
5190b57cec5SDimitry Andric     if (PrimitiveTypeSize < CFNumberSize)
5200b57cec5SDimitry Andric       os << (CFNumberSize - PrimitiveTypeSize)
5210b57cec5SDimitry Andric       << " bits of the CFNumber value will "
5220b57cec5SDimitry Andric       << (isCreate ? "be garbage." : "overwrite adjacent storage.");
5230b57cec5SDimitry Andric     else
5240b57cec5SDimitry Andric       os << (PrimitiveTypeSize - CFNumberSize)
5250b57cec5SDimitry Andric       << " bits of the integer value will be "
5260b57cec5SDimitry Andric       << (isCreate ? "lost." : "garbage.");
5270b57cec5SDimitry Andric 
5280b57cec5SDimitry Andric     if (!BT)
5290b57cec5SDimitry Andric       BT.reset(new APIMisuse(this, "Bad use of CFNumber APIs"));
5300b57cec5SDimitry Andric 
531a7dea167SDimitry Andric     auto report = std::make_unique<PathSensitiveBugReport>(*BT, os.str(), N);
5320b57cec5SDimitry Andric     report->addRange(CE->getArg(2)->getSourceRange());
5330b57cec5SDimitry Andric     C.emitReport(std::move(report));
5340b57cec5SDimitry Andric   }
5350b57cec5SDimitry Andric }
5360b57cec5SDimitry Andric 
5370b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
5380b57cec5SDimitry Andric // CFRetain/CFRelease/CFMakeCollectable/CFAutorelease checking for null arguments.
5390b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
5400b57cec5SDimitry Andric 
5410b57cec5SDimitry Andric namespace {
5420b57cec5SDimitry Andric class CFRetainReleaseChecker : public Checker<check::PreCall> {
5430b57cec5SDimitry Andric   mutable APIMisuse BT{this, "null passed to CF memory management function"};
544349cc55cSDimitry Andric   const CallDescriptionSet ModelledCalls = {
545bdd1243dSDimitry Andric       {{"CFRetain"}, 1},
546bdd1243dSDimitry Andric       {{"CFRelease"}, 1},
547bdd1243dSDimitry Andric       {{"CFMakeCollectable"}, 1},
548bdd1243dSDimitry Andric       {{"CFAutorelease"}, 1},
549349cc55cSDimitry Andric   };
5500b57cec5SDimitry Andric 
5510b57cec5SDimitry Andric public:
5520b57cec5SDimitry Andric   void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
5530b57cec5SDimitry Andric };
5540b57cec5SDimitry Andric } // end anonymous namespace
5550b57cec5SDimitry Andric 
5560b57cec5SDimitry Andric void CFRetainReleaseChecker::checkPreCall(const CallEvent &Call,
5570b57cec5SDimitry Andric                                           CheckerContext &C) const {
5580b57cec5SDimitry Andric   // TODO: Make this check part of CallDescription.
5590b57cec5SDimitry Andric   if (!Call.isGlobalCFunction())
5600b57cec5SDimitry Andric     return;
5610b57cec5SDimitry Andric 
5620b57cec5SDimitry Andric   // Check if we called CFRetain/CFRelease/CFMakeCollectable/CFAutorelease.
563349cc55cSDimitry Andric   if (!ModelledCalls.contains(Call))
5640b57cec5SDimitry Andric     return;
5650b57cec5SDimitry Andric 
5660b57cec5SDimitry Andric   // Get the argument's value.
5670b57cec5SDimitry Andric   SVal ArgVal = Call.getArgSVal(0);
568bdd1243dSDimitry Andric   std::optional<DefinedSVal> DefArgVal = ArgVal.getAs<DefinedSVal>();
5690b57cec5SDimitry Andric   if (!DefArgVal)
5700b57cec5SDimitry Andric     return;
5710b57cec5SDimitry Andric 
5720b57cec5SDimitry Andric   // Is it null?
5730b57cec5SDimitry Andric   ProgramStateRef state = C.getState();
5740b57cec5SDimitry Andric   ProgramStateRef stateNonNull, stateNull;
5750b57cec5SDimitry Andric   std::tie(stateNonNull, stateNull) = state->assume(*DefArgVal);
5760b57cec5SDimitry Andric 
5770b57cec5SDimitry Andric   if (!stateNonNull) {
5780b57cec5SDimitry Andric     ExplodedNode *N = C.generateErrorNode(stateNull);
5790b57cec5SDimitry Andric     if (!N)
5800b57cec5SDimitry Andric       return;
5810b57cec5SDimitry Andric 
5820b57cec5SDimitry Andric     SmallString<64> Str;
5830b57cec5SDimitry Andric     raw_svector_ostream OS(Str);
5840b57cec5SDimitry Andric     OS << "Null pointer argument in call to "
5850b57cec5SDimitry Andric        << cast<FunctionDecl>(Call.getDecl())->getName();
5860b57cec5SDimitry Andric 
587a7dea167SDimitry Andric     auto report = std::make_unique<PathSensitiveBugReport>(BT, OS.str(), N);
5880b57cec5SDimitry Andric     report->addRange(Call.getArgSourceRange(0));
5890b57cec5SDimitry Andric     bugreporter::trackExpressionValue(N, Call.getArgExpr(0), *report);
5900b57cec5SDimitry Andric     C.emitReport(std::move(report));
5910b57cec5SDimitry Andric     return;
5920b57cec5SDimitry Andric   }
5930b57cec5SDimitry Andric 
5940b57cec5SDimitry Andric   // From here on, we know the argument is non-null.
5950b57cec5SDimitry Andric   C.addTransition(stateNonNull);
5960b57cec5SDimitry Andric }
5970b57cec5SDimitry Andric 
5980b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
5990b57cec5SDimitry Andric // Check for sending 'retain', 'release', or 'autorelease' directly to a Class.
6000b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
6010b57cec5SDimitry Andric 
6020b57cec5SDimitry Andric namespace {
6030b57cec5SDimitry Andric class ClassReleaseChecker : public Checker<check::PreObjCMessage> {
6040b57cec5SDimitry Andric   mutable Selector releaseS;
6050b57cec5SDimitry Andric   mutable Selector retainS;
6060b57cec5SDimitry Andric   mutable Selector autoreleaseS;
6070b57cec5SDimitry Andric   mutable Selector drainS;
6080b57cec5SDimitry Andric   mutable std::unique_ptr<BugType> BT;
6090b57cec5SDimitry Andric 
6100b57cec5SDimitry Andric public:
6110b57cec5SDimitry Andric   void checkPreObjCMessage(const ObjCMethodCall &msg, CheckerContext &C) const;
6120b57cec5SDimitry Andric };
6130b57cec5SDimitry Andric } // end anonymous namespace
6140b57cec5SDimitry Andric 
6150b57cec5SDimitry Andric void ClassReleaseChecker::checkPreObjCMessage(const ObjCMethodCall &msg,
6160b57cec5SDimitry Andric                                               CheckerContext &C) const {
6170b57cec5SDimitry Andric   if (!BT) {
6180b57cec5SDimitry Andric     BT.reset(new APIMisuse(
6190b57cec5SDimitry Andric         this, "message incorrectly sent to class instead of class instance"));
6200b57cec5SDimitry Andric 
6210b57cec5SDimitry Andric     ASTContext &Ctx = C.getASTContext();
6220b57cec5SDimitry Andric     releaseS = GetNullarySelector("release", Ctx);
6230b57cec5SDimitry Andric     retainS = GetNullarySelector("retain", Ctx);
6240b57cec5SDimitry Andric     autoreleaseS = GetNullarySelector("autorelease", Ctx);
6250b57cec5SDimitry Andric     drainS = GetNullarySelector("drain", Ctx);
6260b57cec5SDimitry Andric   }
6270b57cec5SDimitry Andric 
6280b57cec5SDimitry Andric   if (msg.isInstanceMessage())
6290b57cec5SDimitry Andric     return;
6300b57cec5SDimitry Andric   const ObjCInterfaceDecl *Class = msg.getReceiverInterface();
6310b57cec5SDimitry Andric   assert(Class);
6320b57cec5SDimitry Andric 
6330b57cec5SDimitry Andric   Selector S = msg.getSelector();
6340b57cec5SDimitry Andric   if (!(S == releaseS || S == retainS || S == autoreleaseS || S == drainS))
6350b57cec5SDimitry Andric     return;
6360b57cec5SDimitry Andric 
6370b57cec5SDimitry Andric   if (ExplodedNode *N = C.generateNonFatalErrorNode()) {
6380b57cec5SDimitry Andric     SmallString<200> buf;
6390b57cec5SDimitry Andric     llvm::raw_svector_ostream os(buf);
6400b57cec5SDimitry Andric 
6410b57cec5SDimitry Andric     os << "The '";
6420b57cec5SDimitry Andric     S.print(os);
6430b57cec5SDimitry Andric     os << "' message should be sent to instances "
6440b57cec5SDimitry Andric           "of class '" << Class->getName()
6450b57cec5SDimitry Andric        << "' and not the class directly";
6460b57cec5SDimitry Andric 
647a7dea167SDimitry Andric     auto report = std::make_unique<PathSensitiveBugReport>(*BT, os.str(), N);
6480b57cec5SDimitry Andric     report->addRange(msg.getSourceRange());
6490b57cec5SDimitry Andric     C.emitReport(std::move(report));
6500b57cec5SDimitry Andric   }
6510b57cec5SDimitry Andric }
6520b57cec5SDimitry Andric 
6530b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
6540b57cec5SDimitry Andric // Check for passing non-Objective-C types to variadic methods that expect
6550b57cec5SDimitry Andric // only Objective-C types.
6560b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
6570b57cec5SDimitry Andric 
6580b57cec5SDimitry Andric namespace {
6590b57cec5SDimitry Andric class VariadicMethodTypeChecker : public Checker<check::PreObjCMessage> {
6600b57cec5SDimitry Andric   mutable Selector arrayWithObjectsS;
6610b57cec5SDimitry Andric   mutable Selector dictionaryWithObjectsAndKeysS;
6620b57cec5SDimitry Andric   mutable Selector setWithObjectsS;
6630b57cec5SDimitry Andric   mutable Selector orderedSetWithObjectsS;
6640b57cec5SDimitry Andric   mutable Selector initWithObjectsS;
6650b57cec5SDimitry Andric   mutable Selector initWithObjectsAndKeysS;
6660b57cec5SDimitry Andric   mutable std::unique_ptr<BugType> BT;
6670b57cec5SDimitry Andric 
6680b57cec5SDimitry Andric   bool isVariadicMessage(const ObjCMethodCall &msg) const;
6690b57cec5SDimitry Andric 
6700b57cec5SDimitry Andric public:
6710b57cec5SDimitry Andric   void checkPreObjCMessage(const ObjCMethodCall &msg, CheckerContext &C) const;
6720b57cec5SDimitry Andric };
6730b57cec5SDimitry Andric } // end anonymous namespace
6740b57cec5SDimitry Andric 
6750b57cec5SDimitry Andric /// isVariadicMessage - Returns whether the given message is a variadic message,
6760b57cec5SDimitry Andric /// where all arguments must be Objective-C types.
6770b57cec5SDimitry Andric bool
6780b57cec5SDimitry Andric VariadicMethodTypeChecker::isVariadicMessage(const ObjCMethodCall &msg) const {
6790b57cec5SDimitry Andric   const ObjCMethodDecl *MD = msg.getDecl();
6800b57cec5SDimitry Andric 
6810b57cec5SDimitry Andric   if (!MD || !MD->isVariadic() || isa<ObjCProtocolDecl>(MD->getDeclContext()))
6820b57cec5SDimitry Andric     return false;
6830b57cec5SDimitry Andric 
6840b57cec5SDimitry Andric   Selector S = msg.getSelector();
6850b57cec5SDimitry Andric 
6860b57cec5SDimitry Andric   if (msg.isInstanceMessage()) {
6870b57cec5SDimitry Andric     // FIXME: Ideally we'd look at the receiver interface here, but that's not
6880b57cec5SDimitry Andric     // useful for init, because alloc returns 'id'. In theory, this could lead
6890b57cec5SDimitry Andric     // to false positives, for example if there existed a class that had an
6900b57cec5SDimitry Andric     // initWithObjects: implementation that does accept non-Objective-C pointer
6910b57cec5SDimitry Andric     // types, but the chance of that happening is pretty small compared to the
6920b57cec5SDimitry Andric     // gains that this analysis gives.
6930b57cec5SDimitry Andric     const ObjCInterfaceDecl *Class = MD->getClassInterface();
6940b57cec5SDimitry Andric 
6950b57cec5SDimitry Andric     switch (findKnownClass(Class)) {
6960b57cec5SDimitry Andric     case FC_NSArray:
6970b57cec5SDimitry Andric     case FC_NSOrderedSet:
6980b57cec5SDimitry Andric     case FC_NSSet:
6990b57cec5SDimitry Andric       return S == initWithObjectsS;
7000b57cec5SDimitry Andric     case FC_NSDictionary:
7010b57cec5SDimitry Andric       return S == initWithObjectsAndKeysS;
7020b57cec5SDimitry Andric     default:
7030b57cec5SDimitry Andric       return false;
7040b57cec5SDimitry Andric     }
7050b57cec5SDimitry Andric   } else {
7060b57cec5SDimitry Andric     const ObjCInterfaceDecl *Class = msg.getReceiverInterface();
7070b57cec5SDimitry Andric 
7080b57cec5SDimitry Andric     switch (findKnownClass(Class)) {
7090b57cec5SDimitry Andric       case FC_NSArray:
7100b57cec5SDimitry Andric         return S == arrayWithObjectsS;
7110b57cec5SDimitry Andric       case FC_NSOrderedSet:
7120b57cec5SDimitry Andric         return S == orderedSetWithObjectsS;
7130b57cec5SDimitry Andric       case FC_NSSet:
7140b57cec5SDimitry Andric         return S == setWithObjectsS;
7150b57cec5SDimitry Andric       case FC_NSDictionary:
7160b57cec5SDimitry Andric         return S == dictionaryWithObjectsAndKeysS;
7170b57cec5SDimitry Andric       default:
7180b57cec5SDimitry Andric         return false;
7190b57cec5SDimitry Andric     }
7200b57cec5SDimitry Andric   }
7210b57cec5SDimitry Andric }
7220b57cec5SDimitry Andric 
7230b57cec5SDimitry Andric void VariadicMethodTypeChecker::checkPreObjCMessage(const ObjCMethodCall &msg,
7240b57cec5SDimitry Andric                                                     CheckerContext &C) const {
7250b57cec5SDimitry Andric   if (!BT) {
7260b57cec5SDimitry Andric     BT.reset(new APIMisuse(this,
7270b57cec5SDimitry Andric                            "Arguments passed to variadic method aren't all "
7280b57cec5SDimitry Andric                            "Objective-C pointer types"));
7290b57cec5SDimitry Andric 
7300b57cec5SDimitry Andric     ASTContext &Ctx = C.getASTContext();
7310b57cec5SDimitry Andric     arrayWithObjectsS = GetUnarySelector("arrayWithObjects", Ctx);
7320b57cec5SDimitry Andric     dictionaryWithObjectsAndKeysS =
7330b57cec5SDimitry Andric       GetUnarySelector("dictionaryWithObjectsAndKeys", Ctx);
7340b57cec5SDimitry Andric     setWithObjectsS = GetUnarySelector("setWithObjects", Ctx);
7350b57cec5SDimitry Andric     orderedSetWithObjectsS = GetUnarySelector("orderedSetWithObjects", Ctx);
7360b57cec5SDimitry Andric 
7370b57cec5SDimitry Andric     initWithObjectsS = GetUnarySelector("initWithObjects", Ctx);
7380b57cec5SDimitry Andric     initWithObjectsAndKeysS = GetUnarySelector("initWithObjectsAndKeys", Ctx);
7390b57cec5SDimitry Andric   }
7400b57cec5SDimitry Andric 
7410b57cec5SDimitry Andric   if (!isVariadicMessage(msg))
7420b57cec5SDimitry Andric       return;
7430b57cec5SDimitry Andric 
7440b57cec5SDimitry Andric   // We are not interested in the selector arguments since they have
7450b57cec5SDimitry Andric   // well-defined types, so the compiler will issue a warning for them.
7460b57cec5SDimitry Andric   unsigned variadicArgsBegin = msg.getSelector().getNumArgs();
7470b57cec5SDimitry Andric 
7480b57cec5SDimitry Andric   // We're not interested in the last argument since it has to be nil or the
7490b57cec5SDimitry Andric   // compiler would have issued a warning for it elsewhere.
7500b57cec5SDimitry Andric   unsigned variadicArgsEnd = msg.getNumArgs() - 1;
7510b57cec5SDimitry Andric 
7520b57cec5SDimitry Andric   if (variadicArgsEnd <= variadicArgsBegin)
7530b57cec5SDimitry Andric     return;
7540b57cec5SDimitry Andric 
7550b57cec5SDimitry Andric   // Verify that all arguments have Objective-C types.
756bdd1243dSDimitry Andric   std::optional<ExplodedNode *> errorNode;
7570b57cec5SDimitry Andric 
7580b57cec5SDimitry Andric   for (unsigned I = variadicArgsBegin; I != variadicArgsEnd; ++I) {
7590b57cec5SDimitry Andric     QualType ArgTy = msg.getArgExpr(I)->getType();
7600b57cec5SDimitry Andric     if (ArgTy->isObjCObjectPointerType())
7610b57cec5SDimitry Andric       continue;
7620b57cec5SDimitry Andric 
7630b57cec5SDimitry Andric     // Block pointers are treaded as Objective-C pointers.
7640b57cec5SDimitry Andric     if (ArgTy->isBlockPointerType())
7650b57cec5SDimitry Andric       continue;
7660b57cec5SDimitry Andric 
7670b57cec5SDimitry Andric     // Ignore pointer constants.
76881ad6265SDimitry Andric     if (isa<loc::ConcreteInt>(msg.getArgSVal(I)))
7690b57cec5SDimitry Andric       continue;
7700b57cec5SDimitry Andric 
7710b57cec5SDimitry Andric     // Ignore pointer types annotated with 'NSObject' attribute.
7720b57cec5SDimitry Andric     if (C.getASTContext().isObjCNSObjectType(ArgTy))
7730b57cec5SDimitry Andric       continue;
7740b57cec5SDimitry Andric 
7750b57cec5SDimitry Andric     // Ignore CF references, which can be toll-free bridged.
7760b57cec5SDimitry Andric     if (coreFoundation::isCFObjectRef(ArgTy))
7770b57cec5SDimitry Andric       continue;
7780b57cec5SDimitry Andric 
7790b57cec5SDimitry Andric     // Generate only one error node to use for all bug reports.
78081ad6265SDimitry Andric     if (!errorNode)
7810b57cec5SDimitry Andric       errorNode = C.generateNonFatalErrorNode();
7820b57cec5SDimitry Andric 
783bdd1243dSDimitry Andric     if (!*errorNode)
7840b57cec5SDimitry Andric       continue;
7850b57cec5SDimitry Andric 
7860b57cec5SDimitry Andric     SmallString<128> sbuf;
7870b57cec5SDimitry Andric     llvm::raw_svector_ostream os(sbuf);
7880b57cec5SDimitry Andric 
7890b57cec5SDimitry Andric     StringRef TypeName = GetReceiverInterfaceName(msg);
7900b57cec5SDimitry Andric     if (!TypeName.empty())
7910b57cec5SDimitry Andric       os << "Argument to '" << TypeName << "' method '";
7920b57cec5SDimitry Andric     else
7930b57cec5SDimitry Andric       os << "Argument to method '";
7940b57cec5SDimitry Andric 
7950b57cec5SDimitry Andric     msg.getSelector().print(os);
7960b57cec5SDimitry Andric     os << "' should be an Objective-C pointer type, not '";
7970b57cec5SDimitry Andric     ArgTy.print(os, C.getLangOpts());
7980b57cec5SDimitry Andric     os << "'";
7990b57cec5SDimitry Andric 
800bdd1243dSDimitry Andric     auto R =
801bdd1243dSDimitry Andric         std::make_unique<PathSensitiveBugReport>(*BT, os.str(), *errorNode);
8020b57cec5SDimitry Andric     R->addRange(msg.getArgSourceRange(I));
8030b57cec5SDimitry Andric     C.emitReport(std::move(R));
8040b57cec5SDimitry Andric   }
8050b57cec5SDimitry Andric }
8060b57cec5SDimitry Andric 
8070b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
8080b57cec5SDimitry Andric // Improves the modeling of loops over Cocoa collections.
8090b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
8100b57cec5SDimitry Andric 
8110b57cec5SDimitry Andric // The map from container symbol to the container count symbol.
8120b57cec5SDimitry Andric // We currently will remember the last container count symbol encountered.
8130b57cec5SDimitry Andric REGISTER_MAP_WITH_PROGRAMSTATE(ContainerCountMap, SymbolRef, SymbolRef)
8140b57cec5SDimitry Andric REGISTER_MAP_WITH_PROGRAMSTATE(ContainerNonEmptyMap, SymbolRef, bool)
8150b57cec5SDimitry Andric 
8160b57cec5SDimitry Andric namespace {
8170b57cec5SDimitry Andric class ObjCLoopChecker
8180b57cec5SDimitry Andric   : public Checker<check::PostStmt<ObjCForCollectionStmt>,
8190b57cec5SDimitry Andric                    check::PostObjCMessage,
8200b57cec5SDimitry Andric                    check::DeadSymbols,
8210b57cec5SDimitry Andric                    check::PointerEscape > {
8220b57cec5SDimitry Andric   mutable IdentifierInfo *CountSelectorII;
8230b57cec5SDimitry Andric 
8240b57cec5SDimitry Andric   bool isCollectionCountMethod(const ObjCMethodCall &M,
8250b57cec5SDimitry Andric                                CheckerContext &C) const;
8260b57cec5SDimitry Andric 
8270b57cec5SDimitry Andric public:
8280b57cec5SDimitry Andric   ObjCLoopChecker() : CountSelectorII(nullptr) {}
8290b57cec5SDimitry Andric   void checkPostStmt(const ObjCForCollectionStmt *FCS, CheckerContext &C) const;
8300b57cec5SDimitry Andric   void checkPostObjCMessage(const ObjCMethodCall &M, CheckerContext &C) const;
8310b57cec5SDimitry Andric   void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
8320b57cec5SDimitry Andric   ProgramStateRef checkPointerEscape(ProgramStateRef State,
8330b57cec5SDimitry Andric                                      const InvalidatedSymbols &Escaped,
8340b57cec5SDimitry Andric                                      const CallEvent *Call,
8350b57cec5SDimitry Andric                                      PointerEscapeKind Kind) const;
8360b57cec5SDimitry Andric };
8370b57cec5SDimitry Andric } // end anonymous namespace
8380b57cec5SDimitry Andric 
8390b57cec5SDimitry Andric static bool isKnownNonNilCollectionType(QualType T) {
8400b57cec5SDimitry Andric   const ObjCObjectPointerType *PT = T->getAs<ObjCObjectPointerType>();
8410b57cec5SDimitry Andric   if (!PT)
8420b57cec5SDimitry Andric     return false;
8430b57cec5SDimitry Andric 
8440b57cec5SDimitry Andric   const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
8450b57cec5SDimitry Andric   if (!ID)
8460b57cec5SDimitry Andric     return false;
8470b57cec5SDimitry Andric 
8480b57cec5SDimitry Andric   switch (findKnownClass(ID)) {
8490b57cec5SDimitry Andric   case FC_NSArray:
8500b57cec5SDimitry Andric   case FC_NSDictionary:
8510b57cec5SDimitry Andric   case FC_NSEnumerator:
8520b57cec5SDimitry Andric   case FC_NSOrderedSet:
8530b57cec5SDimitry Andric   case FC_NSSet:
8540b57cec5SDimitry Andric     return true;
8550b57cec5SDimitry Andric   default:
8560b57cec5SDimitry Andric     return false;
8570b57cec5SDimitry Andric   }
8580b57cec5SDimitry Andric }
8590b57cec5SDimitry Andric 
8600b57cec5SDimitry Andric /// Assumes that the collection is non-nil.
8610b57cec5SDimitry Andric ///
8620b57cec5SDimitry Andric /// If the collection is known to be nil, returns NULL to indicate an infeasible
8630b57cec5SDimitry Andric /// path.
8640b57cec5SDimitry Andric static ProgramStateRef checkCollectionNonNil(CheckerContext &C,
8650b57cec5SDimitry Andric                                              ProgramStateRef State,
8660b57cec5SDimitry Andric                                              const ObjCForCollectionStmt *FCS) {
8670b57cec5SDimitry Andric   if (!State)
8680b57cec5SDimitry Andric     return nullptr;
8690b57cec5SDimitry Andric 
8700b57cec5SDimitry Andric   SVal CollectionVal = C.getSVal(FCS->getCollection());
871bdd1243dSDimitry Andric   std::optional<DefinedSVal> KnownCollection =
872bdd1243dSDimitry Andric       CollectionVal.getAs<DefinedSVal>();
8730b57cec5SDimitry Andric   if (!KnownCollection)
8740b57cec5SDimitry Andric     return State;
8750b57cec5SDimitry Andric 
8760b57cec5SDimitry Andric   ProgramStateRef StNonNil, StNil;
8770b57cec5SDimitry Andric   std::tie(StNonNil, StNil) = State->assume(*KnownCollection);
8780b57cec5SDimitry Andric   if (StNil && !StNonNil) {
8790b57cec5SDimitry Andric     // The collection is nil. This path is infeasible.
8800b57cec5SDimitry Andric     return nullptr;
8810b57cec5SDimitry Andric   }
8820b57cec5SDimitry Andric 
8830b57cec5SDimitry Andric   return StNonNil;
8840b57cec5SDimitry Andric }
8850b57cec5SDimitry Andric 
8860b57cec5SDimitry Andric /// Assumes that the collection elements are non-nil.
8870b57cec5SDimitry Andric ///
8880b57cec5SDimitry Andric /// This only applies if the collection is one of those known not to contain
8890b57cec5SDimitry Andric /// nil values.
8900b57cec5SDimitry Andric static ProgramStateRef checkElementNonNil(CheckerContext &C,
8910b57cec5SDimitry Andric                                           ProgramStateRef State,
8920b57cec5SDimitry Andric                                           const ObjCForCollectionStmt *FCS) {
8930b57cec5SDimitry Andric   if (!State)
8940b57cec5SDimitry Andric     return nullptr;
8950b57cec5SDimitry Andric 
8960b57cec5SDimitry Andric   // See if the collection is one where we /know/ the elements are non-nil.
8970b57cec5SDimitry Andric   if (!isKnownNonNilCollectionType(FCS->getCollection()->getType()))
8980b57cec5SDimitry Andric     return State;
8990b57cec5SDimitry Andric 
9000b57cec5SDimitry Andric   const LocationContext *LCtx = C.getLocationContext();
9010b57cec5SDimitry Andric   const Stmt *Element = FCS->getElement();
9020b57cec5SDimitry Andric 
9030b57cec5SDimitry Andric   // FIXME: Copied from ExprEngineObjC.
904bdd1243dSDimitry Andric   std::optional<Loc> ElementLoc;
9050b57cec5SDimitry Andric   if (const DeclStmt *DS = dyn_cast<DeclStmt>(Element)) {
9060b57cec5SDimitry Andric     const VarDecl *ElemDecl = cast<VarDecl>(DS->getSingleDecl());
9070b57cec5SDimitry Andric     assert(ElemDecl->getInit() == nullptr);
9080b57cec5SDimitry Andric     ElementLoc = State->getLValue(ElemDecl, LCtx);
9090b57cec5SDimitry Andric   } else {
9100b57cec5SDimitry Andric     ElementLoc = State->getSVal(Element, LCtx).getAs<Loc>();
9110b57cec5SDimitry Andric   }
9120b57cec5SDimitry Andric 
9130b57cec5SDimitry Andric   if (!ElementLoc)
9140b57cec5SDimitry Andric     return State;
9150b57cec5SDimitry Andric 
9160b57cec5SDimitry Andric   // Go ahead and assume the value is non-nil.
9170b57cec5SDimitry Andric   SVal Val = State->getSVal(*ElementLoc);
91881ad6265SDimitry Andric   return State->assume(cast<DefinedOrUnknownSVal>(Val), true);
9190b57cec5SDimitry Andric }
9200b57cec5SDimitry Andric 
9210b57cec5SDimitry Andric /// Returns NULL state if the collection is known to contain elements
9220b57cec5SDimitry Andric /// (or is known not to contain elements if the Assumption parameter is false.)
9230b57cec5SDimitry Andric static ProgramStateRef
9240b57cec5SDimitry Andric assumeCollectionNonEmpty(CheckerContext &C, ProgramStateRef State,
9250b57cec5SDimitry Andric                          SymbolRef CollectionS, bool Assumption) {
9260b57cec5SDimitry Andric   if (!State || !CollectionS)
9270b57cec5SDimitry Andric     return State;
9280b57cec5SDimitry Andric 
9290b57cec5SDimitry Andric   const SymbolRef *CountS = State->get<ContainerCountMap>(CollectionS);
9300b57cec5SDimitry Andric   if (!CountS) {
9310b57cec5SDimitry Andric     const bool *KnownNonEmpty = State->get<ContainerNonEmptyMap>(CollectionS);
9320b57cec5SDimitry Andric     if (!KnownNonEmpty)
9330b57cec5SDimitry Andric       return State->set<ContainerNonEmptyMap>(CollectionS, Assumption);
9340b57cec5SDimitry Andric     return (Assumption == *KnownNonEmpty) ? State : nullptr;
9350b57cec5SDimitry Andric   }
9360b57cec5SDimitry Andric 
9370b57cec5SDimitry Andric   SValBuilder &SvalBuilder = C.getSValBuilder();
9380b57cec5SDimitry Andric   SVal CountGreaterThanZeroVal =
9390b57cec5SDimitry Andric     SvalBuilder.evalBinOp(State, BO_GT,
9400b57cec5SDimitry Andric                           nonloc::SymbolVal(*CountS),
9410b57cec5SDimitry Andric                           SvalBuilder.makeIntVal(0, (*CountS)->getType()),
9420b57cec5SDimitry Andric                           SvalBuilder.getConditionType());
943bdd1243dSDimitry Andric   std::optional<DefinedSVal> CountGreaterThanZero =
9440b57cec5SDimitry Andric       CountGreaterThanZeroVal.getAs<DefinedSVal>();
9450b57cec5SDimitry Andric   if (!CountGreaterThanZero) {
9460b57cec5SDimitry Andric     // The SValBuilder cannot construct a valid SVal for this condition.
9470b57cec5SDimitry Andric     // This means we cannot properly reason about it.
9480b57cec5SDimitry Andric     return State;
9490b57cec5SDimitry Andric   }
9500b57cec5SDimitry Andric 
9510b57cec5SDimitry Andric   return State->assume(*CountGreaterThanZero, Assumption);
9520b57cec5SDimitry Andric }
9530b57cec5SDimitry Andric 
9540b57cec5SDimitry Andric static ProgramStateRef
9550b57cec5SDimitry Andric assumeCollectionNonEmpty(CheckerContext &C, ProgramStateRef State,
9560b57cec5SDimitry Andric                          const ObjCForCollectionStmt *FCS,
9570b57cec5SDimitry Andric                          bool Assumption) {
9580b57cec5SDimitry Andric   if (!State)
9590b57cec5SDimitry Andric     return nullptr;
9600b57cec5SDimitry Andric 
9610b57cec5SDimitry Andric   SymbolRef CollectionS = C.getSVal(FCS->getCollection()).getAsSymbol();
9620b57cec5SDimitry Andric   return assumeCollectionNonEmpty(C, State, CollectionS, Assumption);
9630b57cec5SDimitry Andric }
9640b57cec5SDimitry Andric 
9650b57cec5SDimitry Andric /// If the fist block edge is a back edge, we are reentering the loop.
9660b57cec5SDimitry Andric static bool alreadyExecutedAtLeastOneLoopIteration(const ExplodedNode *N,
9670b57cec5SDimitry Andric                                              const ObjCForCollectionStmt *FCS) {
9680b57cec5SDimitry Andric   if (!N)
9690b57cec5SDimitry Andric     return false;
9700b57cec5SDimitry Andric 
9710b57cec5SDimitry Andric   ProgramPoint P = N->getLocation();
972bdd1243dSDimitry Andric   if (std::optional<BlockEdge> BE = P.getAs<BlockEdge>()) {
9730b57cec5SDimitry Andric     return BE->getSrc()->getLoopTarget() == FCS;
9740b57cec5SDimitry Andric   }
9750b57cec5SDimitry Andric 
9760b57cec5SDimitry Andric   // Keep looking for a block edge.
977*06c3fb27SDimitry Andric   for (const ExplodedNode *N : N->preds()) {
978*06c3fb27SDimitry Andric     if (alreadyExecutedAtLeastOneLoopIteration(N, FCS))
9790b57cec5SDimitry Andric       return true;
9800b57cec5SDimitry Andric   }
9810b57cec5SDimitry Andric 
9820b57cec5SDimitry Andric   return false;
9830b57cec5SDimitry Andric }
9840b57cec5SDimitry Andric 
9850b57cec5SDimitry Andric void ObjCLoopChecker::checkPostStmt(const ObjCForCollectionStmt *FCS,
9860b57cec5SDimitry Andric                                     CheckerContext &C) const {
9870b57cec5SDimitry Andric   ProgramStateRef State = C.getState();
9880b57cec5SDimitry Andric 
9890b57cec5SDimitry Andric   // Check if this is the branch for the end of the loop.
990e8d8bef9SDimitry Andric   if (!ExprEngine::hasMoreIteration(State, FCS, C.getLocationContext())) {
9910b57cec5SDimitry Andric     if (!alreadyExecutedAtLeastOneLoopIteration(C.getPredecessor(), FCS))
9920b57cec5SDimitry Andric       State = assumeCollectionNonEmpty(C, State, FCS, /*Assumption*/false);
9930b57cec5SDimitry Andric 
9940b57cec5SDimitry Andric   // Otherwise, this is a branch that goes through the loop body.
9950b57cec5SDimitry Andric   } else {
9960b57cec5SDimitry Andric     State = checkCollectionNonNil(C, State, FCS);
9970b57cec5SDimitry Andric     State = checkElementNonNil(C, State, FCS);
9980b57cec5SDimitry Andric     State = assumeCollectionNonEmpty(C, State, FCS, /*Assumption*/true);
9990b57cec5SDimitry Andric   }
10000b57cec5SDimitry Andric 
10010b57cec5SDimitry Andric   if (!State)
10020b57cec5SDimitry Andric     C.generateSink(C.getState(), C.getPredecessor());
10030b57cec5SDimitry Andric   else if (State != C.getState())
10040b57cec5SDimitry Andric     C.addTransition(State);
10050b57cec5SDimitry Andric }
10060b57cec5SDimitry Andric 
10070b57cec5SDimitry Andric bool ObjCLoopChecker::isCollectionCountMethod(const ObjCMethodCall &M,
10080b57cec5SDimitry Andric                                               CheckerContext &C) const {
10090b57cec5SDimitry Andric   Selector S = M.getSelector();
10100b57cec5SDimitry Andric   // Initialize the identifiers on first use.
10110b57cec5SDimitry Andric   if (!CountSelectorII)
10120b57cec5SDimitry Andric     CountSelectorII = &C.getASTContext().Idents.get("count");
10130b57cec5SDimitry Andric 
10140b57cec5SDimitry Andric   // If the method returns collection count, record the value.
10150b57cec5SDimitry Andric   return S.isUnarySelector() &&
10160b57cec5SDimitry Andric          (S.getIdentifierInfoForSlot(0) == CountSelectorII);
10170b57cec5SDimitry Andric }
10180b57cec5SDimitry Andric 
10190b57cec5SDimitry Andric void ObjCLoopChecker::checkPostObjCMessage(const ObjCMethodCall &M,
10200b57cec5SDimitry Andric                                            CheckerContext &C) const {
10210b57cec5SDimitry Andric   if (!M.isInstanceMessage())
10220b57cec5SDimitry Andric     return;
10230b57cec5SDimitry Andric 
10240b57cec5SDimitry Andric   const ObjCInterfaceDecl *ClassID = M.getReceiverInterface();
10250b57cec5SDimitry Andric   if (!ClassID)
10260b57cec5SDimitry Andric     return;
10270b57cec5SDimitry Andric 
10280b57cec5SDimitry Andric   FoundationClass Class = findKnownClass(ClassID);
10290b57cec5SDimitry Andric   if (Class != FC_NSDictionary &&
10300b57cec5SDimitry Andric       Class != FC_NSArray &&
10310b57cec5SDimitry Andric       Class != FC_NSSet &&
10320b57cec5SDimitry Andric       Class != FC_NSOrderedSet)
10330b57cec5SDimitry Andric     return;
10340b57cec5SDimitry Andric 
10350b57cec5SDimitry Andric   SymbolRef ContainerS = M.getReceiverSVal().getAsSymbol();
10360b57cec5SDimitry Andric   if (!ContainerS)
10370b57cec5SDimitry Andric     return;
10380b57cec5SDimitry Andric 
10390b57cec5SDimitry Andric   // If we are processing a call to "count", get the symbolic value returned by
10400b57cec5SDimitry Andric   // a call to "count" and add it to the map.
10410b57cec5SDimitry Andric   if (!isCollectionCountMethod(M, C))
10420b57cec5SDimitry Andric     return;
10430b57cec5SDimitry Andric 
10440b57cec5SDimitry Andric   const Expr *MsgExpr = M.getOriginExpr();
10450b57cec5SDimitry Andric   SymbolRef CountS = C.getSVal(MsgExpr).getAsSymbol();
10460b57cec5SDimitry Andric   if (CountS) {
10470b57cec5SDimitry Andric     ProgramStateRef State = C.getState();
10480b57cec5SDimitry Andric 
10490b57cec5SDimitry Andric     C.getSymbolManager().addSymbolDependency(ContainerS, CountS);
10500b57cec5SDimitry Andric     State = State->set<ContainerCountMap>(ContainerS, CountS);
10510b57cec5SDimitry Andric 
10520b57cec5SDimitry Andric     if (const bool *NonEmpty = State->get<ContainerNonEmptyMap>(ContainerS)) {
10530b57cec5SDimitry Andric       State = State->remove<ContainerNonEmptyMap>(ContainerS);
10540b57cec5SDimitry Andric       State = assumeCollectionNonEmpty(C, State, ContainerS, *NonEmpty);
10550b57cec5SDimitry Andric     }
10560b57cec5SDimitry Andric 
10570b57cec5SDimitry Andric     C.addTransition(State);
10580b57cec5SDimitry Andric   }
10590b57cec5SDimitry Andric }
10600b57cec5SDimitry Andric 
10610b57cec5SDimitry Andric static SymbolRef getMethodReceiverIfKnownImmutable(const CallEvent *Call) {
10620b57cec5SDimitry Andric   const ObjCMethodCall *Message = dyn_cast_or_null<ObjCMethodCall>(Call);
10630b57cec5SDimitry Andric   if (!Message)
10640b57cec5SDimitry Andric     return nullptr;
10650b57cec5SDimitry Andric 
10660b57cec5SDimitry Andric   const ObjCMethodDecl *MD = Message->getDecl();
10670b57cec5SDimitry Andric   if (!MD)
10680b57cec5SDimitry Andric     return nullptr;
10690b57cec5SDimitry Andric 
10700b57cec5SDimitry Andric   const ObjCInterfaceDecl *StaticClass;
10710b57cec5SDimitry Andric   if (isa<ObjCProtocolDecl>(MD->getDeclContext())) {
10720b57cec5SDimitry Andric     // We can't find out where the method was declared without doing more work.
10730b57cec5SDimitry Andric     // Instead, see if the receiver is statically typed as a known immutable
10740b57cec5SDimitry Andric     // collection.
10750b57cec5SDimitry Andric     StaticClass = Message->getOriginExpr()->getReceiverInterface();
10760b57cec5SDimitry Andric   } else {
10770b57cec5SDimitry Andric     StaticClass = MD->getClassInterface();
10780b57cec5SDimitry Andric   }
10790b57cec5SDimitry Andric 
10800b57cec5SDimitry Andric   if (!StaticClass)
10810b57cec5SDimitry Andric     return nullptr;
10820b57cec5SDimitry Andric 
10830b57cec5SDimitry Andric   switch (findKnownClass(StaticClass, /*IncludeSuper=*/false)) {
10840b57cec5SDimitry Andric   case FC_None:
10850b57cec5SDimitry Andric     return nullptr;
10860b57cec5SDimitry Andric   case FC_NSArray:
10870b57cec5SDimitry Andric   case FC_NSDictionary:
10880b57cec5SDimitry Andric   case FC_NSEnumerator:
10890b57cec5SDimitry Andric   case FC_NSNull:
10900b57cec5SDimitry Andric   case FC_NSOrderedSet:
10910b57cec5SDimitry Andric   case FC_NSSet:
10920b57cec5SDimitry Andric   case FC_NSString:
10930b57cec5SDimitry Andric     break;
10940b57cec5SDimitry Andric   }
10950b57cec5SDimitry Andric 
10960b57cec5SDimitry Andric   return Message->getReceiverSVal().getAsSymbol();
10970b57cec5SDimitry Andric }
10980b57cec5SDimitry Andric 
10990b57cec5SDimitry Andric ProgramStateRef
11000b57cec5SDimitry Andric ObjCLoopChecker::checkPointerEscape(ProgramStateRef State,
11010b57cec5SDimitry Andric                                     const InvalidatedSymbols &Escaped,
11020b57cec5SDimitry Andric                                     const CallEvent *Call,
11030b57cec5SDimitry Andric                                     PointerEscapeKind Kind) const {
11040b57cec5SDimitry Andric   SymbolRef ImmutableReceiver = getMethodReceiverIfKnownImmutable(Call);
11050b57cec5SDimitry Andric 
1106bdd1243dSDimitry Andric   // Remove the invalidated symbols from the collection count map.
1107*06c3fb27SDimitry Andric   for (SymbolRef Sym : Escaped) {
11080b57cec5SDimitry Andric     // Don't invalidate this symbol's count if we know the method being called
11090b57cec5SDimitry Andric     // is declared on an immutable class. This isn't completely correct if the
11100b57cec5SDimitry Andric     // receiver is also passed as an argument, but in most uses of NSArray,
11110b57cec5SDimitry Andric     // NSDictionary, etc. this isn't likely to happen in a dangerous way.
11120b57cec5SDimitry Andric     if (Sym == ImmutableReceiver)
11130b57cec5SDimitry Andric       continue;
11140b57cec5SDimitry Andric 
11150b57cec5SDimitry Andric     // The symbol escaped. Pessimistically, assume that the count could have
11160b57cec5SDimitry Andric     // changed.
11170b57cec5SDimitry Andric     State = State->remove<ContainerCountMap>(Sym);
11180b57cec5SDimitry Andric     State = State->remove<ContainerNonEmptyMap>(Sym);
11190b57cec5SDimitry Andric   }
11200b57cec5SDimitry Andric   return State;
11210b57cec5SDimitry Andric }
11220b57cec5SDimitry Andric 
11230b57cec5SDimitry Andric void ObjCLoopChecker::checkDeadSymbols(SymbolReaper &SymReaper,
11240b57cec5SDimitry Andric                                        CheckerContext &C) const {
11250b57cec5SDimitry Andric   ProgramStateRef State = C.getState();
11260b57cec5SDimitry Andric 
11270b57cec5SDimitry Andric   // Remove the dead symbols from the collection count map.
11280b57cec5SDimitry Andric   ContainerCountMapTy Tracked = State->get<ContainerCountMap>();
1129*06c3fb27SDimitry Andric   for (SymbolRef Sym : llvm::make_first_range(Tracked)) {
11300b57cec5SDimitry Andric     if (SymReaper.isDead(Sym)) {
11310b57cec5SDimitry Andric       State = State->remove<ContainerCountMap>(Sym);
11320b57cec5SDimitry Andric       State = State->remove<ContainerNonEmptyMap>(Sym);
11330b57cec5SDimitry Andric     }
11340b57cec5SDimitry Andric   }
11350b57cec5SDimitry Andric 
11360b57cec5SDimitry Andric   C.addTransition(State);
11370b57cec5SDimitry Andric }
11380b57cec5SDimitry Andric 
11390b57cec5SDimitry Andric namespace {
11400b57cec5SDimitry Andric /// \class ObjCNonNilReturnValueChecker
11410b57cec5SDimitry Andric /// The checker restricts the return values of APIs known to
11420b57cec5SDimitry Andric /// never (or almost never) return 'nil'.
11430b57cec5SDimitry Andric class ObjCNonNilReturnValueChecker
11440b57cec5SDimitry Andric   : public Checker<check::PostObjCMessage,
11450b57cec5SDimitry Andric                    check::PostStmt<ObjCArrayLiteral>,
11460b57cec5SDimitry Andric                    check::PostStmt<ObjCDictionaryLiteral>,
11470b57cec5SDimitry Andric                    check::PostStmt<ObjCBoxedExpr> > {
11480b57cec5SDimitry Andric     mutable bool Initialized;
11490b57cec5SDimitry Andric     mutable Selector ObjectAtIndex;
11500b57cec5SDimitry Andric     mutable Selector ObjectAtIndexedSubscript;
11510b57cec5SDimitry Andric     mutable Selector NullSelector;
11520b57cec5SDimitry Andric 
11530b57cec5SDimitry Andric public:
11540b57cec5SDimitry Andric   ObjCNonNilReturnValueChecker() : Initialized(false) {}
11550b57cec5SDimitry Andric 
11560b57cec5SDimitry Andric   ProgramStateRef assumeExprIsNonNull(const Expr *NonNullExpr,
11570b57cec5SDimitry Andric                                       ProgramStateRef State,
11580b57cec5SDimitry Andric                                       CheckerContext &C) const;
11590b57cec5SDimitry Andric   void assumeExprIsNonNull(const Expr *E, CheckerContext &C) const {
11600b57cec5SDimitry Andric     C.addTransition(assumeExprIsNonNull(E, C.getState(), C));
11610b57cec5SDimitry Andric   }
11620b57cec5SDimitry Andric 
11630b57cec5SDimitry Andric   void checkPostStmt(const ObjCArrayLiteral *E, CheckerContext &C) const {
11640b57cec5SDimitry Andric     assumeExprIsNonNull(E, C);
11650b57cec5SDimitry Andric   }
11660b57cec5SDimitry Andric   void checkPostStmt(const ObjCDictionaryLiteral *E, CheckerContext &C) const {
11670b57cec5SDimitry Andric     assumeExprIsNonNull(E, C);
11680b57cec5SDimitry Andric   }
11690b57cec5SDimitry Andric   void checkPostStmt(const ObjCBoxedExpr *E, CheckerContext &C) const {
11700b57cec5SDimitry Andric     assumeExprIsNonNull(E, C);
11710b57cec5SDimitry Andric   }
11720b57cec5SDimitry Andric 
11730b57cec5SDimitry Andric   void checkPostObjCMessage(const ObjCMethodCall &M, CheckerContext &C) const;
11740b57cec5SDimitry Andric };
11750b57cec5SDimitry Andric } // end anonymous namespace
11760b57cec5SDimitry Andric 
11770b57cec5SDimitry Andric ProgramStateRef
11780b57cec5SDimitry Andric ObjCNonNilReturnValueChecker::assumeExprIsNonNull(const Expr *NonNullExpr,
11790b57cec5SDimitry Andric                                                   ProgramStateRef State,
11800b57cec5SDimitry Andric                                                   CheckerContext &C) const {
11810b57cec5SDimitry Andric   SVal Val = C.getSVal(NonNullExpr);
1182bdd1243dSDimitry Andric   if (std::optional<DefinedOrUnknownSVal> DV =
1183bdd1243dSDimitry Andric           Val.getAs<DefinedOrUnknownSVal>())
11840b57cec5SDimitry Andric     return State->assume(*DV, true);
11850b57cec5SDimitry Andric   return State;
11860b57cec5SDimitry Andric }
11870b57cec5SDimitry Andric 
11880b57cec5SDimitry Andric void ObjCNonNilReturnValueChecker::checkPostObjCMessage(const ObjCMethodCall &M,
11890b57cec5SDimitry Andric                                                         CheckerContext &C)
11900b57cec5SDimitry Andric                                                         const {
11910b57cec5SDimitry Andric   ProgramStateRef State = C.getState();
11920b57cec5SDimitry Andric 
11930b57cec5SDimitry Andric   if (!Initialized) {
11940b57cec5SDimitry Andric     ASTContext &Ctx = C.getASTContext();
11950b57cec5SDimitry Andric     ObjectAtIndex = GetUnarySelector("objectAtIndex", Ctx);
11960b57cec5SDimitry Andric     ObjectAtIndexedSubscript = GetUnarySelector("objectAtIndexedSubscript", Ctx);
11970b57cec5SDimitry Andric     NullSelector = GetNullarySelector("null", Ctx);
11980b57cec5SDimitry Andric   }
11990b57cec5SDimitry Andric 
12000b57cec5SDimitry Andric   // Check the receiver type.
12010b57cec5SDimitry Andric   if (const ObjCInterfaceDecl *Interface = M.getReceiverInterface()) {
12020b57cec5SDimitry Andric 
12030b57cec5SDimitry Andric     // Assume that object returned from '[self init]' or '[super init]' is not
12040b57cec5SDimitry Andric     // 'nil' if we are processing an inlined function/method.
12050b57cec5SDimitry Andric     //
12060b57cec5SDimitry Andric     // A defensive callee will (and should) check if the object returned by
12070b57cec5SDimitry Andric     // '[super init]' is 'nil' before doing it's own initialization. However,
12080b57cec5SDimitry Andric     // since 'nil' is rarely returned in practice, we should not warn when the
12090b57cec5SDimitry Andric     // caller to the defensive constructor uses the object in contexts where
12100b57cec5SDimitry Andric     // 'nil' is not accepted.
12110b57cec5SDimitry Andric     if (!C.inTopFrame() && M.getDecl() &&
12120b57cec5SDimitry Andric         M.getDecl()->getMethodFamily() == OMF_init &&
12130b57cec5SDimitry Andric         M.isReceiverSelfOrSuper()) {
12140b57cec5SDimitry Andric       State = assumeExprIsNonNull(M.getOriginExpr(), State, C);
12150b57cec5SDimitry Andric     }
12160b57cec5SDimitry Andric 
12170b57cec5SDimitry Andric     FoundationClass Cl = findKnownClass(Interface);
12180b57cec5SDimitry Andric 
12190b57cec5SDimitry Andric     // Objects returned from
12200b57cec5SDimitry Andric     // [NSArray|NSOrderedSet]::[ObjectAtIndex|ObjectAtIndexedSubscript]
12210b57cec5SDimitry Andric     // are never 'nil'.
12220b57cec5SDimitry Andric     if (Cl == FC_NSArray || Cl == FC_NSOrderedSet) {
12230b57cec5SDimitry Andric       Selector Sel = M.getSelector();
12240b57cec5SDimitry Andric       if (Sel == ObjectAtIndex || Sel == ObjectAtIndexedSubscript) {
12250b57cec5SDimitry Andric         // Go ahead and assume the value is non-nil.
12260b57cec5SDimitry Andric         State = assumeExprIsNonNull(M.getOriginExpr(), State, C);
12270b57cec5SDimitry Andric       }
12280b57cec5SDimitry Andric     }
12290b57cec5SDimitry Andric 
12300b57cec5SDimitry Andric     // Objects returned from [NSNull null] are not nil.
12310b57cec5SDimitry Andric     if (Cl == FC_NSNull) {
12320b57cec5SDimitry Andric       if (M.getSelector() == NullSelector) {
12330b57cec5SDimitry Andric         // Go ahead and assume the value is non-nil.
12340b57cec5SDimitry Andric         State = assumeExprIsNonNull(M.getOriginExpr(), State, C);
12350b57cec5SDimitry Andric       }
12360b57cec5SDimitry Andric     }
12370b57cec5SDimitry Andric   }
12380b57cec5SDimitry Andric   C.addTransition(State);
12390b57cec5SDimitry Andric }
12400b57cec5SDimitry Andric 
12410b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
12420b57cec5SDimitry Andric // Check registration.
12430b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
12440b57cec5SDimitry Andric 
12450b57cec5SDimitry Andric void ento::registerNilArgChecker(CheckerManager &mgr) {
12460b57cec5SDimitry Andric   mgr.registerChecker<NilArgChecker>();
12470b57cec5SDimitry Andric }
12480b57cec5SDimitry Andric 
12495ffd83dbSDimitry Andric bool ento::shouldRegisterNilArgChecker(const CheckerManager &mgr) {
12500b57cec5SDimitry Andric   return true;
12510b57cec5SDimitry Andric }
12520b57cec5SDimitry Andric 
12530b57cec5SDimitry Andric void ento::registerCFNumberChecker(CheckerManager &mgr) {
12540b57cec5SDimitry Andric   mgr.registerChecker<CFNumberChecker>();
12550b57cec5SDimitry Andric }
12560b57cec5SDimitry Andric 
12575ffd83dbSDimitry Andric bool ento::shouldRegisterCFNumberChecker(const CheckerManager &mgr) {
12580b57cec5SDimitry Andric   return true;
12590b57cec5SDimitry Andric }
12600b57cec5SDimitry Andric 
12610b57cec5SDimitry Andric void ento::registerCFRetainReleaseChecker(CheckerManager &mgr) {
12620b57cec5SDimitry Andric   mgr.registerChecker<CFRetainReleaseChecker>();
12630b57cec5SDimitry Andric }
12640b57cec5SDimitry Andric 
12655ffd83dbSDimitry Andric bool ento::shouldRegisterCFRetainReleaseChecker(const CheckerManager &mgr) {
12660b57cec5SDimitry Andric   return true;
12670b57cec5SDimitry Andric }
12680b57cec5SDimitry Andric 
12690b57cec5SDimitry Andric void ento::registerClassReleaseChecker(CheckerManager &mgr) {
12700b57cec5SDimitry Andric   mgr.registerChecker<ClassReleaseChecker>();
12710b57cec5SDimitry Andric }
12720b57cec5SDimitry Andric 
12735ffd83dbSDimitry Andric bool ento::shouldRegisterClassReleaseChecker(const CheckerManager &mgr) {
12740b57cec5SDimitry Andric   return true;
12750b57cec5SDimitry Andric }
12760b57cec5SDimitry Andric 
12770b57cec5SDimitry Andric void ento::registerVariadicMethodTypeChecker(CheckerManager &mgr) {
12780b57cec5SDimitry Andric   mgr.registerChecker<VariadicMethodTypeChecker>();
12790b57cec5SDimitry Andric }
12800b57cec5SDimitry Andric 
12815ffd83dbSDimitry Andric bool ento::shouldRegisterVariadicMethodTypeChecker(const CheckerManager &mgr) {
12820b57cec5SDimitry Andric   return true;
12830b57cec5SDimitry Andric }
12840b57cec5SDimitry Andric 
12850b57cec5SDimitry Andric void ento::registerObjCLoopChecker(CheckerManager &mgr) {
12860b57cec5SDimitry Andric   mgr.registerChecker<ObjCLoopChecker>();
12870b57cec5SDimitry Andric }
12880b57cec5SDimitry Andric 
12895ffd83dbSDimitry Andric bool ento::shouldRegisterObjCLoopChecker(const CheckerManager &mgr) {
12900b57cec5SDimitry Andric   return true;
12910b57cec5SDimitry Andric }
12920b57cec5SDimitry Andric 
12930b57cec5SDimitry Andric void ento::registerObjCNonNilReturnValueChecker(CheckerManager &mgr) {
12940b57cec5SDimitry Andric   mgr.registerChecker<ObjCNonNilReturnValueChecker>();
12950b57cec5SDimitry Andric }
12960b57cec5SDimitry Andric 
12975ffd83dbSDimitry Andric bool ento::shouldRegisterObjCNonNilReturnValueChecker(const CheckerManager &mgr) {
12980b57cec5SDimitry Andric   return true;
12990b57cec5SDimitry Andric }
1300