1//=======- ASTUtils.cpp ------------------------------------------*- C++ -*-==//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "ASTUtils.h"
10#include "PtrTypesSemantics.h"
11#include "clang/AST/Attr.h"
12#include "clang/AST/Decl.h"
13#include "clang/AST/DeclCXX.h"
14#include "clang/AST/ExprCXX.h"
15#include "clang/AST/ExprObjC.h"
16#include "clang/AST/StmtVisitor.h"
17#include <optional>
18
19namespace clang {
20
21bool isSafePtr(clang::CXXRecordDecl *Decl) {
22 return isRefCounted(Class: Decl) || isCheckedPtr(Class: Decl);
23}
24
25bool tryToFindPtrOrigin(
26 const Expr *E, bool StopAtFirstRefCountedObj,
27 std::function<bool(const clang::CXXRecordDecl *)> isSafePtr,
28 std::function<bool(const clang::QualType)> isSafePtrType,
29 std::function<bool(const clang::Decl *)> isSafeGlobalDecl,
30 std::function<bool(const clang::Expr *, bool)> callback) {
31 while (E) {
32 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: E)) {
33 if (auto *VD = dyn_cast_or_null<VarDecl>(Val: DRE->getDecl())) {
34 auto QT = VD->getType();
35 auto IsImmortal = safeGetName(ASTNode: VD) == "NSApp";
36 if (VD->hasGlobalStorage() && (IsImmortal || QT.isConstQualified()))
37 return callback(E, true);
38 if (VD->hasGlobalStorage() && isSafeGlobalDecl(VD))
39 return callback(E, true);
40 }
41 }
42 if (auto *tempExpr = dyn_cast<MaterializeTemporaryExpr>(Val: E)) {
43 E = tempExpr->getSubExpr();
44 continue;
45 }
46 if (auto *tempExpr = dyn_cast<CXXBindTemporaryExpr>(Val: E)) {
47 E = tempExpr->getSubExpr();
48 continue;
49 }
50 if (auto *tempExpr = dyn_cast<CXXConstructExpr>(Val: E)) {
51 if (auto *C = tempExpr->getConstructor()) {
52 if (auto *Class = C->getParent(); Class && isSafePtr(Class))
53 return callback(E, true);
54 break;
55 }
56 }
57 if (auto *TempExpr = dyn_cast<CXXUnresolvedConstructExpr>(Val: E)) {
58 if (isSafePtrType(TempExpr->getTypeAsWritten()))
59 return callback(TempExpr, true);
60 }
61 if (auto *POE = dyn_cast<PseudoObjectExpr>(Val: E)) {
62 if (auto *RF = POE->getResultExpr()) {
63 E = RF;
64 continue;
65 }
66 }
67 if (auto *tempExpr = dyn_cast<ParenExpr>(Val: E)) {
68 E = tempExpr->getSubExpr();
69 continue;
70 }
71 if (auto *OpaqueValue = dyn_cast<OpaqueValueExpr>(Val: E)) {
72 E = OpaqueValue->getSourceExpr();
73 continue;
74 }
75 if (auto *Expr = dyn_cast<ConditionalOperator>(Val: E)) {
76 return tryToFindPtrOrigin(E: Expr->getTrueExpr(), StopAtFirstRefCountedObj,
77 isSafePtr, isSafePtrType, isSafeGlobalDecl,
78 callback) &&
79 tryToFindPtrOrigin(E: Expr->getFalseExpr(), StopAtFirstRefCountedObj,
80 isSafePtr, isSafePtrType, isSafeGlobalDecl,
81 callback);
82 }
83 if (auto *cast = dyn_cast<CastExpr>(Val: E)) {
84 if (StopAtFirstRefCountedObj) {
85 if (auto *ConversionFunc =
86 dyn_cast_or_null<FunctionDecl>(Val: cast->getConversionFunction())) {
87 if (isCtorOfSafePtr(F: ConversionFunc))
88 return callback(E, true);
89 }
90 if (isa<CXXFunctionalCastExpr>(Val: E) && isSafePtrType(cast->getType()))
91 return callback(E, true);
92 }
93 // FIXME: This can give false "origin" that would lead to false negatives
94 // in checkers. See https://reviews.llvm.org/D37023 for reference.
95 E = cast->getSubExpr();
96 continue;
97 }
98 if (auto *call = dyn_cast<CallExpr>(Val: E)) {
99 if (auto *Callee = call->getCalleeDecl()) {
100 if (Callee->hasAttr<CFReturnsRetainedAttr>() ||
101 Callee->hasAttr<NSReturnsRetainedAttr>() ||
102 Callee->hasAttr<NSReturnsAutoreleasedAttr>()) {
103 return callback(E, true);
104 }
105 }
106
107 if (auto *memberCall = dyn_cast<CXXMemberCallExpr>(Val: call)) {
108 if (auto *decl = memberCall->getMethodDecl()) {
109 std::optional<bool> IsGetterOfRefCt = isGetterOfSafePtr(Method: decl);
110 if (IsGetterOfRefCt && *IsGetterOfRefCt) {
111 E = memberCall->getImplicitObjectArgument()->IgnoreParenCasts();
112 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: E)) {
113 if (auto *Decl = dyn_cast_or_null<VarDecl>(Val: DRE->getDecl())) {
114 if (Decl->isLocalVarDeclOrParm()) {
115 if (StopAtFirstRefCountedObj)
116 return callback(E, true);
117 }
118 }
119 }
120 continue;
121 }
122 }
123 }
124
125 if (auto *operatorCall = dyn_cast<CXXOperatorCallExpr>(Val: E)) {
126 if (auto *Callee = operatorCall->getDirectCallee()) {
127 auto ClsName = safeGetName(ASTNode: Callee->getParent());
128 if (isRefType(Name: ClsName) || isCheckedPtr(Name: ClsName) ||
129 isRetainPtrOrOSPtr(Name: ClsName) || ClsName == "unique_ptr" ||
130 ClsName == "UniqueRef" || ClsName == "WeakPtr" ||
131 ClsName == "WeakRef") {
132 if (operatorCall->getNumArgs() == 1) {
133 E = operatorCall->getArg(Arg: 0);
134 continue;
135 }
136 }
137 }
138 }
139
140 if (auto *callee = call->getDirectCallee()) {
141 if (isCtorOfSafePtr(F: callee)) {
142 if (StopAtFirstRefCountedObj)
143 return callback(E, true);
144
145 E = call->getArg(Arg: 0);
146 continue;
147 }
148
149 if (isStdOrWTFMove(F: callee) && call->getNumArgs() == 1) {
150 E = call->getArg(Arg: 0)->IgnoreParenCasts();
151 continue;
152 }
153
154 if (isSafePtrType(callee->getReturnType()))
155 return callback(E, true);
156
157 if (isSingleton(F: callee))
158 return callback(E, true);
159
160 if (callee->isInStdNamespace() && safeGetName(ASTNode: callee) == "forward") {
161 E = call->getArg(Arg: 0);
162 continue;
163 }
164
165 if (isPtrConversion(F: callee)) {
166 E = call->getArg(Arg: 0);
167 continue;
168 }
169
170 auto Name = safeGetName(ASTNode: callee);
171 if (Name == "__builtin___CFStringMakeConstantString" ||
172 Name == "NSStringFromSelector" || Name == "NSSelectorFromString" ||
173 Name == "NSStringFromClass" || Name == "NSClassFromString" ||
174 Name == "NSStringFromProtocol" || Name == "NSProtocolFromString")
175 return callback(E, true);
176 } else if (auto *CalleeE = call->getCallee()) {
177 if (auto *E = dyn_cast<DeclRefExpr>(Val: CalleeE->IgnoreParenCasts())) {
178 if (isSingleton(F: E->getFoundDecl()))
179 return callback(E, true);
180 }
181
182 if (auto *MemberExpr = dyn_cast<CXXDependentScopeMemberExpr>(Val: CalleeE)) {
183 auto *Base = MemberExpr->getBase();
184 auto MemberName = MemberExpr->getMember().getAsString();
185 bool IsGetter = MemberName == "get" || MemberName == "ptr";
186 if (Base && isSafePtrType(Base->getType()) && IsGetter)
187 return callback(E, true);
188 }
189 }
190
191 // Sometimes, canonical type erroneously turns Ref<T> into T.
192 // Workaround this problem by checking again if the original type was
193 // a SubstTemplateTypeParmType of a safe smart pointer type (e.g. Ref).
194 if (auto *CalleeDecl = call->getCalleeDecl()) {
195 if (auto *FD = dyn_cast<FunctionDecl>(Val: CalleeDecl)) {
196 auto RetType = FD->getReturnType();
197 if (auto *Subst = dyn_cast<SubstTemplateTypeParmType>(Val&: RetType)) {
198 if (auto *SubstType = Subst->desugar().getTypePtr()) {
199 if (auto *RD = dyn_cast<RecordType>(Val: SubstType)) {
200 if (auto *CXX = dyn_cast<CXXRecordDecl>(Val: RD->getDecl()))
201 if (isSafePtr(CXX))
202 return callback(E, true);
203 }
204 }
205 }
206 }
207 }
208 }
209 if (auto *ObjCMsgExpr = dyn_cast<ObjCMessageExpr>(Val: E)) {
210 if (auto *Method = ObjCMsgExpr->getMethodDecl()) {
211 if (isSafePtrType(Method->getReturnType()))
212 return callback(E, true);
213 }
214 if (ObjCMsgExpr->isClassMessage())
215 return callback(E, true);
216 auto Selector = ObjCMsgExpr->getSelector();
217 auto NameForFirstSlot = Selector.getNameForSlot(argIndex: 0);
218 if ((NameForFirstSlot == "class" || NameForFirstSlot == "superclass") &&
219 !Selector.getNumArgs())
220 return callback(E, true);
221 }
222 if (auto *ObjCProtocol = dyn_cast<ObjCProtocolExpr>(Val: E))
223 return callback(ObjCProtocol, true);
224 if (auto *ObjCDict = dyn_cast<ObjCDictionaryLiteral>(Val: E))
225 return callback(ObjCDict, true);
226 if (auto *ObjCArray = dyn_cast<ObjCArrayLiteral>(Val: E))
227 return callback(ObjCArray, true);
228 if (auto *ObjCStr = dyn_cast<ObjCStringLiteral>(Val: E))
229 return callback(ObjCStr, true);
230 if (auto *unaryOp = dyn_cast<UnaryOperator>(Val: E)) {
231 // FIXME: Currently accepts ANY unary operator. Is it OK?
232 E = unaryOp->getSubExpr();
233 continue;
234 }
235 if (auto *BoxedExpr = dyn_cast<ObjCBoxedExpr>(Val: E)) {
236 if (StopAtFirstRefCountedObj)
237 return callback(BoxedExpr, true);
238 E = BoxedExpr->getSubExpr();
239 continue;
240 }
241 break;
242 }
243 // Some other expression.
244 return callback(E, false);
245}
246
247bool isASafeCallArg(const Expr *E) {
248 assert(E);
249 auto IsCheckedLocalVarOrParam = [](const VarDecl *Decl) {
250 auto Ty = Decl->getType();
251 const CXXRecordDecl *CXXRD = Ty->getAsCXXRecordDecl();
252 if (!CXXRD)
253 CXXRD = Ty->getPointeeCXXRecordDecl();
254 if (CXXRD && isWeakPtr(Class: CXXRD))
255 return false;
256 return Decl->isLocalVarDeclOrParm();
257 };
258 if (auto *Ref = dyn_cast<DeclRefExpr>(Val: E)) {
259 auto *FoundDecl = Ref->getFoundDecl();
260 if (auto *D = dyn_cast_or_null<VarDecl>(Val: FoundDecl)) {
261 if (IsCheckedLocalVarOrParam(D))
262 return true;
263 if (auto *ImplicitP = dyn_cast<ImplicitParamDecl>(Val: D)) {
264 auto Kind = ImplicitP->getParameterKind();
265 if (Kind == ImplicitParamKind::ObjCSelf ||
266 Kind == ImplicitParamKind::ObjCCmd ||
267 Kind == ImplicitParamKind::CXXThis ||
268 Kind == ImplicitParamKind::CXXVTT)
269 return true;
270 }
271 } else if (auto *BD = dyn_cast_or_null<BindingDecl>(Val: FoundDecl)) {
272 if (VarDecl *VD = BD->getHoldingVar()) {
273 if (IsCheckedLocalVarOrParam(VD))
274 return true;
275 }
276 }
277 }
278 if (isa<CXXTemporaryObjectExpr>(Val: E))
279 return true; // A temporary lives until the end of this statement.
280 if (isConstOwnerPtrMemberExpr(E))
281 return true;
282
283 // TODO: checker for method calls on non-refcounted objects
284 return isa<CXXThisExpr>(Val: E);
285}
286
287bool isNullPtr(const clang::Expr *E) {
288 if (isa<CXXNullPtrLiteralExpr>(Val: E) || isa<GNUNullExpr>(Val: E))
289 return true;
290 if (auto *Int = dyn_cast_or_null<IntegerLiteral>(Val: E)) {
291 if (Int->getValue().isZero())
292 return true;
293 }
294 return false;
295}
296
297bool isConstOwnerPtrMemberExpr(const clang::Expr *E) {
298 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(Val: E)) {
299 if (auto *Callee = MCE->getDirectCallee()) {
300 auto Name = safeGetName(ASTNode: Callee);
301 if (Name == "get" || Name == "ptr")
302 E = MCE->getImplicitObjectArgument();
303 if (isa<CXXConversionDecl>(Val: Callee))
304 E = MCE->getImplicitObjectArgument();
305 }
306 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(Val: E)) {
307 if (OCE->getOperator() == OO_Star && OCE->getNumArgs() == 1)
308 E = OCE->getArg(Arg: 0);
309 }
310 const ValueDecl *D = nullptr;
311 if (auto *ME = dyn_cast<MemberExpr>(Val: E))
312 D = ME->getMemberDecl();
313 else if (auto *IVR = dyn_cast<ObjCIvarRefExpr>(Val: E))
314 D = IVR->getDecl();
315 if (!D)
316 return false;
317 auto T = D->getType();
318 return isOwnerPtrType(T) && T.isConstQualified();
319}
320
321bool isExprToGetCheckedPtrCapableMember(const clang::Expr *E) {
322 auto *ME = dyn_cast<MemberExpr>(Val: E);
323 if (!ME)
324 return false;
325 auto *Base = ME->getBase();
326 if (!Base)
327 return false;
328 if (!isa<CXXThisExpr>(Val: Base->IgnoreParenCasts()))
329 return false;
330 auto *D = ME->getMemberDecl();
331 if (!D)
332 return false;
333 auto T = D->getType();
334 auto *CXXRD = T->getAsCXXRecordDecl();
335 if (!CXXRD)
336 return false;
337 auto result = isCheckedPtrCapable(Class: CXXRD);
338 return result && *result;
339}
340
341bool isAllocInit(const Expr *E, const Expr **InnerExpr) {
342 auto *ObjCMsgExpr = dyn_cast<ObjCMessageExpr>(Val: E);
343 if (auto *POE = dyn_cast<PseudoObjectExpr>(Val: E)) {
344 if (unsigned ExprCount = POE->getNumSemanticExprs()) {
345 auto *Expr = POE->getSemanticExpr(index: ExprCount - 1)->IgnoreParenCasts();
346 ObjCMsgExpr = dyn_cast<ObjCMessageExpr>(Val: Expr);
347 if (InnerExpr)
348 *InnerExpr = ObjCMsgExpr;
349 }
350 }
351 if (!ObjCMsgExpr)
352 return false;
353 auto Selector = ObjCMsgExpr->getSelector();
354 auto NameForFirstSlot = Selector.getNameForSlot(argIndex: 0);
355 if (NameForFirstSlot.starts_with(Prefix: "alloc") ||
356 NameForFirstSlot.starts_with(Prefix: "copy") ||
357 NameForFirstSlot.starts_with(Prefix: "mutableCopy")) {
358 if (auto *MD = ObjCMsgExpr->getMethodDecl()) {
359 if (MD->getReturnType()->isVoidType())
360 return false;
361 }
362 return true;
363 }
364 if (!NameForFirstSlot.starts_with(Prefix: "init") &&
365 !NameForFirstSlot.starts_with(Prefix: "_init"))
366 return false;
367 if (!ObjCMsgExpr->isInstanceMessage())
368 return false;
369 auto *Receiver = ObjCMsgExpr->getInstanceReceiver();
370 if (!Receiver)
371 return false;
372 Receiver = Receiver->IgnoreParenCasts();
373 if (auto *Inner = dyn_cast<ObjCMessageExpr>(Val: Receiver)) {
374 if (InnerExpr)
375 *InnerExpr = Inner;
376 auto InnerSelector = Inner->getSelector();
377 return InnerSelector.getNameForSlot(argIndex: 0).starts_with(Prefix: "alloc");
378 } else if (auto *CE = dyn_cast<CallExpr>(Val: Receiver)) {
379 if (InnerExpr)
380 *InnerExpr = CE;
381 if (auto *Callee = CE->getDirectCallee()) {
382 if (Callee->getDeclName().isIdentifier()) {
383 auto CalleeName = Callee->getName();
384 return CalleeName.starts_with(Prefix: "alloc");
385 }
386 }
387 }
388 return false;
389}
390
391class EnsureFunctionVisitor
392 : public ConstStmtVisitor<EnsureFunctionVisitor, bool> {
393public:
394 bool VisitStmt(const Stmt *S) {
395 for (const Stmt *Child : S->children()) {
396 if (Child && !Visit(S: Child))
397 return false;
398 }
399 return true;
400 }
401
402 bool VisitReturnStmt(const ReturnStmt *RS) {
403 if (auto *RV = RS->getRetValue()) {
404 RV = RV->IgnoreParenCasts();
405 if (isNullPtr(E: RV))
406 return true;
407 return isConstOwnerPtrMemberExpr(E: RV);
408 }
409 return false;
410 }
411};
412
413bool EnsureFunctionAnalysis::isACallToEnsureFn(const clang::Expr *E) const {
414 auto *MCE = dyn_cast<CXXMemberCallExpr>(Val: E);
415 if (!MCE)
416 return false;
417 auto *Callee = MCE->getDirectCallee();
418 if (!Callee)
419 return false;
420 auto *Body = Callee->getBody();
421 if (!Body || Callee->isVirtualAsWritten())
422 return false;
423 auto [CacheIt, IsNew] = Cache.insert(KV: std::make_pair(x&: Callee, y: false));
424 if (IsNew)
425 CacheIt->second = EnsureFunctionVisitor().Visit(S: Body);
426 return CacheIt->second;
427}
428
429} // namespace clang
430