18#include "llvm/ADT/DenseSet.h"
26class RetainPtrCtorAdoptChecker
27 :
public Checker<check::ASTDecl<TranslationUnitDecl>> {
30 mutable BugReporter *BR =
nullptr;
31 mutable std::unique_ptr<RetainSummaryManager> Summaries;
32 mutable llvm::DenseSet<const ValueDecl *> CreateOrCopyOutArguments;
33 mutable llvm::DenseSet<const Expr *> CreateOrCopyFnCall;
34 mutable RetainTypeChecker RTC;
37 RetainPtrCtorAdoptChecker()
38 : Bug(this,
"Correct use of RetainPtr, adoptNS, and adoptCF",
39 "WebKit coding guidelines") {}
41 void checkASTDecl(
const TranslationUnitDecl *TUD, AnalysisManager &MGR,
42 BugReporter &BRArg)
const {
48 struct LocalVisitor :
public RecursiveASTVisitor<LocalVisitor> {
49 const RetainPtrCtorAdoptChecker *Checker;
50 Decl *DeclWithIssue{
nullptr};
52 using Base = RecursiveASTVisitor<LocalVisitor>;
54 explicit LocalVisitor(
const RetainPtrCtorAdoptChecker *Checker)
59 bool shouldVisitTemplateInstantiations()
const {
return true; }
60 bool shouldVisitImplicitCode()
const {
return false; }
62 bool TraverseDecl(Decl *D) {
63 llvm::SaveAndRestore SavedDecl(DeclWithIssue);
66 return Base::TraverseDecl(D);
69 bool TraverseClassTemplateDecl(ClassTemplateDecl *CTD) {
72 return Base::TraverseClassTemplateDecl(CTD);
75 bool VisitTypedefDecl(TypedefDecl *TD) {
80 bool VisitCallExpr(
const CallExpr *CE) {
81 Checker->visitCallExpr(CE, DeclWithIssue);
85 bool VisitCXXConstructExpr(
const CXXConstructExpr *CE) {
86 Checker->visitConstructExpr(CE, DeclWithIssue);
90 bool VisitObjCMessageExpr(
const ObjCMessageExpr *ObjCMsgExpr) {
91 Checker->visitObjCMessageExpr(ObjCMsgExpr, DeclWithIssue);
95 bool VisitReturnStmt(
const ReturnStmt *RS) {
96 Checker->visitReturnStmt(RS, DeclWithIssue);
100 bool VisitVarDecl(
const VarDecl *VD) {
101 Checker->visitVarDecl(VD);
105 bool VisitBinaryOperator(
const BinaryOperator *BO) {
106 Checker->visitBinaryOperator(BO);
111 LocalVisitor visitor(
this);
112 Summaries = std::make_unique<RetainSummaryManager>(
115 RTC.visitTranslationUnitDecl(TUD);
116 visitor.TraverseDecl(
const_cast<TranslationUnitDecl *
>(TUD));
119 bool isAdoptFn(
const Decl *FnDecl)
const {
123 bool isAdoptFnName(
const std::string &Name)
const {
124 return isAdoptNS(Name) || Name ==
"adoptCF" || Name ==
"adoptCFArc" ||
125 Name ==
"adoptCFNullable" || Name ==
"adoptCFNullableArc" ||
126 Name ==
"adoptOSObject" || Name ==
"adoptOSObjectArc";
129 bool isAdoptNS(
const std::string &Name)
const {
130 return Name ==
"adoptNS" || Name ==
"adoptNSArc" ||
131 Name ==
"adoptNSNullable" || Name ==
"adoptNSNullableArc";
134 void visitCallExpr(
const CallExpr *CE,
const Decl *DeclWithIssue)
const {
135 assert(BR &&
"expected nonnull BugReporter");
136 if (BR->getSourceManager().isInSystemHeader(CE->
getExprLoc()))
142 if (isAdoptFnName(FnName))
143 checkAdoptCall(CE, FnName, DeclWithIssue);
145 checkCreateOrCopyFunction(CE, DeclWithIssue);
146 checkBridgingRelease(CE, F, DeclWithIssue);
155 if (
auto *UnresolvedExpr = dyn_cast<UnresolvedLookupExpr>(CalleeExpr)) {
156 auto Name = UnresolvedExpr->getName();
157 if (!Name.isIdentifier())
159 FnName = Name.getAsString();
160 if (isAdoptFnName(FnName))
161 checkAdoptCall(CE, FnName, DeclWithIssue);
163 checkCreateOrCopyFunction(CE, DeclWithIssue);
166 void checkAdoptCall(
const CallExpr *CE,
const std::string &FnName,
167 const Decl *DeclWithIssue)
const {
172 auto Result = isOwned(Arg);
173 if (
Result == IsOwnedResult::Unknown)
174 Result = IsOwnedResult::NotOwned;
176 const Expr *Inner =
nullptr;
177 if (
isAllocInit(Arg, &Inner) || isCreateOrCopy(Arg)) {
179 CreateOrCopyFnCall.insert(Inner);
180 CreateOrCopyFnCall.insert(Arg);
183 if (
Result == IsOwnedResult::Owned ||
Result == IsOwnedResult::Skip ||
185 CreateOrCopyFnCall.insert(Arg);
189 if (
auto *DRE = dyn_cast<DeclRefExpr>(Arg)) {
190 if (CreateOrCopyOutArguments.contains(DRE->getDecl()))
193 if (RTC.isARCEnabled() && isAdoptFnName(FnName))
194 reportUseAfterFree(FnName, CE, DeclWithIssue,
"when ARC is disabled");
196 reportUseAfterFree(FnName, CE, DeclWithIssue);
199 void visitObjCMessageExpr(
const ObjCMessageExpr *ObjCMsgExpr,
200 const Decl *DeclWithIssue)
const {
201 if (BR->getSourceManager().isInSystemHeader(ObjCMsgExpr->
getExprLoc()))
205 if (Selector.getAsString() ==
"autorelease") {
209 ObjCMsgExpr = dyn_cast<ObjCMessageExpr>(Receiver);
212 const Expr *Inner =
nullptr;
215 CreateOrCopyFnCall.insert(ObjCMsgExpr);
217 CreateOrCopyFnCall.insert(Inner);
221 const Expr *Inner =
nullptr;
224 if (RTC.isARCEnabled())
226 if (CreateOrCopyFnCall.contains(ObjCMsgExpr))
229 CreateOrCopyFnCall.insert(Inner);
230 reportLeak(ObjCMsgExpr, DeclWithIssue);
233 void checkCreateOrCopyFunction(
const CallExpr *CE,
234 const Decl *DeclWithIssue)
const {
237 auto *FnDecl = CalleeDecl ? CalleeDecl->
getAsFunction() :
nullptr;
238 for (
unsigned ArgIndex = 0; ArgIndex < ArgCount; ++ArgIndex) {
240 auto *Unary = dyn_cast<UnaryOperator>(Arg);
243 if (Unary->getOpcode() != UO_AddrOf)
245 auto *SubExpr = Unary->getSubExpr();
248 auto *DRE = dyn_cast<DeclRefExpr>(SubExpr->IgnoreParenCasts());
251 auto *
Decl = DRE->getDecl();
254 if (FnDecl && ArgIndex < FnDecl->getNumParams()) {
257 auto *ParamDecl = FnDecl->getParamDecl(ArgIndex);
258 if (ParamDecl->hasAttr<CFReturnsRetainedAttr>())
259 CreateOrCopyOutArguments.insert(Decl);
263 if (RTC.isUnretained(
Decl->getType()))
264 CreateOrCopyOutArguments.insert(Decl);
267 auto Summary = Summaries->getSummary(AnyCall(CE));
268 switch (Summary->getRetEffect().getKind()) {
271 if (!CreateOrCopyFnCall.contains(CE))
272 reportLeak(CE, DeclWithIssue);
279 void checkBridgingRelease(
const CallExpr *CE,
const FunctionDecl *Callee,
280 const Decl *DeclWithIssue)
const {
285 auto *InnerCE = dyn_cast<CallExpr>(Arg);
289 auto *InnerF = InnerCE->getDirectCallee();
290 if (!InnerF || !isCreateOrCopyFunction(InnerF))
293 CreateOrCopyFnCall.insert(InnerCE);
296 void visitConstructExpr(
const CXXConstructExpr *CE,
297 const Decl *DeclWithIssue)
const {
298 assert(BR &&
"expected nonnull BugReporter");
299 if (BR->getSourceManager().isInSystemHeader(CE->
getExprLoc()))
314 if (isAdoptFn(DeclWithIssue) ||
safeGetName(DeclWithIssue) ==
"retainPtr")
317 std::string Name =
"RetainPtr constructor";
319 auto Result = isOwned(Arg);
321 if (isCreateOrCopy(Arg))
322 CreateOrCopyFnCall.insert(Arg);
324 const Expr *Inner =
nullptr;
326 CreateOrCopyFnCall.insert(Arg);
328 CreateOrCopyFnCall.insert(Inner);
331 if (
Result == IsOwnedResult::Skip)
334 if (
Result == IsOwnedResult::Unknown)
335 Result = IsOwnedResult::NotOwned;
336 if (
Result == IsOwnedResult::Owned)
337 reportLeak(Name, CE, DeclWithIssue);
339 reportLeak(Name, CE, DeclWithIssue,
"when ARC is disabled");
340 else if (isCreateOrCopy(Arg))
341 reportLeak(Name, CE, DeclWithIssue);
344 void visitVarDecl(
const VarDecl *VD)
const {
346 if (!
Init || !RTC.isARCEnabled())
349 const Expr *Inner =
nullptr;
351 CreateOrCopyFnCall.insert(
Init);
353 CreateOrCopyFnCall.insert(Inner);
357 void visitBinaryOperator(
const BinaryOperator *BO)
const {
363 const Expr *Inner =
nullptr;
365 CreateOrCopyFnCall.insert(RHS);
367 CreateOrCopyFnCall.insert(Inner);
371 auto *UO = dyn_cast<UnaryOperator>(LHS);
374 auto OpCode = UO->getOpcode();
375 if (OpCode != UO_Deref)
377 auto *DerefTarget = UO->getSubExpr();
380 DerefTarget = DerefTarget->IgnoreParenCasts();
381 auto *DRE = dyn_cast<DeclRefExpr>(DerefTarget);
384 auto *
Decl = DRE->getDecl();
389 if (
Decl->hasAttr<CFReturnsRetainedAttr>())
390 CreateOrCopyFnCall.insert(RHS);
393 void visitReturnStmt(
const ReturnStmt *RS,
const Decl *DeclWithIssue)
const {
400 std::optional<bool> retainsRet;
401 if (
auto *FnDecl = dyn_cast<FunctionDecl>(DeclWithIssue))
402 retainsRet = retainsReturnValue(FnDecl);
403 else if (
auto *MethodDecl = dyn_cast<ObjCMethodDecl>(DeclWithIssue))
404 retainsRet = retainsReturnValue(MethodDecl);
407 if (!retainsRet || !*retainsRet) {
409 if (RTC.isUnretained(
RetValue->getType()))
412 if (retainsRet && *retainsRet) {
413 CreateOrCopyFnCall.insert(
RetValue);
416 if (
auto *CE = dyn_cast<CallExpr>(
RetValue)) {
417 auto *
Callee = CE->getDirectCallee();
418 if (!Callee || !isCreateOrCopyFunction(Callee))
420 CreateOrCopyFnCall.insert(CE);
423 const Expr *Inner =
nullptr;
425 CreateOrCopyFnCall.insert(
RetValue);
427 CreateOrCopyFnCall.insert(Inner);
431 template <
typename CallableType>
432 std::optional<bool> retainsReturnValue(
const CallableType *FnDecl)
const {
433 auto Summary = Summaries->getSummary(AnyCall(FnDecl));
434 auto RetEffect = Summary->getRetEffect();
435 switch (RetEffect.getKind()) {
450 bool isCreateOrCopy(
const Expr *E)
const {
451 auto *CE = dyn_cast<CallExpr>(E);
454 auto *
Callee = CE->getDirectCallee();
457 return isCreateOrCopyFunction(Callee);
460 bool isCreateOrCopyFunction(
const FunctionDecl *FnDecl)
const {
462 return CalleeName.find(
"Create") != std::string::npos ||
463 CalleeName.find(
"Copy") != std::string::npos;
466 enum class IsOwnedResult {
Unknown,
Skip, Owned, NotOwned };
467 IsOwnedResult isOwned(
const Expr *E)
const {
469 if (
auto *POE = dyn_cast<PseudoObjectExpr>(E)) {
470 if (
unsigned SemanticExprCount = POE->getNumSemanticExprs()) {
471 E = POE->getSemanticExpr(SemanticExprCount - 1);
476 return IsOwnedResult::NotOwned;
477 if (
auto *DRE = dyn_cast<DeclRefExpr>(E)) {
478 auto QT = DRE->getType();
480 return IsOwnedResult::NotOwned;
481 QT = QT.getCanonicalType();
482 if (RTC.isUnretained(QT,
true ))
483 return IsOwnedResult::NotOwned;
484 auto *PointeeType = QT->getPointeeType().getTypePtrOrNull();
485 if (PointeeType && PointeeType->isVoidType())
486 return IsOwnedResult::NotOwned;
488 if (
auto *TE = dyn_cast<CXXBindTemporaryExpr>(E)) {
489 E = TE->getSubExpr();
492 if (
auto *ObjCMsgExpr = dyn_cast<ObjCMessageExpr>(E)) {
493 auto Summary = Summaries->getSummary(AnyCall(ObjCMsgExpr));
494 auto RetEffect = Summary->getRetEffect();
495 switch (RetEffect.getKind()) {
497 return IsOwnedResult::Unknown;
499 return IsOwnedResult::Owned;
501 return IsOwnedResult::NotOwned;
507 return IsOwnedResult::Unknown;
509 return IsOwnedResult::Unknown;
512 if (
auto *CXXCE = dyn_cast<CXXMemberCallExpr>(E)) {
513 if (
auto *MD = CXXCE->getMethodDecl()) {
514 auto *Cls = MD->getParent();
515 if (
auto *CD = dyn_cast<CXXConversionDecl>(MD)) {
516 auto QT = CD->getConversionType().getCanonicalType();
517 auto *ResultType = QT.getTypePtrOrNull();
519 (ResultType->isPointerType() || ResultType->isReferenceType() ||
520 ResultType->isObjCObjectPointerType()))
521 return IsOwnedResult::NotOwned;
525 return IsOwnedResult::Owned;
528 if (
auto *CE = dyn_cast<CallExpr>(E)) {
529 if (
auto *Callee = CE->getDirectCallee()) {
530 if (isAdoptFn(Callee))
531 return IsOwnedResult::NotOwned;
533 if (Name ==
"__builtin___CFStringMakeConstantString")
534 return IsOwnedResult::NotOwned;
535 if ((Name ==
"checked_cf_cast" || Name ==
"dynamic_cf_cast" ||
536 Name ==
"checked_objc_cast" || Name ==
"dynamic_objc_cast") &&
541 auto RetType =
Callee->getReturnType();
543 return IsOwnedResult::NotOwned;
544 if (isCreateOrCopyFunction(Callee)) {
545 CreateOrCopyFnCall.insert(CE);
546 return IsOwnedResult::Owned;
548 }
else if (
auto *CalleeExpr = CE->getCallee()) {
550 return IsOwnedResult::Skip;
552 return IsOwnedResult::Skip;
554 auto Summary = Summaries->getSummary(AnyCall(CE));
555 auto RetEffect = Summary->getRetEffect();
556 switch (RetEffect.getKind()) {
558 return IsOwnedResult::Unknown;
560 return IsOwnedResult::Owned;
562 return IsOwnedResult::NotOwned;
564 return IsOwnedResult::Unknown;
566 return IsOwnedResult::Unknown;
571 return IsOwnedResult::Unknown;
574 void reportUseAfterFree(
const std::string &Name,
const CallExpr *CE,
575 const Decl *DeclWithIssue,
577 SmallString<100> Buf;
578 llvm::raw_svector_ostream Os(Buf);
580 Os <<
"Incorrect use of " << Name
581 <<
". The argument is +0 and results in an use-after-free";
586 assert(BR &&
"expected nonnull BugReporter");
588 BR->getSourceManager());
589 auto Report = std::make_unique<BasicBugReport>(Bug, Os.str(), BSLoc);
591 Report->setDeclWithIssue(DeclWithIssue);
592 BR->emitReport(std::move(
Report));
595 void reportLeak(std::string &Name,
const CXXConstructExpr *CE,
596 const Decl *DeclWithIssue,
598 SmallString<100> Buf;
599 llvm::raw_svector_ostream Os(Buf);
601 Os <<
"Incorrect use of " << Name
602 <<
". The argument is +1 and results in a memory leak";
607 assert(BR &&
"expected nonnull BugReporter");
609 BR->getSourceManager());
610 auto Report = std::make_unique<BasicBugReport>(Bug, Os.str(), BSLoc);
612 Report->setDeclWithIssue(DeclWithIssue);
613 BR->emitReport(std::move(
Report));
616 template <
typename ExprType>
617 void reportLeak(
const ExprType *E,
const Decl *DeclWithIssue)
const {
618 SmallString<100> Buf;
619 llvm::raw_svector_ostream Os(Buf);
621 Os <<
"The return value is +1 and results in a memory leak.";
623 PathDiagnosticLocation BSLoc(E->getSourceRange().getBegin(),
624 BR->getSourceManager());
625 auto Report = std::make_unique<BasicBugReport>(Bug, Os.str(), BSLoc);
626 Report->addRange(E->getSourceRange());
627 Report->setDeclWithIssue(DeclWithIssue);
628 BR->emitReport(std::move(
Report));
633void ento::registerRetainPtrCtorAdoptChecker(
CheckerManager &Mgr) {
637bool ento::shouldRegisterRetainPtrCtorAdoptChecker(
const CheckerManager &mgr) {
static PRESERVE_NONE bool RetValue(InterpState &S, CodePtr &Ptr)
*collection of selector each with an associated kind and an ordered *collection of selectors A selector has a an optional score condition
static bool isAssignmentOp(Opcode Opc)
Expr * getArg(unsigned Arg)
Return the specified argument.
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
unsigned getNumArgs() const
Return the number of arguments to the constructor call.
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Expr * getInstanceReceiver()
Returns the object expression (receiver) for an instance message, or null for a message that is not a...
Selector getSelector() const
void visitTypedef(const TypedefDecl *)
SourceLocation getBegin() const
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
ASTContext & getASTContext() const
const Expr * getInit() const
CHECKER * registerChecker(AT &&...Args)
Register a single-part checker (derived from Checker): construct its singleton instance,...
Simple checker classes that implement one frontend (i.e.
@ OwnedSymbol
Indicates that the returned value is an owned (+1) symbol.
@ OwnedWhenTrackedReceiver
Indicates that the return value is an owned object when the receiver is also a tracked object.
@ NoRet
Indicates that no retain count information is tracked for the return value.
@ NotOwnedSymbol
Indicates that the returned value is an object with retain count semantics but that it is not owned (...
std::variant< struct RequiresDecl, struct HeaderDecl, struct UmbrellaDirDecl, struct ModuleDecl, struct ExcludeDecl, struct ExportDecl, struct ExportAsDecl, struct ExternModuleDecl, struct UseDecl, struct LinkDecl, struct ConfigMacrosDecl, struct ConflictDecl > Decl
All declarations that can appear in a module declaration.
The JSON file list parser is used to communicate input to InstallAPI.
bool isa(CodeGen::Address addr)
bool isRetainPtrOrOSPtrType(const clang::QualType T)
@ Result
The result type of a method or function.
bool isRetainPtrOrOSPtr(const std::string &Name)
std::string safeGetName(const T *ASTNode)
bool isNullPtr(const clang::Expr *E)
bool isAllocInit(const Expr *E, const Expr **InnerExpr)