34bool isRefcountedStringsHack(
const VarDecl *
V) {
36 auto safeClass = [](
const std::string &className) {
37 return className ==
"String" || className ==
"AtomString" ||
38 className ==
"UniquedString" || className ==
"Identifier";
42 if (
auto *CXXRD = T->getAsCXXRecordDecl()) {
46 if (T->isPointerType() || T->isReferenceType()) {
47 if (
auto *CXXRD = T->getPointeeCXXRecordDecl()) {
56 const VarDecl *Guardian{
nullptr};
57 bool GuardianIsRawPtrOrRef{
false};
59 explicit GuardianVisitor(
const VarDecl *Guardian,
60 bool GuardianIsRawPtrOrRef =
false)
61 : Guardian(Guardian), GuardianIsRawPtrOrRef(GuardianIsRawPtrOrRef) {
65 bool VisitBinaryOperator(BinaryOperator *BO)
override {
67 if (
auto *VarRef = dyn_cast<DeclRefExpr>(BO->
getLHS())) {
68 if (VarRef->getDecl() == Guardian)
75 bool VisitCXXConstructExpr(CXXConstructExpr *CE)
override {
79 unsigned ArgIndex = 0;
82 if (ArgIndex < Ctor->getNumParams())
83 ParamType = Ctor->getParamDecl(ArgIndex)->getType();
84 if (mutatesGuardian(Arg, ParamType))
91 bool VisitCallExpr(CallExpr *CE)
override {
94 return !indirectCallMutatesGuardian(CE);
97 if (
auto *
Method = dyn_cast<CXXMethodDecl>(Callee)) {
102 auto *OperatorMethod = dyn_cast<CXXMethodDecl>(Callee);
104 !OperatorMethod->isImplicitObjectMemberFunction())
105 OperatorMethod =
nullptr;
106 unsigned ArgIndex = 0;
107 unsigned ArgOffset = OperatorMethod ? 1 : 0;
110 if (ArgIndex >= ArgOffset) {
111 unsigned ParmIndex = ArgIndex - ArgOffset;
112 if (ParmIndex < Callee->getNumParams())
113 ParamType =
Callee->getParamDecl(ParmIndex)->getType();
114 }
else if (OperatorMethod->isConst()) {
118 if (mutatesGuardian(Arg, ParamType))
125 bool VisitCXXMemberCallExpr(CXXMemberCallExpr *MCE)
override {
126 if (GuardianIsRawPtrOrRef)
130 if (ObjType.isConstQualified())
134 if (
auto *
Prototype = getCalleePrototype(MCE);
139 if (
auto *UO = dyn_cast<UnaryOperator>(ThisArg);
140 UO && UO->getOpcode() == UO_AddrOf)
142 if (
auto *VarRef = dyn_cast<DeclRefExpr>(ThisArg)) {
143 if (!isa_and_nonnull<CXXConversionDecl>(
Method) &&
144 VarRef->getDecl() == Guardian)
153 static const FunctionProtoType *getCalleePrototype(
const CallExpr *CE) {
158 QualType CalleeType = CalleeExpr->
getType();
159 if (
auto *BO = dyn_cast<BinaryOperator>(CalleeExpr); BO && BO->
isPtrMemOp())
163 CalleeType = PointeeType;
164 return CalleeType->
getAs<FunctionProtoType>();
171 bool indirectCallMutatesGuardian(
const CallExpr *CE) {
172 if (Guardian->hasAttr<BlocksAttr>())
174 auto *
Prototype = getCalleePrototype(CE);
175 unsigned ArgIndex = 0;
178 if (
Prototype && ArgIndex < Prototype->getNumParams())
179 ParamType =
Prototype->getParamType(ArgIndex);
180 if (mutatesGuardian(Arg, ParamType))
187 bool mutatesGuardian(
const Expr *Arg, QualType ParamType) {
189 auto ArgType = !ParamType.
isNull() ? ParamType : Arg->
getType();
190 bool IsAddressOf =
false;
191 if (
auto *UO = dyn_cast<UnaryOperator>(Arg);
192 UO && UO->getOpcode() == UO_AddrOf) {
196 auto *VarRef = dyn_cast<DeclRefExpr>(Arg);
197 if (!VarRef || VarRef->getDecl() != Guardian)
199 if (GuardianIsRawPtrOrRef && !Guardian->getType()->isAnyPointerType())
202 if (!ArgType->isPointerType())
204 return !ArgType->getPointeeType().isConstQualified();
206 if (GuardianIsRawPtrOrRef) {
207 if (!ArgType->isReferenceType())
209 return !ArgType.getNonReferenceType().isConstQualified();
211 return !ArgType.getNonReferenceType().isConstQualified();
215bool isGuardedScopeEmbeddedInGuardianScope(
const VarDecl *Guarded,
216 const VarDecl *MaybeGuardian) {
218 assert(MaybeGuardian);
223 const CompoundStmt *guardiansClosestCompStmtAncestor =
nullptr;
228 !guardianAncestors.
empty();
233 for (
auto &guardianAncestor : guardianAncestors) {
234 if (
auto *CStmtParentAncestor = guardianAncestor.get<
CompoundStmt>()) {
235 guardiansClosestCompStmtAncestor = CStmtParentAncestor;
239 if (guardiansClosestCompStmtAncestor)
243 if (!guardiansClosestCompStmtAncestor)
250 !guardedVarAncestors.
empty();
255 for (
auto &guardedVarAncestor : guardedVarAncestors) {
256 if (
auto *CStmtAncestor = guardedVarAncestor.get<
CompoundStmt>()) {
257 if (!FirstCompondStmt) {
258 FirstCompondStmt = CStmtAncestor;
261 if (CStmtAncestor == guardiansClosestCompStmtAncestor) {
262 GuardianVisitor guardianVisitor(MaybeGuardian);
263 auto *GuardedScope =
const_cast<CompoundStmt *
>(FirstCompondStmt);
264 return guardianVisitor.TraverseCompoundStmt(GuardedScope);
276findObjCForCollectionStmtOfElement(
const VarDecl *
V) {
279 auto *DS = VarParent.get<
DeclStmt>();
280 if (!DS || !DS->isSingleDecl())
282 for (
auto &DeclStmtParent : Ctx.
getParents(*DS)) {
284 if (FCS && FCS->getElement() == DS)
291static const VarDecl *findAssignedVar(
const Expr *DestExpr) {
294 if (
auto *DRE = dyn_cast<DeclRefExpr>(DestExpr))
295 return dyn_cast_or_null<VarDecl>(DRE->getDecl());
296 if (
auto *UO = dyn_cast<UnaryOperator>(DestExpr);
297 UO && UO->getOpcode() == UO_Deref) {
298 DestExpr = UO->getSubExpr();
301 if (
auto *ASE = dyn_cast<ArraySubscriptExpr>(DestExpr)) {
302 DestExpr = ASE->getBase();
310class RawPtrRefLocalVarsChecker
311 :
public Checker<check::ASTDecl<TranslationUnitDecl>> {
313 EnsureFunctionAnalysis EFA;
316 mutable BugReporter *BR;
317 const std::unique_ptr<PtrRefSafetyModel> Model;
320 RawPtrRefLocalVarsChecker(
const char *description,
321 std::unique_ptr<PtrRefSafetyModel> Model)
322 : Bug(this, description,
"WebKit coding guidelines"),
323 Model(std::move(Model)) {}
325 std::optional<bool> isUnsafePtr(QualType T)
const {
329 void checkASTDecl(
const TranslationUnitDecl *TUD, AnalysisManager &MGR,
330 BugReporter &BRArg)
const {
337 const RawPtrRefLocalVarsChecker *Checker;
338 Decl *DeclWithIssue{
nullptr};
340 TrivialFunctionAnalysis TFA;
342 explicit LocalVisitor(
const RawPtrRefLocalVarsChecker *Checker)
345 ShouldVisitTemplateInstantiations =
true;
346 ShouldVisitImplicitCode =
false;
349 bool TraverseDecl(Decl *D)
override {
357 llvm::SaveAndRestore SavedDecl(DeclWithIssue);
363 bool TraverseLambdaExpr(
LambdaExpr *L)
override {
366 return DynamicRecursiveASTVisitor::TraverseLambdaExpr(L);
376 for (
unsigned I = 0, N = L->
capture_size(); I != N; ++I) {
383 return TraverseDecl(FTD);
386 bool VisitTypedefDecl(TypedefDecl *TD)
override {
387 if (
auto *RTC = Checker->Model->retainTypeChecker())
388 RTC->visitTypedef(TD);
392 bool VisitVarDecl(VarDecl *
V)
override {
393 auto *
Init =
V->getInit();
394 if (
V->isLocalVarDecl())
395 Checker->visitVarDecl(
V,
V->getType(),
Init, DeclWithIssue);
399 bool VisitBinaryOperator(BinaryOperator *BO)
override {
401 if (Checker->Model->recognizesIndirectStores()) {
402 if (
auto *
V = findAssignedVar(BO->
getLHS()))
405 }
else if (
auto *VarRef = dyn_cast<DeclRefExpr>(BO->
getLHS())) {
406 if (
auto *
V = dyn_cast<VarDecl>(VarRef->getDecl()))
407 Checker->visitVarDecl(
V,
V->getType(), BO->
getRHS(),
414 bool TraverseIfStmt(IfStmt *IS)
override {
422 return TraverseStmt(Else);
427 return DynamicRecursiveASTVisitor::TraverseIfStmt(IS);
431 bool TraverseForStmt(ForStmt *FS)
override {
433 return DynamicRecursiveASTVisitor::TraverseForStmt(FS);
437 bool TraverseCXXForRangeStmt(CXXForRangeStmt *FRS)
override {
439 return DynamicRecursiveASTVisitor::TraverseCXXForRangeStmt(FRS);
443 bool TraverseWhileStmt(WhileStmt *WS)
override {
445 return DynamicRecursiveASTVisitor::TraverseWhileStmt(WS);
451 return DynamicRecursiveASTVisitor::TraverseCompoundStmt(CS);
455 bool TraverseClassTemplateDecl(ClassTemplateDecl *Decl)
override {
458 return DynamicRecursiveASTVisitor::TraverseClassTemplateDecl(Decl);
462 LocalVisitor visitor(
this);
463 if (
auto *RTC = Model->retainTypeChecker())
464 RTC->visitTranslationUnitDecl(TUD);
465 visitor.TraverseDecl(
const_cast<TranslationUnitDecl *
>(TUD));
468 void visitVarDecl(
const VarDecl *
V, QualType SinkType,
const Expr *
Value,
469 const Decl *DeclWithIssue)
const {
470 if (shouldSkipVarDecl(
V))
473 if (
auto *DD = dyn_cast<DecompositionDecl>(
V)) {
474 const auto *InitList =
476 if (InitList && InitList->getNumInits() != DD->bindings().size())
479 unsigned BindingIndex = 0;
480 for (
auto *BD : DD->bindings()) {
481 const unsigned Index = BindingIndex++;
482 auto *Binding = BD->getBinding();
485 std::optional<bool> IsUncountedPtr = isUnsafePtr(Binding->getType());
486 if (!IsUncountedPtr || !*IsUncountedPtr)
489 const Expr *Origin =
nullptr;
490 if (Model->checksForInteriorDestruction()) {
491 const Expr *Source = InitList ? InitList->getInit(Index) :
Value;
492 if (isPtrOriginSafe(
V, Source, DeclWithIssue, Origin,
496 reportBug(
V,
V->getType(),
nullptr, BD, DeclWithIssue, Origin);
500 std::optional<bool> IsUncountedPtr = isUnsafePtr(SinkType);
501 if (IsUncountedPtr && *IsUncountedPtr) {
502 const Expr *Origin =
nullptr;
507 if (
auto *FCS = findObjCForCollectionStmtOfElement(
V))
508 Value = FCS->getCollection();
511 if (isPtrOriginSafe(
V,
Value, DeclWithIssue, Origin, SinkType))
513 }
else if (Model->checksForInteriorDestruction())
515 reportBug(
V, SinkType,
Value,
nullptr, DeclWithIssue, Origin);
519 bool isPtrOriginSafe(
const VarDecl *
V,
const Expr *
Value,
520 const Decl *DeclWithIssue,
const Expr *&Origin,
521 QualType SinkType = QualType())
const {
524 Model->checksForInteriorDestruction(),
525 [&](
const clang::CXXRecordDecl *
Record) {
526 return Model->isSafePtr(Record);
528 [&](
const clang::QualType
Type) { return Model->isSafePtrType(Type); },
529 [&](
const clang::Decl *D) {
530 return Model->isSafeDecl(D, BR->getSourceManager());
532 [&](
const clang::Expr *InitArgOrigin,
bool IsSafe,
533 bool OriginDependsOnFullExpressionTemporary,
534 bool PtrIsLifetimeBoundToOrigin) {
539 if (!OriginDependsOnFullExpressionTemporary)
542 Origin = InitArgOrigin;
558 if (EFA.isACallToEnsureFn(InitArgOrigin))
561 if (Model->isSafeExpr(InitArgOrigin, PtrIsLifetimeBoundToOrigin,
565 if (!Model->checksForInteriorDestruction() &&
566 hasGuardian(
V, InitArgOrigin, DeclWithIssue))
570 Origin = InitArgOrigin;
575 bool hasGuardian(
const VarDecl *
V,
const Expr *InitArgOrigin,
576 const Decl *DeclWithIssue)
const {
577 auto *Ref = dyn_cast<DeclRefExpr>(InitArgOrigin);
581 auto *MaybeGuardian = dyn_cast_or_null<VarDecl>(Ref->getFoundDecl());
590 if (
auto *FCS = findObjCForCollectionStmtOfElement(
V);
593 GuardianVisitor Visitor(MaybeGuardian,
true);
594 return Visitor.TraverseStmt(
const_cast<Stmt *
>(FCS->getBody()));
597 if (!GuardianType.
isNull()) {
600 (Model->isSafePtr(
Record) ||
601 isRefcountedStringsHack(MaybeGuardian))) {
604 if (
auto *FCS = findObjCForCollectionStmtOfElement(
V)) {
605 GuardianVisitor Visitor(MaybeGuardian);
606 return Visitor.TraverseStmt(
const_cast<Stmt *
>(FCS->getBody()));
608 if (isGuardedScopeEmbeddedInGuardianScope(
V, MaybeGuardian))
615 bool IsRawPtrOrRef = isUnsafePtr(GuardianType).value_or(
false);
616 GuardianVisitor Visitor{MaybeGuardian, IsRawPtrOrRef};
617 if (
auto *FD = dyn_cast<FunctionDecl>(DeclWithIssue))
618 return Visitor.TraverseStmt(FD->getBody());
619 if (
auto *MD = dyn_cast<ObjCMethodDecl>(DeclWithIssue))
620 return Visitor.TraverseStmt(MD->getBody());
626 bool shouldSkipVarDecl(
const VarDecl *
V)
const {
630 if (
V->isInitCapture())
637 const Expr *Origin)
const {
640 llvm::raw_svector_ostream Os(Buf);
646 Model->describeHazard(Os, Origin, SinkType);
650 auto Report = std::make_unique<BasicBugReport>(Bug, Os.str(), BSLoc);
653 Report->setDeclWithIssue(DeclWithIssue);
656 if (
V->hasLocalStorage())
657 Os <<
"Local variable ";
658 else if (
V->isStaticLocal())
659 Os <<
"Static local variable ";
660 else if (
V->hasGlobalStorage())
661 Os <<
"Global variable ";
669 Model->describeHazard(Os, Origin, SinkType);
672 auto Report = std::make_unique<BasicBugReport>(Bug, Os.str(), BSLoc);
673 Report->addRange(
V->getSourceRange());
674 Report->setDeclWithIssue(DeclWithIssue);
680class UncountedLocalVarsChecker final :
public RawPtrRefLocalVarsChecker {
682 UncountedLocalVarsChecker()
683 : RawPtrRefLocalVarsChecker(
"Uncounted raw pointer or reference not "
684 "provably backed by ref-counted variable",
688class UncheckedLocalVarsChecker final :
public RawPtrRefLocalVarsChecker {
690 UncheckedLocalVarsChecker()
691 : RawPtrRefLocalVarsChecker(
"Unchecked raw pointer or reference not "
692 "provably backed by checked variable",
696class UnretainedLocalVarsChecker final :
public RawPtrRefLocalVarsChecker {
698 UnretainedLocalVarsChecker()
699 : RawPtrRefLocalVarsChecker(
"Unretained raw pointer or reference not "
700 "provably backed by a RetainPtr",
704class UnborrowedLocalVarsChecker final :
public RawPtrRefLocalVarsChecker {
706 UnborrowedLocalVarsChecker()
707 : RawPtrRefLocalVarsChecker(
"Unborrowed raw pointer or reference not "
708 "provably backed by a Borrow",
714void ento::registerUncountedLocalVarsChecker(
CheckerManager &Mgr) {
718bool ento::shouldRegisterUncountedLocalVarsChecker(
const CheckerManager &) {
722void ento::registerUncheckedLocalVarsChecker(
CheckerManager &Mgr) {
726bool ento::shouldRegisterUncheckedLocalVarsChecker(
const CheckerManager &) {
730void ento::registerUnretainedLocalVarsChecker(
CheckerManager &Mgr) {
734bool ento::shouldRegisterUnretainedLocalVarsChecker(
const CheckerManager &) {
738void ento::registerUnborrowedLocalVarsChecker(
CheckerManager &Mgr) {
742bool ento::shouldRegisterUnborrowedLocalVarsChecker(
const CheckerManager &) {
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
llvm::MachO::Record Record
Defines the clang::SourceLocation class and associated facilities.
Defines the SourceManager interface.
Defines the Objective-C statement AST node classes.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
DynTypedNodeList getParents(const NodeT &Node)
Forwards to get node parents from the ParentMapContext.
static bool isPtrMemOp(Opcode Opc)
predicates to categorize the respective opcodes.
static bool isAssignmentOp(Opcode Opc)
A binding in a decomposition declaration.
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
CXXMethodDecl * getMethodDecl() const
Retrieve the declaration of the called method.
Expr * getImplicitObjectArgument() const
Retrieve the implicit object argument for the member call.
QualType getObjectType() const
Retrieve the type of the object argument.
FunctionTemplateDecl * getDependentLambdaCallOperator() const
Retrieve the dependent lambda call operator of the closure type if this is a templated closure type.
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
CompoundStmt - This represents a group of statements like { stmt stmt }.
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Decl - This represents one declaration (or definition), e.g.
ASTContext & getASTContext() const LLVM_READONLY
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
Container for either a single DynTypedNode or for an ArrayRef to DynTypedNode.
virtual bool TraverseDecl(MaybeConst< Decl > *D)
This represents one expression.
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
VarDecl * getConditionVariable()
Retrieve the variable declared in this "if" statement, if any.
capture_iterator capture_begin() const
Retrieve an iterator pointing to the first lambda capture.
unsigned capture_size() const
Determine the number of captures in this lambda.
capture_init_iterator capture_init_begin()
Retrieve the first initialization argument for this lambda expression (which initializes the first ca...
CXXRecordDecl * getLambdaClass() const
Retrieve the class that corresponds to the lambda.
Represents Objective-C's collection statement.
A (possibly-)qualified type.
bool isNull() const
Return true if this QualType doesn't point to a type yet.
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Encodes a location in the source.
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
Stmt - This represents one statement.
bool isTrivial(const Decl *D) const
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
bool isAnyPointerType() const
const T * getAs() const
Member-template getAs<specific type>'.
Represents a variable declaration or definition.
bool isLocalVarDecl() const
Returns true for local variable declarations other than parameters.
const SourceManager & getSourceManager()
virtual void emitReport(std::unique_ptr< BugReport > R)
Add the given report to the set of reports tracked by BugReporter.
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.
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.
Top level wrappers for InstallAPI frontend operations.
bool isa(CodeGen::Address addr)
std::unique_ptr< PtrRefSafetyModel > makeBorrowSafetyModel()
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
bool isPtrConversion(const FunctionDecl *F)
std::unique_ptr< PtrRefSafetyModel > makeCheckedPtrSafetyModel()
void printQuotedQualifiedName(llvm::raw_ostream &Os, const NamedDeclDerivedT &D)
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
std::optional< bool > isUnsafePtrForStorage(const PtrRefSafetyModel &Model, QualType T, bool IgnoreARC=false)
Applies the memory-management exemptions that hold for a variable, member, or lambda capture (but not...
bool isSmartPtrClass(const std::string &Name)
std::optional< bool > isGetterOfSafePtr(const CXXMethodDecl *M)
std::string safeGetName(const T *ASTNode)
bool isNullPtr(const clang::Expr *E)
DynamicRecursiveASTVisitorBase< false > DynamicRecursiveASTVisitor
std::unique_ptr< PtrRefSafetyModel > makeRefPtrSafetyModel()
bool tryToFindPtrOrigin(const Expr *E, bool StopAtFirstRefCountedObj, bool FollowLifetimeBound, std::function< bool(const clang::CXXRecordDecl *)> isSafePtr, std::function< bool(const clang::QualType)> isSafePtrType, std::function< bool(const clang::Decl *)> isSafeGlobalDecl, std::function< bool(const clang::Expr *, bool, bool, bool)> callback)
This function de-facto defines a set of transformations that we consider safe (in heuristical sense).
std::unique_ptr< PtrRefSafetyModel > makeRetainPtrSafetyModel()
bool isConstOwnerPtrMemberExpr(const clang::Expr *E)