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};
56 explicit GuardianVisitor(
const VarDecl *Guardian) : Guardian(Guardian) {
60 bool VisitBinaryOperator(BinaryOperator *BO)
override {
62 if (
auto *VarRef = dyn_cast<DeclRefExpr>(BO->
getLHS())) {
63 if (VarRef->getDecl() == Guardian)
70 bool VisitCXXConstructExpr(CXXConstructExpr *CE)
override {
74 unsigned ArgIndex = 0;
76 ParmVarDecl *Parm =
nullptr;
77 if (ArgIndex < Ctor->getNumParams())
78 Parm = Ctor->getParamDecl(ArgIndex);
79 if (mutatesGuardian(Arg, Parm))
86 bool VisitCallExpr(CallExpr *CE)
override {
92 unsigned ArgIndex = 0;
95 ParmVarDecl *Parm =
nullptr;
96 if (ArgIndex >= ArgOffset) {
97 unsigned ParmIndex = ArgIndex - ArgOffset;
98 if (ParmIndex < Callee->getNumParams())
99 Parm =
Callee->getParamDecl(ParmIndex);
101 if (mutatesGuardian(Arg, Parm))
108 bool VisitCXXMemberCallExpr(CXXMemberCallExpr *MCE)
override {
111 if (ObjType.isConstQualified())
114 if (
auto *VarRef = dyn_cast<DeclRefExpr>(ThisArg)) {
122 bool mutatesGuardian(
const Expr *Arg,
const ParmVarDecl *ParmDecl) {
124 if (
auto *VarRef = dyn_cast<DeclRefExpr>(Arg)) {
125 if (VarRef->getDecl() == Guardian) {
127 if (!ArgType.isConstQualified())
135bool isGuardedScopeEmbeddedInGuardianScope(
const VarDecl *Guarded,
136 const VarDecl *MaybeGuardian) {
138 assert(MaybeGuardian);
143 const CompoundStmt *guardiansClosestCompStmtAncestor =
nullptr;
148 !guardianAncestors.
empty();
153 for (
auto &guardianAncestor : guardianAncestors) {
154 if (
auto *CStmtParentAncestor = guardianAncestor.get<
CompoundStmt>()) {
155 guardiansClosestCompStmtAncestor = CStmtParentAncestor;
159 if (guardiansClosestCompStmtAncestor)
163 if (!guardiansClosestCompStmtAncestor)
170 !guardedVarAncestors.
empty();
175 for (
auto &guardedVarAncestor : guardedVarAncestors) {
176 if (
auto *CStmtAncestor = guardedVarAncestor.get<
CompoundStmt>()) {
177 if (!FirstCompondStmt) {
178 FirstCompondStmt = CStmtAncestor;
181 if (CStmtAncestor == guardiansClosestCompStmtAncestor) {
182 GuardianVisitor guardianVisitor(MaybeGuardian);
183 auto *GuardedScope =
const_cast<CompoundStmt *
>(FirstCompondStmt);
184 return guardianVisitor.TraverseCompoundStmt(GuardedScope);
193class RawPtrRefLocalVarsChecker
194 :
public Checker<check::ASTDecl<TranslationUnitDecl>> {
196 EnsureFunctionAnalysis EFA;
199 mutable BugReporter *BR;
200 const std::unique_ptr<PtrRefSafetyModel> Model;
203 RawPtrRefLocalVarsChecker(
const char *description,
204 std::unique_ptr<PtrRefSafetyModel> Model)
205 : Bug(this, description,
"WebKit coding guidelines"),
206 Model(std::move(Model)) {}
208 std::optional<bool> isUnsafePtr(QualType
T)
const {
212 void checkASTDecl(
const TranslationUnitDecl *TUD, AnalysisManager &MGR,
213 BugReporter &BRArg)
const {
220 const RawPtrRefLocalVarsChecker *Checker;
221 Decl *DeclWithIssue{
nullptr};
223 TrivialFunctionAnalysis TFA;
225 explicit LocalVisitor(
const RawPtrRefLocalVarsChecker *Checker)
228 ShouldVisitTemplateInstantiations =
true;
229 ShouldVisitImplicitCode =
false;
232 bool TraverseDecl(Decl *D)
override {
233 llvm::SaveAndRestore SavedDecl(DeclWithIssue);
239 bool VisitTypedefDecl(TypedefDecl *TD)
override {
240 if (
auto *RTC = Checker->Model->retainTypeChecker())
241 RTC->visitTypedef(TD);
245 bool VisitVarDecl(VarDecl *
V)
override {
246 auto *
Init =
V->getInit();
247 if (
V->isLocalVarDecl())
248 Checker->visitVarDecl(
V,
Init, DeclWithIssue);
252 bool VisitBinaryOperator(BinaryOperator *BO)
override {
254 if (
auto *VarRef = dyn_cast<DeclRefExpr>(BO->
getLHS())) {
255 if (
auto *
V = dyn_cast<VarDecl>(VarRef->getDecl()))
256 Checker->visitVarDecl(
V, BO->
getRHS(), DeclWithIssue);
262 bool TraverseIfStmt(IfStmt *IS)
override {
272 return DynamicRecursiveASTVisitor::TraverseIfStmt(IS);
276 bool TraverseForStmt(ForStmt *FS)
override {
278 return DynamicRecursiveASTVisitor::TraverseForStmt(FS);
282 bool TraverseCXXForRangeStmt(CXXForRangeStmt *FRS)
override {
284 return DynamicRecursiveASTVisitor::TraverseCXXForRangeStmt(FRS);
288 bool TraverseWhileStmt(WhileStmt *WS)
override {
290 return DynamicRecursiveASTVisitor::TraverseWhileStmt(WS);
296 return DynamicRecursiveASTVisitor::TraverseCompoundStmt(CS);
300 bool TraverseClassTemplateDecl(ClassTemplateDecl *Decl)
override {
303 return DynamicRecursiveASTVisitor::TraverseClassTemplateDecl(Decl);
307 LocalVisitor visitor(
this);
308 if (
auto *RTC = Model->retainTypeChecker())
309 RTC->visitTranslationUnitDecl(TUD);
310 visitor.TraverseDecl(
const_cast<TranslationUnitDecl *
>(TUD));
313 void visitVarDecl(
const VarDecl *
V,
const Expr *
Value,
314 const Decl *DeclWithIssue)
const {
315 if (shouldSkipVarDecl(
V))
318 if (
auto *DD = dyn_cast<DecompositionDecl>(
V)) {
319 for (
auto *BD : DD->bindings()) {
320 auto *Binding = BD->getBinding();
323 std::optional<bool> IsUncountedPtr = isUnsafePtr(Binding->getType());
324 if (!IsUncountedPtr || !*IsUncountedPtr)
326 reportBug(
V,
nullptr, BD, DeclWithIssue);
330 std::optional<bool> IsUncountedPtr = isUnsafePtr(
V->getType());
331 if (IsUncountedPtr && *IsUncountedPtr) {
332 if (
Value && isPtrOriginSafe(
V,
Value, DeclWithIssue))
334 reportBug(
V,
Value,
nullptr, DeclWithIssue);
338 bool isPtrOriginSafe(
const VarDecl *
V,
const Expr *
Value,
339 const Decl *DeclWithIssue)
const {
342 [&](
const clang::CXXRecordDecl *
Record) {
343 return Model->isSafePtr(
Record);
345 [&](
const clang::QualType
Type) {
return Model->isSafePtrType(
Type); },
346 [&](
const clang::Decl *D) {
347 return Model->isSafeDecl(D, BR->getSourceManager());
349 [&](
const clang::Expr *InitArgOrigin,
bool IsSafe) {
350 if (!InitArgOrigin || IsSafe)
365 if (EFA.isACallToEnsureFn(InitArgOrigin))
368 if (Model->isSafeExpr(InitArgOrigin))
371 if (
auto *Ref = llvm::dyn_cast<DeclRefExpr>(InitArgOrigin)) {
372 if (
auto *MaybeGuardian =
373 dyn_cast_or_null<VarDecl>(Ref->getFoundDecl())) {
374 const auto *MaybeGuardianArgType =
376 if (MaybeGuardianArgType) {
377 const CXXRecordDecl *
const MaybeGuardianArgCXXRecord =
378 MaybeGuardianArgType->getAsCXXRecordDecl();
379 if (MaybeGuardianArgCXXRecord) {
381 (Model->isSafePtr(MaybeGuardianArgCXXRecord) ||
382 isRefcountedStringsHack(MaybeGuardian)) &&
383 isGuardedScopeEmbeddedInGuardianScope(
V, MaybeGuardian))
389 if (
auto *FD = dyn_cast<FunctionDecl>(DeclWithIssue)) {
390 if (GuardianVisitor{MaybeGuardian}.TraverseStmt(
394 if (
auto *MD = dyn_cast<ObjCMethodDecl>(DeclWithIssue)) {
395 if (GuardianVisitor{MaybeGuardian}.TraverseStmt(
407 bool shouldSkipVarDecl(
const VarDecl *
V)
const {
411 return BR->getSourceManager().isInSystemHeader(
V->getLocation());
414 void reportBug(
const VarDecl *
V,
const Expr *
Value,
const Decl *BindingDecl,
415 const Decl *DeclWithIssue)
const {
417 SmallString<100> Buf;
418 llvm::raw_svector_ostream Os(Buf);
424 printPointerTypeAndType(Os,
V->getType());
426 SourceLocation ExprLoc = (
Value) ?
Value->getExprLoc() :
V->getLocation();
427 PathDiagnosticLocation BSLoc(ExprLoc, BR->getSourceManager());
428 auto Report = std::make_unique<BasicBugReport>(Bug, Os.str(), BSLoc);
431 BR->emitReport(std::move(
Report));
433 if (
V->hasLocalStorage())
434 Os <<
"Local variable ";
435 else if (
V->isStaticLocal())
436 Os <<
"Static local variable ";
437 else if (
V->hasGlobalStorage())
438 Os <<
"Global variable ";
446 printPointerTypeAndType(Os,
V->getType());
448 PathDiagnosticLocation BSLoc(
V->getLocation(), BR->getSourceManager());
449 auto Report = std::make_unique<BasicBugReport>(Bug, Os.str(), BSLoc);
450 Report->addRange(
V->getSourceRange());
451 Report->setDeclWithIssue(DeclWithIssue);
452 BR->emitReport(std::move(
Report));
456 void printPointerTypeAndType(llvm::raw_svector_ostream &Os,
459 auto *RTC = Model->retainTypeChecker();
461 Os << Model->typeName() <<
" ";
462 if (
auto *Decl = RTC->getCanonicalDecl(QT)) {
465 auto Typedef = VarType->getAs<TypedefType>();
470 auto *DesugaredType = VarType->getUnqualifiedDesugaredType();
472 Os <<
"raw " << (IsPtr ?
"pointer" :
"reference") <<
" to ";
473 Os << Model->typeName() <<
" ";
479class UncountedLocalVarsChecker final :
public RawPtrRefLocalVarsChecker {
481 UncountedLocalVarsChecker()
482 : RawPtrRefLocalVarsChecker(
"Uncounted raw pointer or reference not "
483 "provably backed by ref-counted variable",
487class UncheckedLocalVarsChecker final :
public RawPtrRefLocalVarsChecker {
489 UncheckedLocalVarsChecker()
490 : RawPtrRefLocalVarsChecker(
"Unchecked raw pointer or reference not "
491 "provably backed by checked variable",
495class UnretainedLocalVarsChecker final :
public RawPtrRefLocalVarsChecker {
497 UnretainedLocalVarsChecker()
498 : RawPtrRefLocalVarsChecker(
"Unretained raw pointer or reference not "
499 "provably backed by a RetainPtr",
505void ento::registerUncountedLocalVarsChecker(
CheckerManager &Mgr) {
509bool ento::shouldRegisterUncountedLocalVarsChecker(
const CheckerManager &) {
513void ento::registerUncheckedLocalVarsChecker(
CheckerManager &Mgr) {
517bool ento::shouldRegisterUncheckedLocalVarsChecker(
const CheckerManager &) {
521void ento::registerUnretainedLocalVarsChecker(
CheckerManager &Mgr) {
525bool ento::shouldRegisterUnretainedLocalVarsChecker(
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)
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.
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
CompoundStmt - This represents a group of statements like { stmt stmt }.
ASTContext & getASTContext() const LLVM_READONLY
Container for either a single DynTypedNode or for an ArrayRef to DynTypedNode.
virtual bool TraverseDecl(MaybeConst< Decl > *D)
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.
A (possibly-)qualified type.
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
bool isTrivial(const Decl *D, const Stmt **OffendingStmt=nullptr) const
Represents a variable declaration or definition.
bool isLocalVarDecl() const
Returns true for local variable declarations other than parameters.
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.
The JSON file list parser is used to communicate input to InstallAPI.
bool isa(CodeGen::Address addr)
bool isPtrConversion(const FunctionDecl *F)
std::unique_ptr< PtrRefSafetyModel > makeCheckedPtrSafetyModel()
void printQuotedQualifiedName(llvm::raw_ostream &Os, const NamedDeclDerivedT &D)
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 tryToFindPtrOrigin(const Expr *E, bool StopAtFirstRefCountedObj, 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)> callback)
This function de-facto defines a set of transformations that we consider safe (in heuristical sense).
const FunctionProtoType * T
bool isSmartPtrClass(const std::string &Name)
@ Type
The name was classified as a type.
void printTypeName(llvm::raw_ostream &Os, const QualType QT)
std::string safeGetName(const T *ASTNode)
bool isNullPtr(const clang::Expr *E)
DynamicRecursiveASTVisitorBase< false > DynamicRecursiveASTVisitor
std::unique_ptr< PtrRefSafetyModel > makeRefPtrSafetyModel()
std::unique_ptr< PtrRefSafetyModel > makeRetainPtrSafetyModel()
bool isConstOwnerPtrMemberExpr(const clang::Expr *E)