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)") {}
54 return ID->getIdentifier()->getName();
70 bool IncludeSuperclasses =
true) {
71 static llvm::StringMap<FoundationClass> Classes;
72 if (Classes.empty()) {
84 if (result ==
FC_None && IncludeSuperclasses)
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;
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,
120 bool CanBeSubscript =
false)
const;
137 void NilArgChecker::warnIfNilExpr(
const Expr *
E,
141 if (State->isNull(C.
getSVal(E)).isConstrainedTrue()) {
144 generateBugReport(N, Msg, E->getSourceRange(),
E, C);
153 bool CanBeSubscript)
const {
156 if (!State->isNull(msg.getArgSVal(Arg)).isConstrainedTrue())
161 llvm::raw_svector_ostream os(sbuf);
166 os <<
"Array element cannot be nil";
169 os <<
"Value stored into '";
176 llvm_unreachable(
"Missing foundation class for the subscript expr");
181 os <<
"Value argument ";
184 os <<
"Key argument ";
188 os <<
"' cannot be nil";
192 os <<
"' cannot be nil";
196 generateBugReport(N, os.str(), msg.getArgSourceRange(Arg),
207 BT.reset(
new APIMisuse(
this,
"nil argument"));
209 auto R = llvm::make_unique<BugReport>(*BT, Msg, N);
215 void NilArgChecker::checkPreObjCMessage(
const ObjCMethodCall &msg,
223 static const unsigned InvalidArgIndex =
UINT_MAX;
224 unsigned Arg = InvalidArgIndex;
225 bool CanBeSubscript =
false;
233 if (StringSelectors.empty()) {
251 StringSelectors[KnownSel] = 0;
253 auto I = StringSelectors.find(S);
254 if (
I == StringSelectors.end())
263 if (ArrayWithObjectSel.isNull()) {
267 InsertObjectAtIndexSel =
269 ReplaceObjectAtIndexWithObjectSel =
271 SetObjectAtIndexedSubscriptSel =
273 ArrayByAddingObjectSel =
277 if (S == ArrayWithObjectSel || S == AddObjectSel ||
278 S == InsertObjectAtIndexSel || S == ArrayByAddingObjectSel) {
280 }
else if (S == SetObjectAtIndexedSubscriptSel) {
282 CanBeSubscript =
true;
283 }
else if (S == ReplaceObjectAtIndexWithObjectSel) {
292 if (DictionaryWithObjectForKeySel.isNull()) {
294 DictionaryWithObjectForKeySel =
298 SetObjectForKeyedSubscriptSel =
300 RemoveObjectForKeySel =
304 if (S == DictionaryWithObjectForKeySel || S == SetObjectForKeySel) {
306 warnIfNilArg(C, msg, 1, Class);
307 }
else if (S == SetObjectForKeyedSubscriptSel) {
308 CanBeSubscript =
true;
310 }
else if (S == RemoveObjectForKeySel) {
316 if ((Arg != InvalidArgIndex))
317 warnIfNilArg(C, msg, Arg, Class, CanBeSubscript);
323 for (
unsigned i = 0; i < NumOfElements; ++i) {
324 warnIfNilExpr(AL->
getElement(i),
"Array element cannot be nil", C);
331 for (
unsigned i = 0; i < NumOfElements; ++i) {
333 warnIfNilExpr(Element.
Key,
"Dictionary key cannot be nil", C);
334 warnIfNilExpr(Element.
Value,
"Dictionary value cannot be nil", C);
343 class CFNumberCreateChecker :
public Checker< check::PreStmt<CallExpr> > {
344 mutable std::unique_ptr<APIMisuse> BT;
347 CFNumberCreateChecker() : II(nullptr) {}
353 uint64_t SourceSize, uint64_t TargetSize, uint64_t NumberKind);
377 static const unsigned char FixedSize[] = { 8, 16, 32, 64, 32, 64 };
380 return FixedSize[i-1];
404 static const char* GetCFNumberTypeStr(uint64_t i) {
405 static const char*
Names[] = {
406 "kCFNumberSInt8Type",
407 "kCFNumberSInt16Type",
408 "kCFNumberSInt32Type",
409 "kCFNumberSInt64Type",
410 "kCFNumberFloat32Type",
411 "kCFNumberFloat64Type",
413 "kCFNumberShortType",
416 "kCFNumberLongLongType",
417 "kCFNumberFloatType",
418 "kCFNumberDoubleType",
419 "kCFNumberCFIndexType",
420 "kCFNumberNSIntegerType",
421 "kCFNumberCGFloatType"
428 void CFNumberCreateChecker::checkPreStmt(
const CallExpr *CE,
444 SVal TheTypeVal = state->getSVal(CE->
getArg(1), LCtx);
452 uint64_t NumberKind = V->
getValue().getLimitedValue();
459 uint64_t TargetSize = *OptTargetSize;
464 SVal TheValueExpr = state->getSVal(CE->
getArg(2), LCtx);
487 if (SourceSize == TargetSize)
500 llvm::raw_svector_ostream os(sbuf);
502 os << (SourceSize == 8 ?
"An " :
"A ")
503 << SourceSize <<
" bit integer is used to initialize a CFNumber "
504 "object that represents "
505 << (TargetSize == 8 ?
"an " :
"a ")
506 << TargetSize <<
" bit integer. ";
508 if (SourceSize < TargetSize)
509 os << (TargetSize - SourceSize)
510 <<
" bits of the CFNumber value will be garbage." ;
512 os << (SourceSize - TargetSize)
513 <<
" bits of the input integer will be lost.";
516 BT.reset(
new APIMisuse(
this,
"Bad use of CFNumberCreate"));
518 auto report = llvm::make_unique<BugReport>(*BT, os.str(), N);
519 report->addRange(CE->
getArg(2)->getSourceRange());
529 class CFRetainReleaseChecker :
public Checker< check::PreStmt<CallExpr> > {
530 mutable std::unique_ptr<APIMisuse> BT;
534 CFRetainReleaseChecker()
541 void CFRetainReleaseChecker::checkPreStmt(
const CallExpr *CE,
558 BT.reset(
new APIMisuse(
559 this,
"null passed to CF memory management function"));
564 if (!(FuncII == Retain || FuncII == Release || FuncII ==
MakeCollectable ||
588 std::tie(stateTrue, stateFalse) = state->assume(ArgIsNull);
590 if (stateTrue && !stateFalse) {
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";
601 description =
"Null pointer argument in call to CFMakeCollectable";
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());
623 class ClassReleaseChecker :
public Checker<check::PreObjCMessage> {
628 mutable std::unique_ptr<BugType> BT;
635 void ClassReleaseChecker::checkPreObjCMessage(
const ObjCMethodCall &msg,
638 BT.reset(
new APIMisuse(
639 this,
"message incorrectly sent to class instead of class instance"));
654 if (!(S == releaseS || S == retainS || S == autoreleaseS || S == drainS))
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);
679 class VariadicMethodTypeChecker :
public Checker<check::PreObjCMessage> {
681 mutable Selector dictionaryWithObjectsAndKeysS;
683 mutable Selector orderedSetWithObjectsS;
685 mutable Selector initWithObjectsAndKeysS;
686 mutable std::unique_ptr<BugType> BT;
698 VariadicMethodTypeChecker::isVariadicMessage(
const ObjCMethodCall &msg)
const {
701 if (!MD || !MD->
isVariadic() || isa<ObjCProtocolDecl>(MD->getDeclContext()))
719 return S == initWithObjectsS;
721 return S == initWithObjectsAndKeysS;
730 return S == arrayWithObjectsS;
732 return S == orderedSetWithObjectsS;
734 return S == setWithObjectsS;
736 return S == dictionaryWithObjectsAndKeysS;
743 void VariadicMethodTypeChecker::checkPreObjCMessage(
const ObjCMethodCall &msg,
746 BT.reset(
new APIMisuse(
this,
747 "Arguments passed to variadic method aren't all "
748 "Objective-C pointer types"));
752 dictionaryWithObjectsAndKeysS =
761 if (!isVariadicMessage(msg))
770 unsigned variadicArgsEnd = msg.
getNumArgs() - 1;
772 if (variadicArgsEnd <= variadicArgsBegin)
776 Optional<ExplodedNode*> errorNode;
778 for (
unsigned I = variadicArgsBegin;
I != variadicArgsEnd; ++
I) {
800 if (!errorNode.hasValue())
803 if (!errorNode.getValue())
807 llvm::raw_svector_ostream os(sbuf);
810 if (!TypeName.empty())
811 os <<
"Argument to '" << TypeName <<
"' method '";
813 os <<
"Argument to method '";
816 os <<
"' should be an Objective-C pointer type, not '";
820 auto R = llvm::make_unique<BugReport>(*BT, os.str(), errorNode.getValue());
821 R->addRange(msg.getArgSourceRange(
I));
836 class ObjCLoopChecker
837 :
public Checker<check::PostStmt<ObjCForCollectionStmt>,
838 check::PostObjCMessage,
840 check::PointerEscape > {
847 ObjCLoopChecker() : CountSelectorII(nullptr) {}
891 if (!KnownCollection)
895 std::tie(StNonNil, StNil) = State->assume(*KnownCollection);
896 if (StNil && !StNonNil) {
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>();
935 SVal Val = State->getSVal(*ElementLoc);
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;
956 SVal CountGreaterThanZeroVal =
959 SvalBuilder.
makeIntVal(0, (*CountS)->getType()),
961 Optional<DefinedSVal> CountGreaterThanZero =
963 if (!CountGreaterThanZero) {
969 return State->assume(*CountGreaterThanZero, Assumption);
992 return BE->getSrc()->getLoopTarget() == FCS;
1028 bool ObjCLoopChecker::isCollectionCountMethod(
const ObjCMethodCall &M,
1032 if (!CountSelectorII)
1040 void ObjCLoopChecker::checkPostObjCMessage(
const ObjCMethodCall &M,
1062 if (!isCollectionCountMethod(M, C))
1071 State = State->set<ContainerCountMap>(ContainerS, CountS);
1073 if (
const bool *NonEmpty = State->get<ContainerNonEmptyMap>(ContainerS)) {
1074 State = State->remove<ContainerNonEmptyMap>(ContainerS);
1083 const ObjCMethodCall *Message = dyn_cast_or_null<ObjCMethodCall>(Call);
1092 if (isa<ObjCProtocolDecl>(MD->getDeclContext())) {
1128 for (InvalidatedSymbols::const_iterator
I = Escaped.begin(),
1137 if (Sym == ImmutableReceiver)
1142 State = State->remove<ContainerCountMap>(Sym);
1143 State = State->remove<ContainerNonEmptyMap>(Sym);
1148 void ObjCLoopChecker::checkDeadSymbols(
SymbolReaper &SymReaper,
1153 ContainerCountMapTy Tracked = State->get<ContainerCountMap>();
1155 E = Tracked.end();
I !=
E; ++
I) {
1157 if (SymReaper.
isDead(Sym)) {
1158 State = State->remove<ContainerCountMap>(Sym);
1159 State = State->remove<ContainerNonEmptyMap>(Sym);
1170 class ObjCNonNilReturnValueChecker
1171 :
public Checker<check::PostObjCMessage,
1172 check::PostStmt<ObjCArrayLiteral>,
1173 check::PostStmt<ObjCDictionaryLiteral>,
1174 check::PostStmt<ObjCBoxedExpr> > {
1177 mutable Selector ObjectAtIndexedSubscript;
1191 assumeExprIsNonNull(E, C);
1194 assumeExprIsNonNull(E, C);
1197 assumeExprIsNonNull(E, C);
1205 ObjCNonNilReturnValueChecker::assumeExprIsNonNull(
const Expr *NonNullExpr,
1210 return State->assume(*DV,
true);
1214 void ObjCNonNilReturnValueChecker::checkPostObjCMessage(
const ObjCMethodCall &M,
1222 ObjectAtIndexedSubscript =
GetUnarySelector(
"objectAtIndexedSubscript", Ctx);
1250 if (Sel == ObjectAtIndex || Sel == ObjectAtIndexedSubscript) {
1287 void ento::registerVariadicMethodTypeChecker(
CheckerManager &mgr) {
1296 ento::registerObjCNonNilReturnValueChecker(
CheckerManager &mgr) {
Defines the clang::ASTContext interface.
static Selector GetNullarySelector(StringRef name, ASTContext &Ctx)
Utility function for constructing a nullary selector.
FunctionDecl - An instance of this class is created to represent a function declaration or definition...
TypedValueRegion - An abstract class representing regions having a typed value.
nonloc::ConcreteInt makeIntVal(const IntegerLiteral *integer)
StringRef getName() const
getName - Get the name of identifier for this declaration as a StringRef.
Smart pointer class that efficiently represents Objective-C method names.
A (possibly-)qualified type.
ExplodedNode * generateErrorNode(ProgramStateRef State=nullptr, const ProgramPointTag *Tag=nullptr)
Generate a transition to a node that will be used to report an error.
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
ObjCInterfaceDecl * getClassInterface()
bool isInstanceMessage() const
static Selector GetUnarySelector(StringRef name, ASTContext &Ctx)
Utility function for constructing an unary selector.
static ProgramStateRef assumeCollectionNonEmpty(CheckerContext &C, ProgramStateRef State, SymbolRef CollectionS, bool Assumption)
Returns NULL state if the collection is known to contain elements (or is known not to contain element...
IdentifierInfo * getIdentifier() const
getIdentifier - Get the identifier that names this declaration, if there is one.
The argument acts as if has been passed to CFMakeCollectable, which transfers the object to the Garba...
ProgramPoint getLocation() const
getLocation - Returns the edge associated with the given node.
ExplodedNode * addTransition(ProgramStateRef State=nullptr, const ProgramPointTag *Tag=nullptr)
Generates a new transition in the program state graph (ExplodedGraph).
virtual QualType getValueType() const =0
static StringRef GetReceiverInterfaceName(const ObjCMethodCall &msg)
const Expr * getInit() const
SourceRange getSourceRange() const override
static Selector getKeywordSelector(ASTContext &Ctx, va_list argp)
bool isBlockPointerType() const
Value representing integer constant.
static ProgramStateRef checkCollectionNonNil(CheckerContext &C, ProgramStateRef State, const ObjCForCollectionStmt *FCS)
Assumes that the collection is non-nil.
ObjCDictionaryElement getKeyValueElement(unsigned Index) const
VarDecl - An instance of this class is created to represent a variable declaration or definition...
bool isReceiverSelfOrSuper() const
Checks if the receiver refers to 'self' or 'super'.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
ObjCMethodDecl - Represents an instance or class method declaration.
ExplodedNode * getPredecessor()
Returns the previous node in the exploded graph, which includes the state of the program before the c...
Defines the Objective-C statement AST node classes.
bool isZeroConstant() const
const ObjCInterfaceDecl * getReceiverInterface() const
Get the interface for the receiver.
One of these records is kept for each identifier that is lexed.
An element in an Objective-C dictionary literal.
IdentifierInfo * getIdentifierInfoForSlot(unsigned argIndex) const
Retrieve the identifier at a given position in the selector.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
const FunctionDecl * getCalleeDecl(const CallExpr *CE) const
Get the declaration of the called function (path-sensitive).
The argument is treated as if an -autorelease message had been sent to the referenced object...
static ProgramStateRef checkElementNonNil(CheckerContext &C, ProgramStateRef State, const ObjCForCollectionStmt *FCS)
Assumes that the collection elements are non-nil.
void addSymbolDependency(const SymbolRef Primary, const SymbolRef Dependent)
Add artificial symbol dependency.
ObjCArrayLiteral - used for objective-c array containers; as in: @["Hello", NSApp, [NSNumber numberWithInt:42]];.
i32 captured_struct **param SharedsTy A type which contains references the shared variables *param Shareds Context with the list of shared variables from the p *TaskFunction *param Data Additional data for task generation like final * state
Represents any expression that calls an Objective-C method.
SVal getReceiverSVal() const
Returns the value of the receiver at the time of this call.
ObjCMethodFamily getMethodFamily() const
Determines the family of this method.
void print(raw_ostream &OS, const PrintingPolicy &Policy, const Twine &PlaceHolder=Twine(), unsigned Indentation=0) const
Expr * Key
The key for the dictionary element.
void print(llvm::raw_ostream &OS) const
Prints the full selector name (e.g. "foo:bar:").
Represents an ObjC class declaration.
detail::InMemoryDirectory::const_iterator I
static SymbolRef getMethodReceiverIfKnownImmutable(const CallEvent *Call)
static bool isKnownNonNilCollectionType(QualType T)
The return type of classify().
#define REGISTER_MAP_WITH_PROGRAMSTATE(Name, Key, Value)
Declares an immutable map of type NameTy, suitable for placement into the ProgramState.
bool isUnarySelector() const
bool inTopFrame() const
Return true if the current LocationContext has no caller context.
bool isDead(SymbolRef sym) const
Returns whether or not a symbol has been confirmed dead.
DefinedOrUnknownSVal makeZeroVal(QualType type)
Construct an SVal representing '0' for the specified type.
Expr - This represents one expression.
static FoundationClass findKnownClass(const ObjCInterfaceDecl *ID, bool IncludeSuperclasses=true)
StringRef getName() const
Return the actual identifier string.
const ProgramStateRef & getState() const
unsigned getNumArgs() const
Optional< T > getAs() const
Convert to the specified SVal type, returning None if this SVal is not of the desired type...
ObjCDictionaryLiteral - AST node to represent objective-c dictionary literals; as in:"name" : NSUserN...
ObjCInterfaceDecl * getReceiverInterface() const
Retrieve the Objective-C interface to which this message is being directed, if known.
SymbolManager & getSymbolManager()
unsigned getNumElements() const
getNumElements - Return number of elements of objective-c array literal.
Expr * getElement(unsigned Index)
getExpr - Return the Expr at the specified index.
bool isCFObjectRef(QualType T)
SVal evalBinOp(ProgramStateRef state, BinaryOperator::Opcode op, SVal lhs, SVal rhs, QualType type)
ExplodedNode * generateNonFatalErrorNode(ProgramStateRef State=nullptr, const ProgramPointTag *Tag=nullptr)
Generate a transition to a node that will be used to report an error.
QualType getConditionType() const
void emitReport(std::unique_ptr< BugReport > R)
Emit the diagnostics report.
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
CHECKER * registerChecker()
Used to register checkers.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
const TemplateArgument * iterator
ExplodedNode * generateSink(ProgramStateRef State, ExplodedNode *Pred, const ProgramPointTag *Tag=nullptr)
Generate a sink node.
DeclStmt - Adaptor class for mixing declarations with statements and expressions. ...
SVal - This represents a symbolic expression, which can be either an L-value or an R-value...
Selector getSelector() const
A class responsible for cleaning up unused symbols.
ObjCBoxedExpr - used for generalized expression boxing.
const ObjCMethodDecl * getDecl() const override
Expr * Value
The value of the dictionary element.
ASTContext & getASTContext()
static bool alreadyExecutedAtLeastOneLoopIteration(const ExplodedNode *N, const ObjCForCollectionStmt *FCS)
If the fist block edge is a back edge, we are reentering the loop.
Represents symbolic expression.
detail::InMemoryDirectory::const_iterator E
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Represents an abstract call to a function or method along a particular path.
Optional< T > getAs() const
Convert to the specified ProgramPoint type, returning None if this ProgramPoint is not of the desired...
ObjCMessageKind getMessageKind() const
Returns how the message was written in the source (property access, subscript, or explicit message se...
PointerEscapeKind
Describes the different reasons a pointer escapes during analysis.
Represents a pointer to an Objective C object.
const LangOptions & getLangOpts() const
const ExplodedNode *const * const_pred_iterator
const T * getAs() const
Member-template getAs<specific type>'.
Represents Objective-C's collection statement.
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface...
unsigned getNumArgs() const override
const Expr * getArgExpr(unsigned Index) const override
DefinedOrUnknownSVal evalEQ(ProgramStateRef state, DefinedOrUnknownSVal lhs, DefinedOrUnknownSVal rhs)
bool isObjCObjectPointerType() const
bool trackNullOrUndefValue(const ExplodedNode *N, const Stmt *S, BugReport &R, bool IsArg=false, bool EnableNullFPSuppression=true)
Attempts to add visitors to trace a null or undefined value back to its point of origin, whether it is a symbol constrained to null or an explicit assignment.
pred_iterator pred_begin()
SymbolRef getAsSymbol(bool IncludeBaseRegions=false) const
If this SVal wraps a symbol return that SymbolRef.
SValBuilder & getSValBuilder()
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
ObjCInterfaceDecl * getSuperClass() const
static Optional< uint64_t > GetCFNumberSize(ASTContext &Ctx, uint64_t i)
A trivial tuple used to represent a source range.
static bool isObjCNSObjectType(QualType Ty)
Return true if this is an NSObject object with its NSObject attribute set.
virtual const ObjCMessageExpr * getOriginExpr() const
const llvm::APSInt & getValue() const
T castAs() const
Convert to the specified SVal type, asserting that this SVal is of the desired type.
unsigned getNumElements() const
getNumElements - Return number of elements of objective-c dictionary literal.
TypedRegion - An abstract class representing regions that are typed.
const LocationContext * getLocationContext() const
SVal getSVal(const Stmt *S) const
Get the value of arbitrary expressions at this point in the path.