32bool isRefcountedStringsHack(
const VarDecl *
V) {
34 auto safeClass = [](
const std::string &className) {
35 return className ==
"String" || className ==
"AtomString" ||
36 className ==
"UniquedString" || className ==
"Identifier";
40 if (
auto *CXXRD =
T->getAsCXXRecordDecl()) {
44 if (
T->isPointerType() ||
T->isReferenceType()) {
45 if (
auto *CXXRD =
T->getPointeeCXXRecordDecl()) {
54 const VarDecl *Guardian{
nullptr};
55 bool GuardianIsRawPtrOrRef{
false};
57 explicit GuardianVisitor(
const VarDecl *Guardian,
58 bool GuardianIsRawPtrOrRef =
false)
59 : Guardian(Guardian), GuardianIsRawPtrOrRef(GuardianIsRawPtrOrRef) {
63 bool VisitBinaryOperator(BinaryOperator *BO)
override {
65 if (
auto *VarRef = dyn_cast<DeclRefExpr>(BO->
getLHS())) {
66 if (VarRef->getDecl() == Guardian)
73 bool VisitCXXConstructExpr(CXXConstructExpr *CE)
override {
77 unsigned ArgIndex = 0;
79 ParmVarDecl *Parm =
nullptr;
80 if (ArgIndex < Ctor->getNumParams())
81 Parm = Ctor->getParamDecl(ArgIndex);
82 if (mutatesGuardian(Arg, Parm))
89 bool VisitCallExpr(CallExpr *CE)
override {
95 if (
auto *
Method = dyn_cast<CXXMethodDecl>(Callee)) {
99 unsigned ArgIndex = 0;
102 ParmVarDecl *Parm =
nullptr;
103 if (ArgIndex >= ArgOffset) {
104 unsigned ParmIndex = ArgIndex - ArgOffset;
105 if (ParmIndex < Callee->getNumParams())
106 Parm =
Callee->getParamDecl(ParmIndex);
108 if (mutatesGuardian(Arg, Parm))
115 bool VisitCXXMemberCallExpr(CXXMemberCallExpr *MCE)
override {
116 if (GuardianIsRawPtrOrRef)
120 if (ObjType.isConstQualified())
123 if (
auto *VarRef = dyn_cast<DeclRefExpr>(ThisArg)) {
131 bool mutatesGuardian(
const Expr *Arg,
const ParmVarDecl *ParmDecl) {
134 bool IsAddressOf =
false;
135 if (
auto *UO = dyn_cast<UnaryOperator>(Arg);
136 UO && UO->getOpcode() == UO_AddrOf) {
140 auto *VarRef = dyn_cast<DeclRefExpr>(Arg);
141 if (!VarRef || VarRef->getDecl() != Guardian)
143 if (GuardianIsRawPtrOrRef && !Guardian->getType()->isPointerType())
146 if (!ArgType->isPointerType())
148 return !ArgType->getPointeeType().isConstQualified();
150 if (GuardianIsRawPtrOrRef) {
151 if (!ArgType->isReferenceType())
153 return !ArgType.getNonReferenceType().isConstQualified();
155 return !ArgType.isConstQualified();
159bool isGuardedScopeEmbeddedInGuardianScope(
const VarDecl *Guarded,
160 const VarDecl *MaybeGuardian) {
162 assert(MaybeGuardian);
167 const CompoundStmt *guardiansClosestCompStmtAncestor =
nullptr;
172 !guardianAncestors.
empty();
177 for (
auto &guardianAncestor : guardianAncestors) {
178 if (
auto *CStmtParentAncestor = guardianAncestor.get<
CompoundStmt>()) {
179 guardiansClosestCompStmtAncestor = CStmtParentAncestor;
183 if (guardiansClosestCompStmtAncestor)
187 if (!guardiansClosestCompStmtAncestor)
194 !guardedVarAncestors.
empty();
199 for (
auto &guardedVarAncestor : guardedVarAncestors) {
200 if (
auto *CStmtAncestor = guardedVarAncestor.get<
CompoundStmt>()) {
201 if (!FirstCompondStmt) {
202 FirstCompondStmt = CStmtAncestor;
205 if (CStmtAncestor == guardiansClosestCompStmtAncestor) {
206 GuardianVisitor guardianVisitor(MaybeGuardian);
207 auto *GuardedScope =
const_cast<CompoundStmt *
>(FirstCompondStmt);
208 return guardianVisitor.TraverseCompoundStmt(GuardedScope);
217static const VarDecl *findAssignedVar(
const Expr *DestExpr) {
220 if (
auto *DRE = dyn_cast<DeclRefExpr>(DestExpr))
221 return dyn_cast_or_null<VarDecl>(DRE->getDecl());
222 if (
auto *UO = dyn_cast<UnaryOperator>(DestExpr);
223 UO && UO->getOpcode() == UO_Deref) {
224 DestExpr = UO->getSubExpr();
227 if (
auto *ASE = dyn_cast<ArraySubscriptExpr>(DestExpr)) {
228 DestExpr = ASE->getBase();
236class RawPtrRefLocalVarsChecker
237 :
public Checker<check::ASTDecl<TranslationUnitDecl>> {
239 EnsureFunctionAnalysis EFA;
242 mutable BugReporter *BR;
243 const std::unique_ptr<PtrRefSafetyModel> Model;
246 RawPtrRefLocalVarsChecker(
const char *description,
247 std::unique_ptr<PtrRefSafetyModel> Model)
248 : Bug(this, description,
"WebKit coding guidelines"),
249 Model(std::move(Model)) {}
251 std::optional<bool> isUnsafePtr(QualType
T)
const {
255 void checkASTDecl(
const TranslationUnitDecl *TUD, AnalysisManager &MGR,
256 BugReporter &BRArg)
const {
263 const RawPtrRefLocalVarsChecker *Checker;
264 Decl *DeclWithIssue{
nullptr};
266 TrivialFunctionAnalysis TFA;
268 explicit LocalVisitor(
const RawPtrRefLocalVarsChecker *Checker)
271 ShouldVisitTemplateInstantiations =
true;
272 ShouldVisitImplicitCode =
false;
275 bool TraverseDecl(Decl *D)
override {
283 llvm::SaveAndRestore SavedDecl(DeclWithIssue);
289 bool TraverseLambdaExpr(
LambdaExpr *L)
override {
292 return DynamicRecursiveASTVisitor::TraverseLambdaExpr(L);
302 for (
unsigned I = 0, N = L->
capture_size(); I != N; ++I) {
309 return TraverseDecl(FTD);
312 bool VisitTypedefDecl(TypedefDecl *TD)
override {
313 if (
auto *RTC = Checker->Model->retainTypeChecker())
314 RTC->visitTypedef(TD);
318 bool VisitVarDecl(VarDecl *
V)
override {
319 auto *
Init =
V->getInit();
320 if (
V->isLocalVarDecl())
321 Checker->visitVarDecl(
V,
V->getType(),
Init, DeclWithIssue);
325 bool VisitBinaryOperator(BinaryOperator *BO)
override {
327 if (Checker->Model->recognizesIndirectStores()) {
328 if (
auto *
V = findAssignedVar(BO->
getLHS()))
331 }
else if (
auto *VarRef = dyn_cast<DeclRefExpr>(BO->
getLHS())) {
332 if (
auto *
V = dyn_cast<VarDecl>(VarRef->getDecl()))
333 Checker->visitVarDecl(
V,
V->getType(), BO->
getRHS(),
340 bool TraverseIfStmt(IfStmt *IS)
override {
348 return TraverseStmt(Else);
353 return DynamicRecursiveASTVisitor::TraverseIfStmt(IS);
357 bool TraverseForStmt(ForStmt *FS)
override {
359 return DynamicRecursiveASTVisitor::TraverseForStmt(FS);
363 bool TraverseCXXForRangeStmt(CXXForRangeStmt *FRS)
override {
365 return DynamicRecursiveASTVisitor::TraverseCXXForRangeStmt(FRS);
369 bool TraverseWhileStmt(WhileStmt *WS)
override {
371 return DynamicRecursiveASTVisitor::TraverseWhileStmt(WS);
377 return DynamicRecursiveASTVisitor::TraverseCompoundStmt(CS);
381 bool TraverseClassTemplateDecl(ClassTemplateDecl *Decl)
override {
384 return DynamicRecursiveASTVisitor::TraverseClassTemplateDecl(Decl);
388 LocalVisitor visitor(
this);
389 if (
auto *RTC = Model->retainTypeChecker())
390 RTC->visitTranslationUnitDecl(TUD);
391 visitor.TraverseDecl(
const_cast<TranslationUnitDecl *
>(TUD));
394 void visitVarDecl(
const VarDecl *
V, QualType SinkType,
const Expr *
Value,
395 const Decl *DeclWithIssue)
const {
396 if (shouldSkipVarDecl(
V))
399 if (
auto *DD = dyn_cast<DecompositionDecl>(
V)) {
400 const auto *InitList =
402 if (InitList && InitList->getNumInits() != DD->bindings().size())
405 unsigned BindingIndex = 0;
406 for (
auto *BD : DD->bindings()) {
407 const unsigned Index = BindingIndex++;
408 auto *Binding = BD->getBinding();
411 std::optional<bool> IsUncountedPtr = isUnsafePtr(Binding->getType());
412 if (!IsUncountedPtr || !*IsUncountedPtr)
415 const Expr *Origin =
nullptr;
416 if (Model->checksForInteriorDestruction()) {
417 const Expr *Source = InitList ? InitList->getInit(Index) :
Value;
418 if (isPtrOriginSafe(
V, Source, DeclWithIssue, Origin))
421 reportBug(
V,
V->getType(),
nullptr, BD, DeclWithIssue, Origin);
425 std::optional<bool> IsUncountedPtr = isUnsafePtr(SinkType);
426 if (IsUncountedPtr && *IsUncountedPtr) {
427 const Expr *Origin =
nullptr;
429 if (isPtrOriginSafe(
V,
Value, DeclWithIssue, Origin))
431 }
else if (Model->checksForInteriorDestruction())
433 reportBug(
V, SinkType,
Value,
nullptr, DeclWithIssue, Origin);
437 bool isPtrOriginSafe(
const VarDecl *
V,
const Expr *
Value,
438 const Decl *DeclWithIssue,
const Expr *&Origin)
const {
441 Model->checksForInteriorDestruction(),
442 [&](
const clang::CXXRecordDecl *
Record) {
443 return Model->isSafePtr(Record);
445 [&](
const clang::QualType
Type) { return Model->isSafePtrType(Type); },
446 [&](
const clang::Decl *D) {
447 return Model->isSafeDecl(D, BR->getSourceManager());
449 [&](
const clang::Expr *InitArgOrigin,
bool IsSafe,
450 bool OriginDependsOnFullExpressionTemporary,
451 bool PtrIsLifetimeBoundToOrigin) {
456 if (!OriginDependsOnFullExpressionTemporary)
459 Origin = InitArgOrigin;
475 if (EFA.isACallToEnsureFn(InitArgOrigin))
478 if (Model->isSafeExpr(InitArgOrigin, PtrIsLifetimeBoundToOrigin))
481 if (!Model->checksForInteriorDestruction() &&
482 hasGuardian(
V, InitArgOrigin, DeclWithIssue))
486 Origin = InitArgOrigin;
491 bool hasGuardian(
const VarDecl *
V,
const Expr *InitArgOrigin,
492 const Decl *DeclWithIssue)
const {
493 auto *Ref = dyn_cast<DeclRefExpr>(InitArgOrigin);
497 auto *MaybeGuardian = dyn_cast_or_null<VarDecl>(Ref->getFoundDecl());
502 if (!GuardianType.
isNull()) {
505 (Model->isSafePtr(
Record) ||
506 isRefcountedStringsHack(MaybeGuardian)) &&
507 isGuardedScopeEmbeddedInGuardianScope(
V, MaybeGuardian))
513 bool IsRawPtrOrRef = isUnsafePtr(GuardianType).value_or(
false);
514 GuardianVisitor Visitor{MaybeGuardian, IsRawPtrOrRef};
515 if (
auto *FD = dyn_cast<FunctionDecl>(DeclWithIssue))
516 return Visitor.TraverseStmt(FD->getBody());
517 if (
auto *MD = dyn_cast<ObjCMethodDecl>(DeclWithIssue))
518 return Visitor.TraverseStmt(MD->getBody());
524 bool shouldSkipVarDecl(
const VarDecl *
V)
const {
528 if (
V->isInitCapture())
535 const Expr *Origin)
const {
538 llvm::raw_svector_ostream Os(Buf);
544 Model->describeHazard(Os, Origin, SinkType);
548 auto Report = std::make_unique<BasicBugReport>(Bug, Os.str(), BSLoc);
551 Report->setDeclWithIssue(DeclWithIssue);
554 if (
V->hasLocalStorage())
555 Os <<
"Local variable ";
556 else if (
V->isStaticLocal())
557 Os <<
"Static local variable ";
558 else if (
V->hasGlobalStorage())
559 Os <<
"Global variable ";
567 Model->describeHazard(Os, Origin, SinkType);
570 auto Report = std::make_unique<BasicBugReport>(Bug, Os.str(), BSLoc);
571 Report->addRange(
V->getSourceRange());
572 Report->setDeclWithIssue(DeclWithIssue);
578class UncountedLocalVarsChecker final :
public RawPtrRefLocalVarsChecker {
580 UncountedLocalVarsChecker()
581 : RawPtrRefLocalVarsChecker(
"Uncounted raw pointer or reference not "
582 "provably backed by ref-counted variable",
586class UncheckedLocalVarsChecker final :
public RawPtrRefLocalVarsChecker {
588 UncheckedLocalVarsChecker()
589 : RawPtrRefLocalVarsChecker(
"Unchecked raw pointer or reference not "
590 "provably backed by checked variable",
594class UnretainedLocalVarsChecker final :
public RawPtrRefLocalVarsChecker {
596 UnretainedLocalVarsChecker()
597 : RawPtrRefLocalVarsChecker(
"Unretained raw pointer or reference not "
598 "provably backed by a RetainPtr",
602class UnborrowedLocalVarsChecker final :
public RawPtrRefLocalVarsChecker {
604 UnborrowedLocalVarsChecker()
605 : RawPtrRefLocalVarsChecker(
"Loan on a CanBorrow object not guarded by "
612void ento::registerUncountedLocalVarsChecker(
CheckerManager &Mgr) {
616bool ento::shouldRegisterUncountedLocalVarsChecker(
const CheckerManager &) {
620void ento::registerUncheckedLocalVarsChecker(
CheckerManager &Mgr) {
624bool ento::shouldRegisterUncheckedLocalVarsChecker(
const CheckerManager &) {
628void ento::registerUnretainedLocalVarsChecker(
CheckerManager &Mgr) {
632bool ento::shouldRegisterUnretainedLocalVarsChecker(
const CheckerManager &) {
636void ento::registerUnborrowedLocalVarsChecker(
CheckerManager &Mgr) {
640bool 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.
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 }.
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.
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.
bool isTrivial(const Decl *D, const Stmt **OffendingStmt=nullptr) const
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
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)