33bool isRefcountedStringsHack(
const VarDecl *
V) {
35 auto safeClass = [](
const std::string &className) {
36 return className ==
"String" || className ==
"AtomString" ||
37 className ==
"UniquedString" || className ==
"Identifier";
41 if (
auto *CXXRD =
T->getAsCXXRecordDecl()) {
45 if (
T->isPointerType() ||
T->isReferenceType()) {
46 if (
auto *CXXRD =
T->getPointeeCXXRecordDecl()) {
55 const VarDecl *Guardian{
nullptr};
56 bool GuardianIsRawPtrOrRef{
false};
58 explicit GuardianVisitor(
const VarDecl *Guardian,
59 bool GuardianIsRawPtrOrRef =
false)
60 : Guardian(Guardian), GuardianIsRawPtrOrRef(GuardianIsRawPtrOrRef) {
64 bool VisitBinaryOperator(BinaryOperator *BO)
override {
66 if (
auto *VarRef = dyn_cast<DeclRefExpr>(BO->
getLHS())) {
67 if (VarRef->getDecl() == Guardian)
74 bool VisitCXXConstructExpr(CXXConstructExpr *CE)
override {
78 unsigned ArgIndex = 0;
80 ParmVarDecl *Parm =
nullptr;
81 if (ArgIndex < Ctor->getNumParams())
82 Parm = Ctor->getParamDecl(ArgIndex);
83 if (mutatesGuardian(Arg, Parm))
90 bool VisitCallExpr(CallExpr *CE)
override {
96 if (
auto *
Method = dyn_cast<CXXMethodDecl>(Callee)) {
101 auto *OperatorMethod = dyn_cast<CXXMethodDecl>(Callee);
103 !OperatorMethod->isImplicitObjectMemberFunction())
104 OperatorMethod =
nullptr;
105 unsigned ArgIndex = 0;
106 unsigned ArgOffset = OperatorMethod ? 1 : 0;
108 ParmVarDecl *Parm =
nullptr;
109 if (ArgIndex >= ArgOffset) {
110 unsigned ParmIndex = ArgIndex - ArgOffset;
111 if (ParmIndex < Callee->getNumParams())
112 Parm =
Callee->getParamDecl(ParmIndex);
113 }
else if (OperatorMethod->isConst()) {
117 if (mutatesGuardian(Arg, Parm))
124 bool VisitCXXMemberCallExpr(CXXMemberCallExpr *MCE)
override {
125 if (GuardianIsRawPtrOrRef)
129 if (ObjType.isConstQualified())
132 if (
auto *VarRef = dyn_cast<DeclRefExpr>(ThisArg)) {
140 bool mutatesGuardian(
const Expr *Arg,
const ParmVarDecl *ParmDecl) {
143 bool IsAddressOf =
false;
144 if (
auto *UO = dyn_cast<UnaryOperator>(Arg);
145 UO && UO->getOpcode() == UO_AddrOf) {
149 auto *VarRef = dyn_cast<DeclRefExpr>(Arg);
150 if (!VarRef || VarRef->getDecl() != Guardian)
152 if (GuardianIsRawPtrOrRef && !Guardian->getType()->isAnyPointerType())
155 if (!ArgType->isPointerType())
157 return !ArgType->getPointeeType().isConstQualified();
159 if (GuardianIsRawPtrOrRef) {
160 if (!ArgType->isReferenceType())
162 return !ArgType.getNonReferenceType().isConstQualified();
164 return !ArgType.getNonReferenceType().isConstQualified();
168bool isGuardedScopeEmbeddedInGuardianScope(
const VarDecl *Guarded,
169 const VarDecl *MaybeGuardian) {
171 assert(MaybeGuardian);
176 const CompoundStmt *guardiansClosestCompStmtAncestor =
nullptr;
181 !guardianAncestors.
empty();
186 for (
auto &guardianAncestor : guardianAncestors) {
187 if (
auto *CStmtParentAncestor = guardianAncestor.get<
CompoundStmt>()) {
188 guardiansClosestCompStmtAncestor = CStmtParentAncestor;
192 if (guardiansClosestCompStmtAncestor)
196 if (!guardiansClosestCompStmtAncestor)
203 !guardedVarAncestors.
empty();
208 for (
auto &guardedVarAncestor : guardedVarAncestors) {
209 if (
auto *CStmtAncestor = guardedVarAncestor.get<
CompoundStmt>()) {
210 if (!FirstCompondStmt) {
211 FirstCompondStmt = CStmtAncestor;
214 if (CStmtAncestor == guardiansClosestCompStmtAncestor) {
215 GuardianVisitor guardianVisitor(MaybeGuardian);
216 auto *GuardedScope =
const_cast<CompoundStmt *
>(FirstCompondStmt);
217 return guardianVisitor.TraverseCompoundStmt(GuardedScope);
229findObjCForCollectionStmtOfElement(
const VarDecl *
V) {
232 auto *DS = VarParent.get<
DeclStmt>();
233 if (!DS || !DS->isSingleDecl())
235 for (
auto &DeclStmtParent : Ctx.
getParents(*DS)) {
237 if (FCS && FCS->getElement() == DS)
244static const VarDecl *findAssignedVar(
const Expr *DestExpr) {
247 if (
auto *DRE = dyn_cast<DeclRefExpr>(DestExpr))
248 return dyn_cast_or_null<VarDecl>(DRE->getDecl());
249 if (
auto *UO = dyn_cast<UnaryOperator>(DestExpr);
250 UO && UO->getOpcode() == UO_Deref) {
251 DestExpr = UO->getSubExpr();
254 if (
auto *ASE = dyn_cast<ArraySubscriptExpr>(DestExpr)) {
255 DestExpr = ASE->getBase();
263class RawPtrRefLocalVarsChecker
264 :
public Checker<check::ASTDecl<TranslationUnitDecl>> {
266 EnsureFunctionAnalysis EFA;
269 mutable BugReporter *BR;
270 const std::unique_ptr<PtrRefSafetyModel> Model;
273 RawPtrRefLocalVarsChecker(
const char *description,
274 std::unique_ptr<PtrRefSafetyModel> Model)
275 : Bug(this, description,
"WebKit coding guidelines"),
276 Model(std::move(Model)) {}
278 std::optional<bool> isUnsafePtr(QualType
T)
const {
282 void checkASTDecl(
const TranslationUnitDecl *TUD, AnalysisManager &MGR,
283 BugReporter &BRArg)
const {
290 const RawPtrRefLocalVarsChecker *Checker;
291 Decl *DeclWithIssue{
nullptr};
293 TrivialFunctionAnalysis TFA;
295 explicit LocalVisitor(
const RawPtrRefLocalVarsChecker *Checker)
298 ShouldVisitTemplateInstantiations =
true;
299 ShouldVisitImplicitCode =
false;
302 bool TraverseDecl(Decl *D)
override {
310 llvm::SaveAndRestore SavedDecl(DeclWithIssue);
316 bool TraverseLambdaExpr(
LambdaExpr *L)
override {
319 return DynamicRecursiveASTVisitor::TraverseLambdaExpr(L);
329 for (
unsigned I = 0, N = L->
capture_size(); I != N; ++I) {
336 return TraverseDecl(FTD);
339 bool VisitTypedefDecl(TypedefDecl *TD)
override {
340 if (
auto *RTC = Checker->Model->retainTypeChecker())
341 RTC->visitTypedef(TD);
345 bool VisitVarDecl(VarDecl *
V)
override {
346 auto *
Init =
V->getInit();
347 if (
V->isLocalVarDecl())
348 Checker->visitVarDecl(
V,
V->getType(),
Init, DeclWithIssue);
352 bool VisitBinaryOperator(BinaryOperator *BO)
override {
354 if (Checker->Model->recognizesIndirectStores()) {
355 if (
auto *
V = findAssignedVar(BO->
getLHS()))
358 }
else if (
auto *VarRef = dyn_cast<DeclRefExpr>(BO->
getLHS())) {
359 if (
auto *
V = dyn_cast<VarDecl>(VarRef->getDecl()))
360 Checker->visitVarDecl(
V,
V->getType(), BO->
getRHS(),
367 bool TraverseIfStmt(IfStmt *IS)
override {
375 return TraverseStmt(Else);
380 return DynamicRecursiveASTVisitor::TraverseIfStmt(IS);
384 bool TraverseForStmt(ForStmt *FS)
override {
386 return DynamicRecursiveASTVisitor::TraverseForStmt(FS);
390 bool TraverseCXXForRangeStmt(CXXForRangeStmt *FRS)
override {
392 return DynamicRecursiveASTVisitor::TraverseCXXForRangeStmt(FRS);
396 bool TraverseWhileStmt(WhileStmt *WS)
override {
398 return DynamicRecursiveASTVisitor::TraverseWhileStmt(WS);
404 return DynamicRecursiveASTVisitor::TraverseCompoundStmt(CS);
408 bool TraverseClassTemplateDecl(ClassTemplateDecl *Decl)
override {
411 return DynamicRecursiveASTVisitor::TraverseClassTemplateDecl(Decl);
415 LocalVisitor visitor(
this);
416 if (
auto *RTC = Model->retainTypeChecker())
417 RTC->visitTranslationUnitDecl(TUD);
418 visitor.TraverseDecl(
const_cast<TranslationUnitDecl *
>(TUD));
421 void visitVarDecl(
const VarDecl *
V, QualType SinkType,
const Expr *
Value,
422 const Decl *DeclWithIssue)
const {
423 if (shouldSkipVarDecl(
V))
426 if (
auto *DD = dyn_cast<DecompositionDecl>(
V)) {
427 const auto *InitList =
429 if (InitList && InitList->getNumInits() != DD->bindings().size())
432 unsigned BindingIndex = 0;
433 for (
auto *BD : DD->bindings()) {
434 const unsigned Index = BindingIndex++;
435 auto *Binding = BD->getBinding();
438 std::optional<bool> IsUncountedPtr = isUnsafePtr(Binding->getType());
439 if (!IsUncountedPtr || !*IsUncountedPtr)
442 const Expr *Origin =
nullptr;
443 if (Model->checksForInteriorDestruction()) {
444 const Expr *Source = InitList ? InitList->getInit(Index) :
Value;
445 if (isPtrOriginSafe(
V, Source, DeclWithIssue, Origin,
449 reportBug(
V,
V->getType(),
nullptr, BD, DeclWithIssue, Origin);
453 std::optional<bool> IsUncountedPtr = isUnsafePtr(SinkType);
454 if (IsUncountedPtr && *IsUncountedPtr) {
455 const Expr *Origin =
nullptr;
460 if (
auto *FCS = findObjCForCollectionStmtOfElement(
V))
461 Value = FCS->getCollection();
464 if (isPtrOriginSafe(
V,
Value, DeclWithIssue, Origin, SinkType))
466 }
else if (Model->checksForInteriorDestruction())
468 reportBug(
V, SinkType,
Value,
nullptr, DeclWithIssue, Origin);
472 bool isPtrOriginSafe(
const VarDecl *
V,
const Expr *
Value,
473 const Decl *DeclWithIssue,
const Expr *&Origin,
474 QualType SinkType = QualType())
const {
477 Model->checksForInteriorDestruction(),
478 [&](
const clang::CXXRecordDecl *
Record) {
479 return Model->isSafePtr(Record);
481 [&](
const clang::QualType
Type) { return Model->isSafePtrType(Type); },
482 [&](
const clang::Decl *D) {
483 return Model->isSafeDecl(D, BR->getSourceManager());
485 [&](
const clang::Expr *InitArgOrigin,
bool IsSafe,
486 bool OriginDependsOnFullExpressionTemporary,
487 bool PtrIsLifetimeBoundToOrigin) {
492 if (!OriginDependsOnFullExpressionTemporary)
495 Origin = InitArgOrigin;
511 if (EFA.isACallToEnsureFn(InitArgOrigin))
514 if (Model->isSafeExpr(InitArgOrigin, PtrIsLifetimeBoundToOrigin,
518 if (!Model->checksForInteriorDestruction() &&
519 hasGuardian(
V, InitArgOrigin, DeclWithIssue))
523 Origin = InitArgOrigin;
528 bool hasGuardian(
const VarDecl *
V,
const Expr *InitArgOrigin,
529 const Decl *DeclWithIssue)
const {
530 auto *Ref = dyn_cast<DeclRefExpr>(InitArgOrigin);
534 auto *MaybeGuardian = dyn_cast_or_null<VarDecl>(Ref->getFoundDecl());
543 if (
auto *FCS = findObjCForCollectionStmtOfElement(
V);
546 GuardianVisitor Visitor(MaybeGuardian,
true);
547 return Visitor.TraverseStmt(
const_cast<Stmt *
>(FCS->getBody()));
550 if (!GuardianType.
isNull()) {
553 (Model->isSafePtr(
Record) ||
554 isRefcountedStringsHack(MaybeGuardian))) {
557 if (
auto *FCS = findObjCForCollectionStmtOfElement(
V)) {
558 GuardianVisitor Visitor(MaybeGuardian);
559 return Visitor.TraverseStmt(
const_cast<Stmt *
>(FCS->getBody()));
561 if (isGuardedScopeEmbeddedInGuardianScope(
V, MaybeGuardian))
568 bool IsRawPtrOrRef = isUnsafePtr(GuardianType).value_or(
false);
569 GuardianVisitor Visitor{MaybeGuardian, IsRawPtrOrRef};
570 if (
auto *FD = dyn_cast<FunctionDecl>(DeclWithIssue))
571 return Visitor.TraverseStmt(FD->getBody());
572 if (
auto *MD = dyn_cast<ObjCMethodDecl>(DeclWithIssue))
573 return Visitor.TraverseStmt(MD->getBody());
579 bool shouldSkipVarDecl(
const VarDecl *
V)
const {
583 if (
V->isInitCapture())
590 const Expr *Origin)
const {
593 llvm::raw_svector_ostream Os(Buf);
599 Model->describeHazard(Os, Origin, SinkType);
603 auto Report = std::make_unique<BasicBugReport>(Bug, Os.str(), BSLoc);
606 Report->setDeclWithIssue(DeclWithIssue);
609 if (
V->hasLocalStorage())
610 Os <<
"Local variable ";
611 else if (
V->isStaticLocal())
612 Os <<
"Static local variable ";
613 else if (
V->hasGlobalStorage())
614 Os <<
"Global variable ";
622 Model->describeHazard(Os, Origin, SinkType);
625 auto Report = std::make_unique<BasicBugReport>(Bug, Os.str(), BSLoc);
626 Report->addRange(
V->getSourceRange());
627 Report->setDeclWithIssue(DeclWithIssue);
633class UncountedLocalVarsChecker final :
public RawPtrRefLocalVarsChecker {
635 UncountedLocalVarsChecker()
636 : RawPtrRefLocalVarsChecker(
"Uncounted raw pointer or reference not "
637 "provably backed by ref-counted variable",
641class UncheckedLocalVarsChecker final :
public RawPtrRefLocalVarsChecker {
643 UncheckedLocalVarsChecker()
644 : RawPtrRefLocalVarsChecker(
"Unchecked raw pointer or reference not "
645 "provably backed by checked variable",
649class UnretainedLocalVarsChecker final :
public RawPtrRefLocalVarsChecker {
651 UnretainedLocalVarsChecker()
652 : RawPtrRefLocalVarsChecker(
"Unretained raw pointer or reference not "
653 "provably backed by a RetainPtr",
657class UnborrowedLocalVarsChecker final :
public RawPtrRefLocalVarsChecker {
659 UnborrowedLocalVarsChecker()
660 : RawPtrRefLocalVarsChecker(
"Unborrowed raw pointer or reference not "
661 "provably backed by a Borrow",
667void ento::registerUncountedLocalVarsChecker(
CheckerManager &Mgr) {
671bool ento::shouldRegisterUncountedLocalVarsChecker(
const CheckerManager &) {
675void ento::registerUncheckedLocalVarsChecker(
CheckerManager &Mgr) {
679bool ento::shouldRegisterUncheckedLocalVarsChecker(
const CheckerManager &) {
683void ento::registerUnretainedLocalVarsChecker(
CheckerManager &Mgr) {
687bool ento::shouldRegisterUnretainedLocalVarsChecker(
const CheckerManager &) {
691void ento::registerUnborrowedLocalVarsChecker(
CheckerManager &Mgr) {
695bool 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 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 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...
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...
bool isAnyPointerType() const
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...
const FunctionProtoType * T
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)