clang 19.0.0git
ObjCSelfInitChecker.cpp
Go to the documentation of this file.
1//== ObjCSelfInitChecker.cpp - Checker for 'self' initialization -*- 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// This defines ObjCSelfInitChecker, a builtin check that checks for uses of
10// 'self' before proper initialization.
11//
12//===----------------------------------------------------------------------===//
13
14// This checks initialization methods to verify that they assign 'self' to the
15// result of an initialization call (e.g. [super init], or [self initWith..])
16// before using 'self' or any instance variable.
17//
18// To perform the required checking, values are tagged with flags that indicate
19// 1) if the object is the one pointed to by 'self', and 2) if the object
20// is the result of an initializer (e.g. [super init]).
21//
22// Uses of an object that is true for 1) but not 2) trigger a diagnostic.
23// The uses that are currently checked are:
24// - Using instance variables.
25// - Returning the object.
26//
27// Note that we don't check for an invalid 'self' that is the receiver of an
28// obj-c message expression to cut down false positives where logging functions
29// get information from self (like its class) or doing "invalidation" on self
30// when the initialization fails.
31//
32// Because the object that 'self' points to gets invalidated when a call
33// receives a reference to 'self', the checker keeps track and passes the flags
34// for 1) and 2) to the new object that 'self' points to after the call.
35//
36//===----------------------------------------------------------------------===//
37
39#include "clang/AST/ParentMap.h"
46#include "llvm/Support/raw_ostream.h"
47
48using namespace clang;
49using namespace ento;
50
51static bool shouldRunOnFunctionOrMethod(const NamedDecl *ND);
52static bool isInitializationMethod(const ObjCMethodDecl *MD);
53static bool isInitMessage(const ObjCMethodCall &Msg);
54static bool isSelfVar(SVal location, CheckerContext &C);
55
56namespace {
57class ObjCSelfInitChecker : public Checker< check::PostObjCMessage,
58 check::PostStmt<ObjCIvarRefExpr>,
59 check::PreStmt<ReturnStmt>,
60 check::PreCall,
61 check::PostCall,
62 check::Location,
63 check::Bind > {
64 const BugType BT{this, "Missing \"self = [(super or self) init...]\"",
66
67 void checkForInvalidSelf(const Expr *E, CheckerContext &C,
68 const char *errorStr) const;
69
70public:
71 void checkPostObjCMessage(const ObjCMethodCall &Msg, CheckerContext &C) const;
72 void checkPostStmt(const ObjCIvarRefExpr *E, CheckerContext &C) const;
73 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
74 void checkLocation(SVal location, bool isLoad, const Stmt *S,
75 CheckerContext &C) const;
76 void checkBind(SVal loc, SVal val, const Stmt *S, CheckerContext &C) const;
77
78 void checkPreCall(const CallEvent &CE, CheckerContext &C) const;
79 void checkPostCall(const CallEvent &CE, CheckerContext &C) const;
80
81 void printState(raw_ostream &Out, ProgramStateRef State,
82 const char *NL, const char *Sep) const override;
83};
84} // end anonymous namespace
85
86namespace {
87enum SelfFlagEnum {
88 /// No flag set.
89 SelfFlag_None = 0x0,
90 /// Value came from 'self'.
91 SelfFlag_Self = 0x1,
92 /// Value came from the result of an initializer (e.g. [super init]).
93 SelfFlag_InitRes = 0x2
94};
95}
96
97REGISTER_MAP_WITH_PROGRAMSTATE(SelfFlag, SymbolRef, SelfFlagEnum)
99
100/// A call receiving a reference to 'self' invalidates the object that
101/// 'self' contains. This keeps the "self flags" assigned to the 'self'
102/// object before the call so we can assign them to the new object that 'self'
103/// points to after the call.
104REGISTER_TRAIT_WITH_PROGRAMSTATE(PreCallSelfFlags, SelfFlagEnum)
105
106static SelfFlagEnum getSelfFlags(SVal val, ProgramStateRef state) {
107 if (SymbolRef sym = val.getAsSymbol())
108 if (const SelfFlagEnum *attachedFlags = state->get<SelfFlag>(sym))
109 return *attachedFlags;
110 return SelfFlag_None;
111}
112
113static SelfFlagEnum getSelfFlags(SVal val, CheckerContext &C) {
114 return getSelfFlags(val, C.getState());
115}
116
117static void addSelfFlag(ProgramStateRef state, SVal val,
118 SelfFlagEnum flag, CheckerContext &C) {
119 // We tag the symbol that the SVal wraps.
120 if (SymbolRef sym = val.getAsSymbol()) {
121 state = state->set<SelfFlag>(sym,
122 SelfFlagEnum(getSelfFlags(val, state) | flag));
123 C.addTransition(state);
124 }
125}
126
127static bool hasSelfFlag(SVal val, SelfFlagEnum flag, CheckerContext &C) {
128 return getSelfFlags(val, C) & flag;
129}
130
131/// Returns true of the value of the expression is the object that 'self'
132/// points to and is an object that did not come from the result of calling
133/// an initializer.
134static bool isInvalidSelf(const Expr *E, CheckerContext &C) {
135 SVal exprVal = C.getSVal(E);
136 if (!hasSelfFlag(exprVal, SelfFlag_Self, C))
137 return false; // value did not come from 'self'.
138 if (hasSelfFlag(exprVal, SelfFlag_InitRes, C))
139 return false; // 'self' is properly initialized.
140
141 return true;
142}
143
144void ObjCSelfInitChecker::checkForInvalidSelf(const Expr *E, CheckerContext &C,
145 const char *errorStr) const {
146 if (!E)
147 return;
148
149 if (!C.getState()->get<CalledInit>())
150 return;
151
152 if (!isInvalidSelf(E, C))
153 return;
154
155 // Generate an error node.
156 ExplodedNode *N = C.generateErrorNode();
157 if (!N)
158 return;
159
160 C.emitReport(std::make_unique<PathSensitiveBugReport>(BT, errorStr, N));
161}
162
163void ObjCSelfInitChecker::checkPostObjCMessage(const ObjCMethodCall &Msg,
164 CheckerContext &C) const {
165 // When encountering a message that does initialization (init rule),
166 // tag the return value so that we know later on that if self has this value
167 // then it is properly initialized.
168
169 // FIXME: A callback should disable checkers at the start of functions.
170 if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>(
171 C.getCurrentAnalysisDeclContext()->getDecl())))
172 return;
173
174 if (isInitMessage(Msg)) {
175 // Tag the return value as the result of an initializer.
176 ProgramStateRef state = C.getState();
177
178 // FIXME this really should be context sensitive, where we record
179 // the current stack frame (for IPA). Also, we need to clean this
180 // value out when we return from this method.
181 state = state->set<CalledInit>(true);
182
183 SVal V = C.getSVal(Msg.getOriginExpr());
184 addSelfFlag(state, V, SelfFlag_InitRes, C);
185 return;
186 }
187
188 // We don't check for an invalid 'self' in an obj-c message expression to cut
189 // down false positives where logging functions get information from self
190 // (like its class) or doing "invalidation" on self when the initialization
191 // fails.
192}
193
194void ObjCSelfInitChecker::checkPostStmt(const ObjCIvarRefExpr *E,
195 CheckerContext &C) const {
196 // FIXME: A callback should disable checkers at the start of functions.
197 if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>(
198 C.getCurrentAnalysisDeclContext()->getDecl())))
199 return;
200
201 checkForInvalidSelf(
202 E->getBase(), C,
203 "Instance variable used while 'self' is not set to the result of "
204 "'[(super or self) init...]'");
205}
206
207void ObjCSelfInitChecker::checkPreStmt(const ReturnStmt *S,
208 CheckerContext &C) const {
209 // FIXME: A callback should disable checkers at the start of functions.
210 if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>(
211 C.getCurrentAnalysisDeclContext()->getDecl())))
212 return;
213
214 checkForInvalidSelf(S->getRetValue(), C,
215 "Returning 'self' while it is not set to the result of "
216 "'[(super or self) init...]'");
217}
218
219// When a call receives a reference to 'self', [Pre/Post]Call pass
220// the SelfFlags from the object 'self' points to before the call to the new
221// object after the call. This is to avoid invalidation of 'self' by logging
222// functions.
223// Another common pattern in classes with multiple initializers is to put the
224// subclass's common initialization bits into a static function that receives
225// the value of 'self', e.g:
226// @code
227// if (!(self = [super init]))
228// return nil;
229// if (!(self = _commonInit(self)))
230// return nil;
231// @endcode
232// Until we can use inter-procedural analysis, in such a call, transfer the
233// SelfFlags to the result of the call.
234
235void ObjCSelfInitChecker::checkPreCall(const CallEvent &CE,
236 CheckerContext &C) const {
237 // FIXME: A callback should disable checkers at the start of functions.
238 if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>(
239 C.getCurrentAnalysisDeclContext()->getDecl())))
240 return;
241
242 ProgramStateRef state = C.getState();
243 unsigned NumArgs = CE.getNumArgs();
244 // If we passed 'self' as and argument to the call, record it in the state
245 // to be propagated after the call.
246 // Note, we could have just given up, but try to be more optimistic here and
247 // assume that the functions are going to continue initialization or will not
248 // modify self.
249 for (unsigned i = 0; i < NumArgs; ++i) {
250 SVal argV = CE.getArgSVal(i);
251 if (isSelfVar(argV, C)) {
252 SelfFlagEnum selfFlags =
253 getSelfFlags(state->getSVal(argV.castAs<Loc>()), C);
254 C.addTransition(state->set<PreCallSelfFlags>(selfFlags));
255 return;
256 } else if (hasSelfFlag(argV, SelfFlag_Self, C)) {
257 SelfFlagEnum selfFlags = getSelfFlags(argV, C);
258 C.addTransition(state->set<PreCallSelfFlags>(selfFlags));
259 return;
260 }
261 }
262}
263
264void ObjCSelfInitChecker::checkPostCall(const CallEvent &CE,
265 CheckerContext &C) const {
266 // FIXME: A callback should disable checkers at the start of functions.
267 if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>(
268 C.getCurrentAnalysisDeclContext()->getDecl())))
269 return;
270
271 ProgramStateRef state = C.getState();
272 SelfFlagEnum prevFlags = state->get<PreCallSelfFlags>();
273 if (!prevFlags)
274 return;
275 state = state->remove<PreCallSelfFlags>();
276
277 unsigned NumArgs = CE.getNumArgs();
278 for (unsigned i = 0; i < NumArgs; ++i) {
279 SVal argV = CE.getArgSVal(i);
280 if (isSelfVar(argV, C)) {
281 // If the address of 'self' is being passed to the call, assume that the
282 // 'self' after the call will have the same flags.
283 // EX: log(&self)
284 addSelfFlag(state, state->getSVal(argV.castAs<Loc>()), prevFlags, C);
285 return;
286 } else if (hasSelfFlag(argV, SelfFlag_Self, C)) {
287 // If 'self' is passed to the call by value, assume that the function
288 // returns 'self'. So assign the flags, which were set on 'self' to the
289 // return value.
290 // EX: self = performMoreInitialization(self)
291 addSelfFlag(state, CE.getReturnValue(), prevFlags, C);
292 return;
293 }
294 }
295
296 C.addTransition(state);
297}
298
299void ObjCSelfInitChecker::checkLocation(SVal location, bool isLoad,
300 const Stmt *S,
301 CheckerContext &C) const {
302 if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>(
303 C.getCurrentAnalysisDeclContext()->getDecl())))
304 return;
305
306 // Tag the result of a load from 'self' so that we can easily know that the
307 // value is the object that 'self' points to.
308 ProgramStateRef state = C.getState();
309 if (isSelfVar(location, C))
310 addSelfFlag(state, state->getSVal(location.castAs<Loc>()), SelfFlag_Self,
311 C);
312}
313
314
315void ObjCSelfInitChecker::checkBind(SVal loc, SVal val, const Stmt *S,
316 CheckerContext &C) const {
317 // Allow assignment of anything to self. Self is a local variable in the
318 // initializer, so it is legal to assign anything to it, like results of
319 // static functions/method calls. After self is assigned something we cannot
320 // reason about, stop enforcing the rules.
321 // (Only continue checking if the assigned value should be treated as self.)
322 if ((isSelfVar(loc, C)) &&
323 !hasSelfFlag(val, SelfFlag_InitRes, C) &&
324 !hasSelfFlag(val, SelfFlag_Self, C) &&
325 !isSelfVar(val, C)) {
326
327 // Stop tracking the checker-specific state in the state.
328 ProgramStateRef State = C.getState();
329 State = State->remove<CalledInit>();
330 if (SymbolRef sym = loc.getAsSymbol())
331 State = State->remove<SelfFlag>(sym);
332 C.addTransition(State);
333 }
334}
335
336void ObjCSelfInitChecker::printState(raw_ostream &Out, ProgramStateRef State,
337 const char *NL, const char *Sep) const {
338 SelfFlagTy FlagMap = State->get<SelfFlag>();
339 bool DidCallInit = State->get<CalledInit>();
340 SelfFlagEnum PreCallFlags = State->get<PreCallSelfFlags>();
341
342 if (FlagMap.isEmpty() && !DidCallInit && !PreCallFlags)
343 return;
344
345 Out << Sep << NL << *this << " :" << NL;
346
347 if (DidCallInit)
348 Out << " An init method has been called." << NL;
349
350 if (PreCallFlags != SelfFlag_None) {
351 if (PreCallFlags & SelfFlag_Self) {
352 Out << " An argument of the current call came from the 'self' variable."
353 << NL;
354 }
355 if (PreCallFlags & SelfFlag_InitRes) {
356 Out << " An argument of the current call came from an init method."
357 << NL;
358 }
359 }
360
361 Out << NL;
362 for (auto [Sym, Flag] : FlagMap) {
363 Out << Sym << " : ";
364
365 if (Flag == SelfFlag_None)
366 Out << "none";
367
368 if (Flag & SelfFlag_Self)
369 Out << "self variable";
370
371 if (Flag & SelfFlag_InitRes) {
372 if (Flag != SelfFlag_InitRes)
373 Out << " | ";
374 Out << "result of init method";
375 }
376
377 Out << NL;
378 }
379}
380
381
382// FIXME: A callback should disable checkers at the start of functions.
384 if (!ND)
385 return false;
386
387 const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(ND);
388 if (!MD)
389 return false;
390 if (!isInitializationMethod(MD))
391 return false;
392
393 // self = [super init] applies only to NSObject subclasses.
394 // For instance, NSProxy doesn't implement -init.
395 ASTContext &Ctx = MD->getASTContext();
396 IdentifierInfo* NSObjectII = &Ctx.Idents.get("NSObject");
398 for ( ; ID ; ID = ID->getSuperClass()) {
399 IdentifierInfo *II = ID->getIdentifier();
400
401 if (II == NSObjectII)
402 break;
403 }
404 return ID != nullptr;
405}
406
407/// Returns true if the location is 'self'.
408static bool isSelfVar(SVal location, CheckerContext &C) {
409 AnalysisDeclContext *analCtx = C.getCurrentAnalysisDeclContext();
410 if (!analCtx->getSelfDecl())
411 return false;
412 if (!isa<loc::MemRegionVal>(location))
413 return false;
414
416 if (const DeclRegion *DR = dyn_cast<DeclRegion>(MRV.stripCasts()))
417 return (DR->getDecl() == analCtx->getSelfDecl());
418
419 return false;
420}
421
423 return MD->getMethodFamily() == OMF_init;
424}
425
426static bool isInitMessage(const ObjCMethodCall &Call) {
427 return Call.getMethodFamily() == OMF_init;
428}
429
430//===----------------------------------------------------------------------===//
431// Registration.
432//===----------------------------------------------------------------------===//
433
434void ento::registerObjCSelfInitChecker(CheckerManager &mgr) {
435 mgr.registerChecker<ObjCSelfInitChecker>();
436}
437
438bool ento::shouldRegisterObjCSelfInitChecker(const CheckerManager &mgr) {
439 return true;
440}
#define V(N, I)
Definition: ASTContext.h:3285
static bool isInitMessage(const ObjCMethodCall &Msg)
static bool isSelfVar(SVal location, CheckerContext &C)
Returns true if the location is 'self'.
static bool shouldRunOnFunctionOrMethod(const NamedDecl *ND)
static bool isInitializationMethod(const ObjCMethodDecl *MD)
static bool isInvalidSelf(const Expr *E, CheckerContext &C)
Returns true of the value of the expression is the object that 'self' points to and is an object that...
static SelfFlagEnum getSelfFlags(SVal val, ProgramStateRef state)
A call receiving a reference to 'self' invalidates the object that 'self' contains.
static bool hasSelfFlag(SVal val, SelfFlagEnum flag, CheckerContext &C)
static void addSelfFlag(ProgramStateRef state, SVal val, SelfFlagEnum flag, CheckerContext &C)
#define REGISTER_MAP_WITH_PROGRAMSTATE(Name, Key, Value)
Declares an immutable map of type NameTy, suitable for placement into the ProgramState.
#define REGISTER_TRAIT_WITH_PROGRAMSTATE(Name, Type)
Declares a program state trait for type Type called Name, and introduce a type named NameTy.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:182
IdentifierTable & Idents
Definition: ASTContext.h:644
AnalysisDeclContext contains the context data for the function, method or block under analysis.
const ImplicitParamDecl * getSelfDecl() const
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:501
This represents one expression.
Definition: Expr.h:110
One of these records is kept for each identifier that is lexed.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
This represents a decl that may have a name.
Definition: Decl.h:249
Represents an ObjC class declaration.
Definition: DeclObjC.h:1153
ObjCInterfaceDecl * getSuperClass() const
Definition: DeclObjC.cpp:352
ObjCIvarRefExpr - A reference to an ObjC instance variable.
Definition: ExprObjC.h:549
const Expr * getBase() const
Definition: ExprObjC.h:583
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:140
ObjCMethodFamily getMethodFamily() const
Determines the family of this method.
Definition: DeclObjC.cpp:1053
ObjCInterfaceDecl * getClassInterface()
Definition: DeclObjC.cpp:1211
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition: Stmt.h:3019
Stmt - This represents one statement.
Definition: Stmt.h:84
Represents an abstract call to a function or method along a particular path.
Definition: CallEvent.h:153
virtual SVal getArgSVal(unsigned Index) const
Returns the value of a given argument at the time of the call.
Definition: CallEvent.cpp:308
virtual unsigned getNumArgs() const =0
Returns the number of arguments (explicit and implicit).
SVal getReturnValue() const
Returns the return value of the call.
Definition: CallEvent.cpp:322
virtual void printState(raw_ostream &Out, ProgramStateRef State, const char *NL, const char *Sep) const
See CheckerManager::runCheckersForPrintState.
Definition: Checker.h:496
CHECKER * registerChecker(AT &&... Args)
Used to register checkers.
Represents any expression that calls an Objective-C method.
Definition: CallEvent.h:1243
const ObjCMessageExpr * getOriginExpr() const override
Returns the expression whose value will be the result of this call.
Definition: CallEvent.h:1269
SVal - This represents a symbolic expression, which can be either an L-value or an R-value.
Definition: SVals.h:55
SymbolRef getAsSymbol(bool IncludeBaseRegions=false) const
If this SVal wraps a symbol return that SymbolRef.
Definition: SVals.cpp:104
T castAs() const
Convert to the specified SVal type, asserting that this SVal is of the desired type.
Definition: SVals.h:82
Symbolic value.
Definition: SymExpr.h:30
LLVM_ATTRIBUTE_RETURNS_NONNULL const MemRegion * stripCasts(bool StripBaseCasts=true) const
Get the underlining region and strip casts.
Definition: SVals.cpp:186
const char *const CoreFoundationObjectiveC
The JSON file list parser is used to communicate input to InstallAPI.