clang 19.0.0git
MacOSXAPIChecker.cpp
Go to the documentation of this file.
1// MacOSXAPIChecker.h - Checks proper use of various MacOS X APIs --*- 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 MacOSXAPIChecker, which is an assortment of checks on calls
10// to various, widely used Apple APIs.
11//
12// FIXME: What's currently in BasicObjCFoundationChecks.cpp should be migrated
13// to here, using the new Checker interface.
14//
15//===----------------------------------------------------------------------===//
16
17#include "clang/AST/Attr.h"
26#include "llvm/ADT/SmallString.h"
27#include "llvm/ADT/StringSwitch.h"
28#include "llvm/Support/raw_ostream.h"
29
30using namespace clang;
31using namespace ento;
32
33namespace {
34class MacOSXAPIChecker : public Checker< check::PreStmt<CallExpr> > {
35 const BugType BT_dispatchOnce{this, "Improper use of 'dispatch_once'",
37
38 static const ObjCIvarRegion *getParentIvarRegion(const MemRegion *R);
39
40public:
41 void checkPreStmt(const CallExpr *CE, CheckerContext &C) const;
42
43 void CheckDispatchOnce(CheckerContext &C, const CallExpr *CE,
44 StringRef FName) const;
45
46 typedef void (MacOSXAPIChecker::*SubChecker)(CheckerContext &,
47 const CallExpr *,
48 StringRef FName) const;
49};
50} //end anonymous namespace
51
52//===----------------------------------------------------------------------===//
53// dispatch_once and dispatch_once_f
54//===----------------------------------------------------------------------===//
55
56const ObjCIvarRegion *
57MacOSXAPIChecker::getParentIvarRegion(const MemRegion *R) {
58 const SubRegion *SR = dyn_cast<SubRegion>(R);
59 while (SR) {
60 if (const ObjCIvarRegion *IR = dyn_cast<ObjCIvarRegion>(SR))
61 return IR;
62 SR = dyn_cast<SubRegion>(SR->getSuperRegion());
63 }
64 return nullptr;
65}
66
67void MacOSXAPIChecker::CheckDispatchOnce(CheckerContext &C, const CallExpr *CE,
68 StringRef FName) const {
69 if (CE->getNumArgs() < 1)
70 return;
71
72 // Check if the first argument is improperly allocated. If so, issue a
73 // warning because that's likely to be bad news.
74 const MemRegion *R = C.getSVal(CE->getArg(0)).getAsRegion();
75 if (!R)
76 return;
77
78 // Global variables are fine.
79 const MemRegion *RB = R->getBaseRegion();
80 const MemSpaceRegion *RS = RB->getMemorySpace();
81 if (isa<GlobalsSpaceRegion>(RS))
82 return;
83
84 // Handle _dispatch_once. In some versions of the OS X SDK we have the case
85 // that dispatch_once is a macro that wraps a call to _dispatch_once.
86 // _dispatch_once is then a function which then calls the real dispatch_once.
87 // Users do not care; they just want the warning at the top-level call.
88 if (CE->getBeginLoc().isMacroID()) {
89 StringRef TrimmedFName = FName.ltrim('_');
90 if (TrimmedFName != FName)
91 FName = TrimmedFName;
92 }
93
95 llvm::raw_svector_ostream os(S);
96 bool SuggestStatic = false;
97 os << "Call to '" << FName << "' uses";
98 if (const VarRegion *VR = dyn_cast<VarRegion>(RB)) {
99 const VarDecl *VD = VR->getDecl();
100 // FIXME: These should have correct memory space and thus should be filtered
101 // out earlier. This branch only fires when we're looking from a block,
102 // which we analyze as a top-level declaration, onto a static local
103 // in a function that contains the block.
104 if (VD->isStaticLocal())
105 return;
106 // We filtered out globals earlier, so it must be a local variable
107 // or a block variable which is under UnknownSpaceRegion.
108 if (VR != R)
109 os << " memory within";
110 if (VD->hasAttr<BlocksAttr>())
111 os << " the block variable '";
112 else
113 os << " the local variable '";
114 os << VR->getDecl()->getName() << '\'';
115 SuggestStatic = true;
116 } else if (const ObjCIvarRegion *IVR = getParentIvarRegion(R)) {
117 if (IVR != R)
118 os << " memory within";
119 os << " the instance variable '" << IVR->getDecl()->getName() << '\'';
120 } else if (isa<HeapSpaceRegion>(RS)) {
121 os << " heap-allocated memory";
122 } else if (isa<UnknownSpaceRegion>(RS)) {
123 // Presence of an IVar superregion has priority over this branch, because
124 // ObjC objects are on the heap even if the core doesn't realize this.
125 // Presence of a block variable base region has priority over this branch,
126 // because block variables are known to be either on stack or on heap
127 // (might actually move between the two, hence UnknownSpace).
128 return;
129 } else {
130 os << " stack allocated memory";
131 }
132 os << " for the predicate value. Using such transient memory for "
133 "the predicate is potentially dangerous.";
134 if (SuggestStatic)
135 os << " Perhaps you intended to declare the variable as 'static'?";
136
137 ExplodedNode *N = C.generateErrorNode();
138 if (!N)
139 return;
140
141 auto report =
142 std::make_unique<PathSensitiveBugReport>(BT_dispatchOnce, os.str(), N);
143 report->addRange(CE->getArg(0)->getSourceRange());
144 C.emitReport(std::move(report));
145}
146
147//===----------------------------------------------------------------------===//
148// Central dispatch function.
149//===----------------------------------------------------------------------===//
150
151void MacOSXAPIChecker::checkPreStmt(const CallExpr *CE,
152 CheckerContext &C) const {
153 StringRef Name = C.getCalleeName(CE);
154 if (Name.empty())
155 return;
156
157 SubChecker SC =
158 llvm::StringSwitch<SubChecker>(Name)
159 .Cases("dispatch_once",
160 "_dispatch_once",
161 "dispatch_once_f",
162 &MacOSXAPIChecker::CheckDispatchOnce)
163 .Default(nullptr);
164
165 if (SC)
166 (this->*SC)(C, CE, Name);
167}
168
169//===----------------------------------------------------------------------===//
170// Registration.
171//===----------------------------------------------------------------------===//
172
173void ento::registerMacOSXAPIChecker(CheckerManager &mgr) {
174 mgr.registerChecker<MacOSXAPIChecker>();
175}
176
177bool ento::shouldRegisterMacOSXAPIChecker(const CheckerManager &mgr) {
178 return true;
179}
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2820
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: Expr.h:3011
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:1638
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition: Expr.h:2998
bool hasAttr() const
Definition: DeclBase.h:585
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:276
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:326
Represents a variable declaration or definition.
Definition: Decl.h:918
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition: Decl.h:1195
CHECKER * registerChecker(AT &&... Args)
Used to register checkers.
MemRegion - The root abstract class for all memory regions.
Definition: MemRegion.h:96
LLVM_ATTRIBUTE_RETURNS_NONNULL const MemSpaceRegion * getMemorySpace() const
Definition: MemRegion.cpp:1317
LLVM_ATTRIBUTE_RETURNS_NONNULL const MemRegion * getBaseRegion() const
Definition: MemRegion.cpp:1343
MemSpaceRegion - A memory region that represents a "memory space"; for example, the set of global var...
Definition: MemRegion.h:203
SubRegion - A region that subsets another larger region.
Definition: MemRegion.h:441
LLVM_ATTRIBUTE_RETURNS_NONNULL const MemRegion * getSuperRegion() const
Definition: MemRegion.h:454
Defines the clang::TargetInfo interface.
const char *const AppleAPIMisuse
The JSON file list parser is used to communicate input to InstallAPI.