/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/StaticAnalyzer/Checkers/MoveChecker.cpp
Line | Count | Source (jump to first uncovered line) |
1 | | // MoveChecker.cpp - Check use of moved-from objects. - 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 checker which checks for potential misuses of a moved-from |
10 | | // object. That means method calls on the object or copying it in moved-from |
11 | | // state. |
12 | | // |
13 | | //===----------------------------------------------------------------------===// |
14 | | |
15 | | #include "clang/AST/Attr.h" |
16 | | #include "clang/AST/ExprCXX.h" |
17 | | #include "clang/Driver/DriverDiagnostic.h" |
18 | | #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h" |
19 | | #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" |
20 | | #include "clang/StaticAnalyzer/Core/Checker.h" |
21 | | #include "clang/StaticAnalyzer/Core/CheckerManager.h" |
22 | | #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" |
23 | | #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" |
24 | | #include "llvm/ADT/StringSet.h" |
25 | | |
26 | | using namespace clang; |
27 | | using namespace ento; |
28 | | |
29 | | namespace { |
30 | | struct RegionState { |
31 | | private: |
32 | | enum Kind { Moved, Reported } K; |
33 | 2.27k | RegionState(Kind InK) : K(InK) {} |
34 | | |
35 | | public: |
36 | 320 | bool isReported() const { return K == Reported; } |
37 | 16 | bool isMoved() const { return K == Moved; } |
38 | | |
39 | 238 | static RegionState getReported() { return RegionState(Reported); } |
40 | 2.03k | static RegionState getMoved() { return RegionState(Moved); } |
41 | | |
42 | 942 | bool operator==(const RegionState &X) const { return K == X.K; } |
43 | 2.95k | void Profile(llvm::FoldingSetNodeID &ID) const { ID.AddInteger(K); } |
44 | | }; |
45 | | } // end of anonymous namespace |
46 | | |
47 | | namespace { |
48 | | class MoveChecker |
49 | | : public Checker<check::PreCall, check::PostCall, |
50 | | check::DeadSymbols, check::RegionChanges> { |
51 | | public: |
52 | | void checkPreCall(const CallEvent &MC, CheckerContext &C) const; |
53 | | void checkPostCall(const CallEvent &MC, CheckerContext &C) const; |
54 | | void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const; |
55 | | ProgramStateRef |
56 | | checkRegionChanges(ProgramStateRef State, |
57 | | const InvalidatedSymbols *Invalidated, |
58 | | ArrayRef<const MemRegion *> RequestedRegions, |
59 | | ArrayRef<const MemRegion *> InvalidatedRegions, |
60 | | const LocationContext *LCtx, const CallEvent *Call) const; |
61 | | void printState(raw_ostream &Out, ProgramStateRef State, |
62 | | const char *NL, const char *Sep) const override; |
63 | | |
64 | | private: |
65 | | enum MisuseKind { MK_FunCall, MK_Copy, MK_Move, MK_Dereference }; |
66 | | enum StdObjectKind { SK_NonStd, SK_Unsafe, SK_Safe, SK_SmartPtr }; |
67 | | |
68 | | enum AggressivenessKind { // In any case, don't warn after a reset. |
69 | | AK_Invalid = -1, |
70 | | AK_KnownsOnly = 0, // Warn only about known move-unsafe classes. |
71 | | AK_KnownsAndLocals = 1, // Also warn about all local objects. |
72 | | AK_All = 2, // Warn on any use-after-move. |
73 | | AK_NumKinds = AK_All |
74 | | }; |
75 | | |
76 | 316 | static bool misuseCausesCrash(MisuseKind MK) { |
77 | 316 | return MK == MK_Dereference; |
78 | 316 | } |
79 | | |
80 | | struct ObjectKind { |
81 | | // Is this a local variable or a local rvalue reference? |
82 | | bool IsLocal; |
83 | | // Is this an STL object? If so, of what kind? |
84 | | StdObjectKind StdKind; |
85 | | }; |
86 | | |
87 | | // STL smart pointers are automatically re-initialized to null when moved |
88 | | // from. So we can't warn on many methods, but we can warn when it is |
89 | | // dereferenced, which is UB even if the resulting lvalue never gets read. |
90 | | const llvm::StringSet<> StdSmartPtrClasses = { |
91 | | "shared_ptr", |
92 | | "unique_ptr", |
93 | | "weak_ptr", |
94 | | }; |
95 | | |
96 | | // Not all of these are entirely move-safe, but they do provide *some* |
97 | | // guarantees, and it means that somebody is using them after move |
98 | | // in a valid manner. |
99 | | // TODO: We can still try to identify *unsafe* use after move, |
100 | | // like we did with smart pointers. |
101 | | const llvm::StringSet<> StdSafeClasses = { |
102 | | "basic_filebuf", |
103 | | "basic_ios", |
104 | | "future", |
105 | | "optional", |
106 | | "packaged_task", |
107 | | "promise", |
108 | | "shared_future", |
109 | | "shared_lock", |
110 | | "thread", |
111 | | "unique_lock", |
112 | | }; |
113 | | |
114 | | // Should we bother tracking the state of the object? |
115 | 3.46k | bool shouldBeTracked(ObjectKind OK) const { |
116 | | // In non-aggressive mode, only warn on use-after-move of local variables |
117 | | // (or local rvalue references) and of STL objects. The former is possible |
118 | | // because local variables (or local rvalue references) are not tempting |
119 | | // their user to re-use the storage. The latter is possible because STL |
120 | | // objects are known to end up in a valid but unspecified state after the |
121 | | // move and their state-reset methods are also known, which allows us to |
122 | | // predict precisely when use-after-move is invalid. |
123 | | // Some STL objects are known to conform to additional contracts after move, |
124 | | // so they are not tracked. However, smart pointers specifically are tracked |
125 | | // because we can perform extra checking over them. |
126 | | // In aggressive mode, warn on any use-after-move because the user has |
127 | | // intentionally asked us to completely eliminate use-after-move |
128 | | // in his code. |
129 | 3.46k | return (Aggressiveness == AK_All) || |
130 | 3.46k | (1.76k Aggressiveness >= AK_KnownsAndLocals1.76k && OK.IsLocal1.05k ) || |
131 | 3.46k | OK.StdKind == SK_Unsafe1.12k || OK.StdKind == SK_SmartPtr1.08k ; |
132 | 3.46k | } |
133 | | |
134 | | // Some objects only suffer from some kinds of misuses, but we need to track |
135 | | // them anyway because we cannot know in advance what misuse will we find. |
136 | 364 | bool shouldWarnAbout(ObjectKind OK, MisuseKind MK) const { |
137 | | // Additionally, only warn on smart pointers when they are dereferenced (or |
138 | | // local or we are aggressive). |
139 | 364 | return shouldBeTracked(OK) && |
140 | 364 | ((Aggressiveness == AK_All) || |
141 | 364 | (104 Aggressiveness >= AK_KnownsAndLocals104 && OK.IsLocal92 ) || |
142 | 364 | OK.StdKind != SK_SmartPtr18 || MK == MK_Dereference14 ); |
143 | 364 | } |
144 | | |
145 | | // Obtains ObjectKind of an object. Because class declaration cannot always |
146 | | // be easily obtained from the memory region, it is supplied separately. |
147 | | ObjectKind classifyObject(const MemRegion *MR, const CXXRecordDecl *RD) const; |
148 | | |
149 | | // Classifies the object and dumps a user-friendly description string to |
150 | | // the stream. |
151 | | void explainObject(llvm::raw_ostream &OS, const MemRegion *MR, |
152 | | const CXXRecordDecl *RD, MisuseKind MK) const; |
153 | | |
154 | | bool belongsTo(const CXXRecordDecl *RD, const llvm::StringSet<> &Set) const; |
155 | | |
156 | | class MovedBugVisitor : public BugReporterVisitor { |
157 | | public: |
158 | | MovedBugVisitor(const MoveChecker &Chk, const MemRegion *R, |
159 | | const CXXRecordDecl *RD, MisuseKind MK) |
160 | 250 | : Chk(Chk), Region(R), RD(RD), MK(MK), Found(false) {} |
161 | | |
162 | 250 | void Profile(llvm::FoldingSetNodeID &ID) const override { |
163 | 250 | static int X = 0; |
164 | 250 | ID.AddPointer(&X); |
165 | 250 | ID.AddPointer(Region); |
166 | | // Don't add RD because it's, in theory, uniquely determined by |
167 | | // the region. In practice though, it's not always possible to obtain |
168 | | // the declaration directly from the region, that's why we store it |
169 | | // in the first place. |
170 | 250 | } |
171 | | |
172 | | PathDiagnosticPieceRef VisitNode(const ExplodedNode *N, |
173 | | BugReporterContext &BRC, |
174 | | PathSensitiveBugReport &BR) override; |
175 | | |
176 | | private: |
177 | | const MoveChecker &Chk; |
178 | | // The tracked region. |
179 | | const MemRegion *Region; |
180 | | // The class of the tracked object. |
181 | | const CXXRecordDecl *RD; |
182 | | // How exactly the object was misused. |
183 | | const MisuseKind MK; |
184 | | bool Found; |
185 | | }; |
186 | | |
187 | | AggressivenessKind Aggressiveness = AK_KnownsAndLocals; |
188 | | |
189 | | public: |
190 | 78 | void setAggressiveness(StringRef Str, CheckerManager &Mgr) { |
191 | 78 | Aggressiveness = |
192 | 78 | llvm::StringSwitch<AggressivenessKind>(Str) |
193 | 78 | .Case("KnownsOnly", AK_KnownsOnly) |
194 | 78 | .Case("KnownsAndLocals", AK_KnownsAndLocals) |
195 | 78 | .Case("All", AK_All) |
196 | 78 | .Default(AK_Invalid); |
197 | | |
198 | 78 | if (Aggressiveness == AK_Invalid) |
199 | 1 | Mgr.reportInvalidCheckerOptionValue(this, "WarnOn", |
200 | 1 | "either \"KnownsOnly\", \"KnownsAndLocals\" or \"All\" string value"); |
201 | 78 | }; |
202 | | |
203 | | private: |
204 | | BugType BT{this, "Use-after-move", categories::CXXMoveSemantics}; |
205 | | |
206 | | // Check if the given form of potential misuse of a given object |
207 | | // should be reported. If so, get it reported. The callback from which |
208 | | // this function was called should immediately return after the call |
209 | | // because this function adds one or two transitions. |
210 | | void modelUse(ProgramStateRef State, const MemRegion *Region, |
211 | | const CXXRecordDecl *RD, MisuseKind MK, |
212 | | CheckerContext &C) const; |
213 | | |
214 | | // Returns the exploded node against which the report was emitted. |
215 | | // The caller *must* add any further transitions against this node. |
216 | | // Returns nullptr and does not report if such node already exists. |
217 | | ExplodedNode *tryToReportBug(const MemRegion *Region, const CXXRecordDecl *RD, |
218 | | CheckerContext &C, MisuseKind MK) const; |
219 | | |
220 | | bool isInMoveSafeContext(const LocationContext *LC) const; |
221 | | bool isStateResetMethod(const CXXMethodDecl *MethodDec) const; |
222 | | bool isMoveSafeMethod(const CXXMethodDecl *MethodDec) const; |
223 | | const ExplodedNode *getMoveLocation(const ExplodedNode *N, |
224 | | const MemRegion *Region, |
225 | | CheckerContext &C) const; |
226 | | }; |
227 | | } // end anonymous namespace |
228 | | |
229 | | REGISTER_MAP_WITH_PROGRAMSTATE(TrackedRegionMap, const MemRegion *, RegionState) |
230 | | |
231 | | // Define the inter-checker API. |
232 | | namespace clang { |
233 | | namespace ento { |
234 | | namespace move { |
235 | 26 | bool isMovedFrom(ProgramStateRef State, const MemRegion *Region) { |
236 | 26 | const RegionState *RS = State->get<TrackedRegionMap>(Region); |
237 | 26 | return RS && (8 RS->isMoved()8 || RS->isReported()0 ); |
238 | 26 | } |
239 | | } // namespace move |
240 | | } // namespace ento |
241 | | } // namespace clang |
242 | | |
243 | | // If a region is removed all of the subregions needs to be removed too. |
244 | | static ProgramStateRef removeFromState(ProgramStateRef State, |
245 | 57.8k | const MemRegion *Region) { |
246 | 57.8k | if (!Region) |
247 | 0 | return State; |
248 | 57.8k | for (auto &E : State->get<TrackedRegionMap>()) { |
249 | 1.59k | if (E.first->isSubRegionOf(Region)) |
250 | 616 | State = State->remove<TrackedRegionMap>(E.first); |
251 | 1.59k | } |
252 | 57.8k | return State; |
253 | 57.8k | } |
254 | | |
255 | | static bool isAnyBaseRegionReported(ProgramStateRef State, |
256 | 316 | const MemRegion *Region) { |
257 | 396 | for (auto &E : State->get<TrackedRegionMap>()) { |
258 | 396 | if (Region->isSubRegionOf(E.first) && E.second.isReported()320 ) |
259 | 66 | return true; |
260 | 396 | } |
261 | 250 | return false; |
262 | 316 | } |
263 | | |
264 | 20.5k | static const MemRegion *unwrapRValueReferenceIndirection(const MemRegion *MR) { |
265 | 20.5k | if (const auto *SR = dyn_cast_or_null<SymbolicRegion>(MR)) { |
266 | 3.34k | SymbolRef Sym = SR->getSymbol(); |
267 | 3.34k | if (Sym->getType()->isRValueReferenceType()) |
268 | 64 | if (const MemRegion *OriginMR = Sym->getOriginRegion()) |
269 | 56 | return OriginMR; |
270 | 3.34k | } |
271 | 20.5k | return MR; |
272 | 20.5k | } |
273 | | |
274 | | PathDiagnosticPieceRef |
275 | | MoveChecker::MovedBugVisitor::VisitNode(const ExplodedNode *N, |
276 | | BugReporterContext &BRC, |
277 | 135k | PathSensitiveBugReport &BR) { |
278 | | // We need only the last move of the reported object's region. |
279 | | // The visitor walks the ExplodedGraph backwards. |
280 | 135k | if (Found) |
281 | 132k | return nullptr; |
282 | 3.17k | ProgramStateRef State = N->getState(); |
283 | 3.17k | ProgramStateRef StatePrev = N->getFirstPred()->getState(); |
284 | 3.17k | const RegionState *TrackedObject = State->get<TrackedRegionMap>(Region); |
285 | 3.17k | const RegionState *TrackedObjectPrev = |
286 | 3.17k | StatePrev->get<TrackedRegionMap>(Region); |
287 | 3.17k | if (!TrackedObject) |
288 | 0 | return nullptr; |
289 | 3.17k | if (TrackedObjectPrev && TrackedObject2.95k ) |
290 | 2.95k | return nullptr; |
291 | | |
292 | | // Retrieve the associated statement. |
293 | 226 | const Stmt *S = N->getStmtForDiagnostics(); |
294 | 226 | if (!S) |
295 | 0 | return nullptr; |
296 | 226 | Found = true; |
297 | | |
298 | 226 | SmallString<128> Str; |
299 | 226 | llvm::raw_svector_ostream OS(Str); |
300 | | |
301 | 226 | ObjectKind OK = Chk.classifyObject(Region, RD); |
302 | 226 | switch (OK.StdKind) { |
303 | 30 | case SK_SmartPtr: |
304 | 30 | if (MK == MK_Dereference) { |
305 | 12 | OS << "Smart pointer"; |
306 | 12 | Chk.explainObject(OS, Region, RD, MK); |
307 | 12 | OS << " is reset to null when moved from"; |
308 | 12 | break; |
309 | 12 | } |
310 | | |
311 | | // If it's not a dereference, we don't care if it was reset to null |
312 | | // or that it is even a smart pointer. |
313 | 30 | [[fallthrough]];18 |
314 | 202 | case SK_NonStd: |
315 | 206 | case SK_Safe: |
316 | 206 | OS << "Object"; |
317 | 206 | Chk.explainObject(OS, Region, RD, MK); |
318 | 206 | OS << " is moved"; |
319 | 206 | break; |
320 | 8 | case SK_Unsafe: |
321 | 8 | OS << "Object"; |
322 | 8 | Chk.explainObject(OS, Region, RD, MK); |
323 | 8 | OS << " is left in a valid but unspecified state after move"; |
324 | 8 | break; |
325 | 226 | } |
326 | | |
327 | | // Generate the extra diagnostic. |
328 | 226 | PathDiagnosticLocation Pos(S, BRC.getSourceManager(), |
329 | 226 | N->getLocationContext()); |
330 | 226 | return std::make_shared<PathDiagnosticEventPiece>(Pos, OS.str(), true); |
331 | 226 | } |
332 | | |
333 | | const ExplodedNode *MoveChecker::getMoveLocation(const ExplodedNode *N, |
334 | | const MemRegion *Region, |
335 | 250 | CheckerContext &C) const { |
336 | | // Walk the ExplodedGraph backwards and find the first node that referred to |
337 | | // the tracked region. |
338 | 250 | const ExplodedNode *MoveNode = N; |
339 | | |
340 | 4.01k | while (N) { |
341 | 4.01k | ProgramStateRef State = N->getState(); |
342 | 4.01k | if (!State->get<TrackedRegionMap>(Region)) |
343 | 250 | break; |
344 | 3.76k | MoveNode = N; |
345 | 3.76k | N = N->pred_empty() ? nullptr0 : *(N->pred_begin()); |
346 | 3.76k | } |
347 | 250 | return MoveNode; |
348 | 250 | } |
349 | | |
350 | | void MoveChecker::modelUse(ProgramStateRef State, const MemRegion *Region, |
351 | | const CXXRecordDecl *RD, MisuseKind MK, |
352 | 16.3k | CheckerContext &C) const { |
353 | 16.3k | assert(!C.isDifferent() && "No transitions should have been made by now"); |
354 | 16.3k | const RegionState *RS = State->get<TrackedRegionMap>(Region); |
355 | 16.3k | ObjectKind OK = classifyObject(Region, RD); |
356 | | |
357 | | // Just in case: if it's not a smart pointer but it does have operator *, |
358 | | // we shouldn't call the bug a dereference. |
359 | 16.3k | if (MK == MK_Dereference && OK.StdKind != SK_SmartPtr138 ) |
360 | 64 | MK = MK_FunCall; |
361 | | |
362 | 16.3k | if (!RS || !shouldWarnAbout(OK, MK)364 |
363 | 16.3k | || isInMoveSafeContext(C.getLocationContext())356 ) { |
364 | | // Finalize changes made by the caller. |
365 | 15.9k | C.addTransition(State); |
366 | 15.9k | return; |
367 | 15.9k | } |
368 | | |
369 | | // Don't report it in case if any base region is already reported. |
370 | | // But still generate a sink in case of UB. |
371 | | // And still finalize changes made by the caller. |
372 | 316 | if (isAnyBaseRegionReported(State, Region)) { |
373 | 66 | if (misuseCausesCrash(MK)) { |
374 | 4 | C.generateSink(State, C.getPredecessor()); |
375 | 62 | } else { |
376 | 62 | C.addTransition(State); |
377 | 62 | } |
378 | 66 | return; |
379 | 66 | } |
380 | | |
381 | 250 | ExplodedNode *N = tryToReportBug(Region, RD, C, MK); |
382 | | |
383 | | // If the program has already crashed on this path, don't bother. |
384 | 250 | if (!N || N->isSink()) |
385 | 12 | return; |
386 | | |
387 | 238 | State = State->set<TrackedRegionMap>(Region, RegionState::getReported()); |
388 | 238 | C.addTransition(State, N); |
389 | 238 | } |
390 | | |
391 | | ExplodedNode *MoveChecker::tryToReportBug(const MemRegion *Region, |
392 | | const CXXRecordDecl *RD, |
393 | | CheckerContext &C, |
394 | 250 | MisuseKind MK) const { |
395 | 250 | if (ExplodedNode *N = misuseCausesCrash(MK) ? C.generateErrorNode() |
396 | 250 | : C.generateNonFatalErrorNode()) { |
397 | | // Uniqueing report to the same object. |
398 | 250 | PathDiagnosticLocation LocUsedForUniqueing; |
399 | 250 | const ExplodedNode *MoveNode = getMoveLocation(N, Region, C); |
400 | | |
401 | 250 | if (const Stmt *MoveStmt = MoveNode->getStmtForDiagnostics()) |
402 | 250 | LocUsedForUniqueing = PathDiagnosticLocation::createBegin( |
403 | 250 | MoveStmt, C.getSourceManager(), MoveNode->getLocationContext()); |
404 | | |
405 | | // Creating the error message. |
406 | 250 | llvm::SmallString<128> Str; |
407 | 250 | llvm::raw_svector_ostream OS(Str); |
408 | 250 | switch(MK) { |
409 | 198 | case MK_FunCall: |
410 | 198 | OS << "Method called on moved-from object"; |
411 | 198 | explainObject(OS, Region, RD, MK); |
412 | 198 | break; |
413 | 18 | case MK_Copy: |
414 | 18 | OS << "Moved-from object"; |
415 | 18 | explainObject(OS, Region, RD, MK); |
416 | 18 | OS << " is copied"; |
417 | 18 | break; |
418 | 22 | case MK_Move: |
419 | 22 | OS << "Moved-from object"; |
420 | 22 | explainObject(OS, Region, RD, MK); |
421 | 22 | OS << " is moved"; |
422 | 22 | break; |
423 | 12 | case MK_Dereference: |
424 | 12 | OS << "Dereference of null smart pointer"; |
425 | 12 | explainObject(OS, Region, RD, MK); |
426 | 12 | break; |
427 | 250 | } |
428 | | |
429 | 250 | auto R = std::make_unique<PathSensitiveBugReport>( |
430 | 250 | BT, OS.str(), N, LocUsedForUniqueing, |
431 | 250 | MoveNode->getLocationContext()->getDecl()); |
432 | 250 | R->addVisitor(std::make_unique<MovedBugVisitor>(*this, Region, RD, MK)); |
433 | 250 | C.emitReport(std::move(R)); |
434 | 250 | return N; |
435 | 250 | } |
436 | 0 | return nullptr; |
437 | 250 | } |
438 | | |
439 | | void MoveChecker::checkPostCall(const CallEvent &Call, |
440 | 50.6k | CheckerContext &C) const { |
441 | 50.6k | const auto *AFC = dyn_cast<AnyFunctionCall>(&Call); |
442 | 50.6k | if (!AFC) |
443 | 3 | return; |
444 | | |
445 | 50.6k | ProgramStateRef State = C.getState(); |
446 | 50.6k | const auto MethodDecl = dyn_cast_or_null<CXXMethodDecl>(AFC->getDecl()); |
447 | 50.6k | if (!MethodDecl) |
448 | 28.0k | return; |
449 | | |
450 | | // Check if an object became moved-from. |
451 | | // Object can become moved from after a call to move assignment operator or |
452 | | // move constructor . |
453 | 22.6k | const auto *ConstructorDecl = dyn_cast<CXXConstructorDecl>(MethodDecl); |
454 | 22.6k | if (ConstructorDecl && !ConstructorDecl->isMoveConstructor()14.0k ) |
455 | 11.9k | return; |
456 | | |
457 | 10.7k | if (!ConstructorDecl && !MethodDecl->isMoveAssignmentOperator()8.67k ) |
458 | 7.28k | return; |
459 | | |
460 | 3.46k | const auto ArgRegion = AFC->getArgSVal(0).getAsRegion(); |
461 | 3.46k | if (!ArgRegion) |
462 | 0 | return; |
463 | | |
464 | | // Skip moving the object to itself. |
465 | 3.46k | const auto *CC = dyn_cast_or_null<CXXConstructorCall>(&Call); |
466 | 3.46k | if (CC && CC->getCXXThisVal().getAsRegion() == ArgRegion2.07k ) |
467 | 0 | return; |
468 | | |
469 | 3.46k | if (const auto *IC = dyn_cast<CXXInstanceCall>(AFC)) |
470 | 1.38k | if (IC->getCXXThisVal().getAsRegion() == ArgRegion) |
471 | 0 | return; |
472 | | |
473 | 3.46k | const MemRegion *BaseRegion = ArgRegion->getBaseRegion(); |
474 | | // Skip temp objects because of their short lifetime. |
475 | 3.46k | if (BaseRegion->getAs<CXXTempObjectRegion>() || |
476 | 3.46k | AFC->getArgExpr(0)->isPRValue()3.16k ) |
477 | 300 | return; |
478 | | // If it has already been reported do not need to modify the state. |
479 | | |
480 | 3.16k | if (State->get<TrackedRegionMap>(ArgRegion)) |
481 | 64 | return; |
482 | | |
483 | 3.09k | const CXXRecordDecl *RD = MethodDecl->getParent(); |
484 | 3.09k | ObjectKind OK = classifyObject(ArgRegion, RD); |
485 | 3.09k | if (shouldBeTracked(OK)) { |
486 | | // Mark object as moved-from. |
487 | 2.03k | State = State->set<TrackedRegionMap>(ArgRegion, RegionState::getMoved()); |
488 | 2.03k | C.addTransition(State); |
489 | 2.03k | return; |
490 | 2.03k | } |
491 | 1.06k | assert(!C.isDifferent() && "Should not have made transitions on this path!"); |
492 | 1.06k | } |
493 | | |
494 | 8.39k | bool MoveChecker::isMoveSafeMethod(const CXXMethodDecl *MethodDec) const { |
495 | | // We abandon the cases where bool/void/void* conversion happens. |
496 | 8.39k | if (const auto *ConversionDec = |
497 | 8.39k | dyn_cast_or_null<CXXConversionDecl>(MethodDec)) { |
498 | 139 | const Type *Tp = ConversionDec->getConversionType().getTypePtrOrNull(); |
499 | 139 | if (!Tp) |
500 | 0 | return false; |
501 | 139 | if (Tp->isBooleanType() || Tp->isVoidType()22 || Tp->isVoidPointerType()22 ) |
502 | 117 | return true; |
503 | 139 | } |
504 | | // Function call `empty` can be skipped. |
505 | 8.27k | return (MethodDec && MethodDec->getDeclName().isIdentifier()7.98k && |
506 | 8.27k | (5.23k MethodDec->getName().lower() == "empty"5.23k || |
507 | 5.23k | MethodDec->getName().lower() == "isempty"5.22k )); |
508 | 8.39k | } |
509 | | |
510 | 8.53k | bool MoveChecker::isStateResetMethod(const CXXMethodDecl *MethodDec) const { |
511 | 8.53k | if (!MethodDec) |
512 | 294 | return false; |
513 | 8.23k | if (MethodDec->hasAttr<ReinitializesAttr>()) |
514 | 8 | return true; |
515 | 8.22k | if (MethodDec->getDeclName().isIdentifier()) { |
516 | 5.36k | std::string MethodName = MethodDec->getName().lower(); |
517 | | // TODO: Some of these methods (eg., resize) are not always resetting |
518 | | // the state, so we should consider looking at the arguments. |
519 | 5.36k | if (MethodName == "assign" || MethodName == "clear"5.33k || |
520 | 5.36k | MethodName == "destroy"5.29k || MethodName == "reset"5.28k || |
521 | 5.36k | MethodName == "resize"5.24k || MethodName == "shrink"5.23k ) |
522 | 129 | return true; |
523 | 5.36k | } |
524 | 8.10k | return false; |
525 | 8.22k | } |
526 | | |
527 | | // Don't report an error inside a move related operation. |
528 | | // We assume that the programmer knows what she does. |
529 | 356 | bool MoveChecker::isInMoveSafeContext(const LocationContext *LC) const { |
530 | 370 | do { |
531 | 370 | const auto *CtxDec = LC->getDecl(); |
532 | 370 | auto *CtorDec = dyn_cast_or_null<CXXConstructorDecl>(CtxDec); |
533 | 370 | auto *DtorDec = dyn_cast_or_null<CXXDestructorDecl>(CtxDec); |
534 | 370 | auto *MethodDec = dyn_cast_or_null<CXXMethodDecl>(CtxDec); |
535 | 370 | if (DtorDec || (CtorDec && CtorDec->isCopyOrMoveConstructor()32 ) || |
536 | 370 | (338 MethodDec338 && MethodDec->isOverloadedOperator()44 && |
537 | 338 | MethodDec->getOverloadedOperator() == OO_Equal8 ) || |
538 | 370 | isStateResetMethod(MethodDec)330 || isMoveSafeMethod(MethodDec)330 ) |
539 | 40 | return true; |
540 | 370 | } while ((LC = LC->getParent())330 ); |
541 | 316 | return false; |
542 | 356 | } |
543 | | |
544 | | bool MoveChecker::belongsTo(const CXXRecordDecl *RD, |
545 | 6.65k | const llvm::StringSet<> &Set) const { |
546 | 6.65k | const IdentifierInfo *II = RD->getIdentifier(); |
547 | 6.65k | return II && Set.count(II->getName()); |
548 | 6.65k | } |
549 | | |
550 | | MoveChecker::ObjectKind |
551 | | MoveChecker::classifyObject(const MemRegion *MR, |
552 | 20.1k | const CXXRecordDecl *RD) const { |
553 | | // Local variables and local rvalue references are classified as "Local". |
554 | | // For the purposes of this checker, we classify move-safe STL types |
555 | | // as not-"STL" types, because that's how the checker treats them. |
556 | 20.1k | MR = unwrapRValueReferenceIndirection(MR); |
557 | 20.1k | bool IsLocal = |
558 | 20.1k | isa_and_nonnull<VarRegion, CXXLifetimeExtendedObjectRegion>(MR) && |
559 | 20.1k | isa<StackSpaceRegion>(MR->getMemorySpace())7.54k ; |
560 | | |
561 | 20.1k | if (!RD || !RD->getDeclContext()->isStdNamespace()) |
562 | 16.5k | return { IsLocal, SK_NonStd }; |
563 | | |
564 | 3.53k | if (belongsTo(RD, StdSmartPtrClasses)) |
565 | 414 | return { IsLocal, SK_SmartPtr }; |
566 | | |
567 | 3.12k | if (belongsTo(RD, StdSafeClasses)) |
568 | 40 | return { IsLocal, SK_Safe }; |
569 | | |
570 | 3.08k | return { IsLocal, SK_Unsafe }; |
571 | 3.12k | } |
572 | | |
573 | | void MoveChecker::explainObject(llvm::raw_ostream &OS, const MemRegion *MR, |
574 | 476 | const CXXRecordDecl *RD, MisuseKind MK) const { |
575 | | // We may need a leading space every time we actually explain anything, |
576 | | // and we never know if we are to explain anything until we try. |
577 | 476 | if (const auto DR = |
578 | 476 | dyn_cast_or_null<DeclRegion>(unwrapRValueReferenceIndirection(MR))) { |
579 | 440 | const auto *RegionDecl = cast<NamedDecl>(DR->getDecl()); |
580 | 440 | OS << " '" << RegionDecl->getDeclName() << "'"; |
581 | 440 | } |
582 | | |
583 | 476 | ObjectKind OK = classifyObject(MR, RD); |
584 | 476 | switch (OK.StdKind) { |
585 | 392 | case SK_NonStd: |
586 | 400 | case SK_Safe: |
587 | 400 | break; |
588 | 60 | case SK_SmartPtr: |
589 | 60 | if (MK != MK_Dereference) |
590 | 36 | break; |
591 | | |
592 | | // We only care about the type if it's a dereference. |
593 | 60 | [[fallthrough]];24 |
594 | 40 | case SK_Unsafe: |
595 | 40 | OS << " of type '" << RD->getQualifiedNameAsString() << "'"; |
596 | 40 | break; |
597 | 476 | }; |
598 | 476 | } |
599 | | |
600 | 49.2k | void MoveChecker::checkPreCall(const CallEvent &Call, CheckerContext &C) const { |
601 | 49.2k | ProgramStateRef State = C.getState(); |
602 | | |
603 | | // Remove the MemRegions from the map on which a ctor/dtor call or assignment |
604 | | // happened. |
605 | | |
606 | | // Checking constructor calls. |
607 | 49.2k | if (const auto *CC = dyn_cast<CXXConstructorCall>(&Call)) { |
608 | 14.0k | State = removeFromState(State, CC->getCXXThisVal().getAsRegion()); |
609 | 14.0k | auto CtorDec = CC->getDecl(); |
610 | | // Check for copying a moved-from object and report the bug. |
611 | 14.0k | if (CtorDec && CtorDec->isCopyOrMoveConstructor()) { |
612 | 8.38k | const MemRegion *ArgRegion = CC->getArgSVal(0).getAsRegion(); |
613 | 8.38k | const CXXRecordDecl *RD = CtorDec->getParent(); |
614 | 8.38k | MisuseKind MK = CtorDec->isMoveConstructor() ? MK_Move2.08k : MK_Copy6.30k ; |
615 | 8.38k | modelUse(State, ArgRegion, RD, MK, C); |
616 | 8.38k | return; |
617 | 8.38k | } |
618 | 14.0k | } |
619 | | |
620 | 40.8k | const auto IC = dyn_cast<CXXInstanceCall>(&Call); |
621 | 40.8k | if (!IC) |
622 | 32.1k | return; |
623 | | |
624 | 8.73k | const MemRegion *ThisRegion = IC->getCXXThisVal().getAsRegion(); |
625 | 8.73k | if (!ThisRegion) |
626 | 2 | return; |
627 | | |
628 | | // The remaining part is check only for method call on a moved-from object. |
629 | 8.72k | const auto MethodDecl = dyn_cast_or_null<CXXMethodDecl>(IC->getDecl()); |
630 | 8.72k | if (!MethodDecl) |
631 | 2 | return; |
632 | | |
633 | | // Calling a destructor on a moved object is fine. |
634 | 8.72k | if (isa<CXXDestructorDecl>(MethodDecl)) |
635 | 525 | return; |
636 | | |
637 | | // We want to investigate the whole object, not only sub-object of a parent |
638 | | // class in which the encountered method defined. |
639 | 8.20k | ThisRegion = ThisRegion->getMostDerivedObjectRegion(); |
640 | | |
641 | 8.20k | if (isStateResetMethod(MethodDecl)) { |
642 | 137 | State = removeFromState(State, ThisRegion); |
643 | 137 | C.addTransition(State); |
644 | 137 | return; |
645 | 137 | } |
646 | | |
647 | 8.06k | if (isMoveSafeMethod(MethodDecl)) |
648 | 133 | return; |
649 | | |
650 | | // Store class declaration as well, for bug reporting purposes. |
651 | 7.93k | const CXXRecordDecl *RD = MethodDecl->getParent(); |
652 | | |
653 | 7.93k | if (MethodDecl->isOverloadedOperator()) { |
654 | 2.72k | OverloadedOperatorKind OOK = MethodDecl->getOverloadedOperator(); |
655 | | |
656 | 2.72k | if (OOK == OO_Equal) { |
657 | | // Remove the tracked object for every assignment operator, but report bug |
658 | | // only for move or copy assignment's argument. |
659 | 1.45k | State = removeFromState(State, ThisRegion); |
660 | | |
661 | 1.45k | if (MethodDecl->isCopyAssignmentOperator() || |
662 | 1.45k | MethodDecl->isMoveAssignmentOperator()1.40k ) { |
663 | 1.43k | const MemRegion *ArgRegion = IC->getArgSVal(0).getAsRegion(); |
664 | 1.43k | MisuseKind MK = |
665 | 1.43k | MethodDecl->isMoveAssignmentOperator() ? MK_Move1.38k : MK_Copy50 ; |
666 | 1.43k | modelUse(State, ArgRegion, RD, MK, C); |
667 | 1.43k | return; |
668 | 1.43k | } |
669 | 14 | C.addTransition(State); |
670 | 14 | return; |
671 | 1.45k | } |
672 | | |
673 | 1.27k | if (OOK == OO_Star || OOK == OO_Arrow1.20k ) { |
674 | 138 | modelUse(State, ThisRegion, RD, MK_Dereference, C); |
675 | 138 | return; |
676 | 138 | } |
677 | 1.27k | } |
678 | | |
679 | 6.34k | modelUse(State, ThisRegion, RD, MK_FunCall, C); |
680 | 6.34k | } |
681 | | |
682 | | void MoveChecker::checkDeadSymbols(SymbolReaper &SymReaper, |
683 | 167k | CheckerContext &C) const { |
684 | 167k | ProgramStateRef State = C.getState(); |
685 | 167k | TrackedRegionMapTy TrackedRegions = State->get<TrackedRegionMap>(); |
686 | 167k | for (auto E : TrackedRegions) { |
687 | 8.82k | const MemRegion *Region = E.first; |
688 | 8.82k | bool IsRegDead = !SymReaper.isLiveRegion(Region); |
689 | | |
690 | | // Remove the dead regions from the region map. |
691 | 8.82k | if (IsRegDead) { |
692 | 1.30k | State = State->remove<TrackedRegionMap>(Region); |
693 | 1.30k | } |
694 | 8.82k | } |
695 | 167k | C.addTransition(State); |
696 | 167k | } |
697 | | |
698 | | ProgramStateRef MoveChecker::checkRegionChanges( |
699 | | ProgramStateRef State, const InvalidatedSymbols *Invalidated, |
700 | | ArrayRef<const MemRegion *> RequestedRegions, |
701 | | ArrayRef<const MemRegion *> InvalidatedRegions, |
702 | 47.5k | const LocationContext *LCtx, const CallEvent *Call) const { |
703 | 47.5k | if (Call) { |
704 | | // Relax invalidation upon function calls: only invalidate parameters |
705 | | // that are passed directly via non-const pointers or non-const references |
706 | | // or rvalue references. |
707 | | // In case of an InstanceCall don't invalidate the this-region since |
708 | | // it is fully handled in checkPreCall and checkPostCall. |
709 | 13.1k | const MemRegion *ThisRegion = nullptr; |
710 | 13.1k | if (const auto *IC = dyn_cast<CXXInstanceCall>(Call)) |
711 | 5.47k | ThisRegion = IC->getCXXThisVal().getAsRegion(); |
712 | | |
713 | | // Requested ("explicit") regions are the regions passed into the call |
714 | | // directly, but not all of them end up being invalidated. |
715 | | // But when they do, they appear in the InvalidatedRegions array as well. |
716 | 13.9k | for (const auto *Region : RequestedRegions) { |
717 | 13.9k | if (ThisRegion != Region && |
718 | 13.9k | llvm::is_contained(InvalidatedRegions, Region)9.85k ) |
719 | 7.90k | State = removeFromState(State, Region); |
720 | 13.9k | } |
721 | 34.3k | } else { |
722 | | // For invalidations that aren't caused by calls, assume nothing. In |
723 | | // particular, direct write into an object's field invalidates the status. |
724 | 34.3k | for (const auto *Region : InvalidatedRegions) |
725 | 34.3k | State = removeFromState(State, Region->getBaseRegion()); |
726 | 34.3k | } |
727 | | |
728 | 47.5k | return State; |
729 | 47.5k | } |
730 | | |
731 | | void MoveChecker::printState(raw_ostream &Out, ProgramStateRef State, |
732 | 40 | const char *NL, const char *Sep) const { |
733 | | |
734 | 40 | TrackedRegionMapTy RS = State->get<TrackedRegionMap>(); |
735 | | |
736 | 40 | if (!RS.isEmpty()) { |
737 | 4 | Out << Sep << "Moved-from objects :" << NL; |
738 | 8 | for (auto I: RS) { |
739 | 8 | I.first->dumpToStream(Out); |
740 | 8 | if (I.second.isMoved()) |
741 | 8 | Out << ": moved"; |
742 | 0 | else |
743 | 0 | Out << ": moved and reported"; |
744 | 8 | Out << NL; |
745 | 8 | } |
746 | 4 | } |
747 | 40 | } |
748 | 78 | void ento::registerMoveChecker(CheckerManager &mgr) { |
749 | 78 | MoveChecker *chk = mgr.registerChecker<MoveChecker>(); |
750 | 78 | chk->setAggressiveness( |
751 | 78 | mgr.getAnalyzerOptions().getCheckerStringOption(chk, "WarnOn"), mgr); |
752 | 78 | } |
753 | | |
754 | 156 | bool ento::shouldRegisterMoveChecker(const CheckerManager &mgr) { |
755 | 156 | return true; |
756 | 156 | } |