clang 23.0.0git
CheckerManager.cpp
Go to the documentation of this file.
1//===- CheckerManager.cpp - Static Analyzer Checker Manager ---------------===//
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// Defines the Static Analyzer Checker Manager.
10//
11//===----------------------------------------------------------------------===//
12
14#include "clang/AST/DeclBase.h"
15#include "clang/AST/Stmt.h"
18#include "clang/Basic/LLVM.h"
26#include "llvm/ADT/SmallVector.h"
27#include "llvm/Support/ErrorHandling.h"
28#include "llvm/Support/FormatVariadic.h"
29#include "llvm/Support/TimeProfiler.h"
30#include <cassert>
31#include <optional>
32#include <vector>
33
34using namespace clang;
35using namespace ento;
36
38 const auto IfAnyAreNonEmpty = [](const auto &... Callbacks) -> bool {
39 return (!Callbacks.empty() || ...);
40 };
41 return IfAnyAreNonEmpty(
42 StmtCheckers, PreObjCMessageCheckers, ObjCMessageNilCheckers,
43 PostObjCMessageCheckers, PreCallCheckers, PostCallCheckers,
44 LocationCheckers, BindCheckers, BlockEntranceCheckers,
45 EndAnalysisCheckers, BeginFunctionCheckers, EndFunctionCheckers,
46 BranchConditionCheckers, NewAllocatorCheckers, LiveSymbolsCheckers,
47 DeadSymbolsCheckers, RegionChangesCheckers, PointerEscapeCheckers,
48 EvalAssumeCheckers, EvalCallCheckers, EndOfTranslationUnitCheckers);
49}
50
52 const CheckerFrontend *Checker, StringRef OptionName,
53 StringRef ExpectedValueDesc) const {
54
55 getDiagnostics().Report(diag::err_analyzer_checker_option_invalid_input)
56 << (llvm::Twine(Checker->getName()) + ":" + OptionName).str()
57 << ExpectedValueDesc;
58}
59
60//===----------------------------------------------------------------------===//
61// Functions for running checkers for AST traversing..
62//===----------------------------------------------------------------------===//
63
65 BugReporter &BR) {
66 assert(D);
67
68 unsigned DeclKind = D->getKind();
69 auto [CCI, Inserted] = CachedDeclCheckersMap.try_emplace(DeclKind);
70 CachedDeclCheckers *checkers = &(CCI->second);
71 if (Inserted) {
72 // Find the checkers that should run for this Decl and cache them.
73 for (const auto &info : DeclCheckers)
74 if (info.IsForDeclFn(D))
75 checkers->push_back(info.CheckFn);
76 }
77
78 assert(checkers);
79 for (const auto &checker : *checkers)
80 checker(D, mgr, BR);
81}
82
84 BugReporter &BR) {
85 assert(D && D->hasBody());
86
87 for (const auto &BodyChecker : BodyCheckers)
88 BodyChecker(D, mgr, BR);
89}
90
91//===----------------------------------------------------------------------===//
92// Functions for running checkers for path-sensitive checking.
93//===----------------------------------------------------------------------===//
94
95template <typename CHECK_CTX>
96static void expandGraphWithCheckers(CHECK_CTX checkCtx,
97 ExplodedNodeSet &Dst,
98 const ExplodedNodeSet &Src) {
99 const NodeBuilderContext &BldrCtx = checkCtx.Eng.getBuilderContext();
100 if (Src.empty())
101 return;
102
103 typename CHECK_CTX::CheckersTy::const_iterator
104 I = checkCtx.checkers_begin(), E = checkCtx.checkers_end();
105 if (I == E) {
106 Dst.insert(Src);
107 return;
108 }
109
110 ExplodedNodeSet Tmp1, Tmp2;
111 const ExplodedNodeSet *PrevSet = &Src;
112
113 for (; I != E; ++I) {
114 ExplodedNodeSet *CurrSet = nullptr;
115 if (I+1 == E)
116 CurrSet = &Dst;
117 else {
118 CurrSet = (PrevSet == &Tmp1) ? &Tmp2 : &Tmp1;
119 CurrSet->clear();
120 }
121
122 NodeBuilder B(*PrevSet, *CurrSet, BldrCtx);
123 for (const auto &NI : *PrevSet)
124 checkCtx.runChecker(*I, B, NI);
125
126 // If all the produced transitions are sinks, stop.
127 if (CurrSet->empty())
128 return;
129
130 // Update which NodeSet is the current one.
131 PrevSet = CurrSet;
132 }
133}
134
135namespace {
136
137std::string checkerScopeName(StringRef Name, const CheckerBackend *Checker) {
138 if (!llvm::timeTraceProfilerEnabled())
139 return "";
140 StringRef CheckerTag = Checker ? Checker->getDebugTag() : "<unknown>";
141 return (Name + ":" + CheckerTag).str();
142}
143
144 struct CheckStmtContext {
145 using CheckersTy = SmallVectorImpl<CheckerManager::CheckStmtFunc>;
146
147 bool IsPreVisit;
148 const CheckersTy &Checkers;
149 const Stmt *S;
150 ExprEngine &Eng;
151 bool WasInlined;
152
153 CheckStmtContext(bool isPreVisit, const CheckersTy &checkers,
154 const Stmt *s, ExprEngine &eng, bool wasInlined = false)
155 : IsPreVisit(isPreVisit), Checkers(checkers), S(s), Eng(eng),
156 WasInlined(wasInlined) {}
157
158 CheckersTy::const_iterator checkers_begin() { return Checkers.begin(); }
159 CheckersTy::const_iterator checkers_end() { return Checkers.end(); }
160
161 void runChecker(CheckerManager::CheckStmtFunc checkFn,
162 NodeBuilder &Bldr, ExplodedNode *Pred) {
163 llvm::TimeTraceScope TimeScope(checkerScopeName("Stmt", checkFn.Checker));
164 // FIXME: Remove respondsToCallback from CheckerContext;
168 S, K, Pred->getStackFrame(), checkFn.Checker);
169 CheckerContext C(Bldr, Eng, Pred, L, WasInlined);
170 checkFn(S, C);
171 }
172 };
173
174} // namespace
175
176/// Run checkers for visiting Stmts.
178 ExplodedNodeSet &Dst,
179 const ExplodedNodeSet &Src,
180 const Stmt *S,
181 ExprEngine &Eng,
182 bool WasInlined) {
183 CheckStmtContext C(isPreVisit, getCachedStmtCheckersFor(S, isPreVisit),
184 S, Eng, WasInlined);
185 llvm::TimeTraceScope TimeScope(
186 isPreVisit ? "CheckerManager::runCheckersForStmt (Pre)"
187 : "CheckerManager::runCheckersForStmt (Post)");
188 expandGraphWithCheckers(C, Dst, Src);
189}
190
191namespace {
192
193 struct CheckObjCMessageContext {
194 using CheckersTy = std::vector<CheckerManager::CheckObjCMessageFunc>;
195
197 bool WasInlined;
198 const CheckersTy &Checkers;
199 const ObjCMethodCall &Msg;
200 ExprEngine &Eng;
201
202 CheckObjCMessageContext(ObjCMessageVisitKind visitKind,
203 const CheckersTy &checkers,
204 const ObjCMethodCall &msg, ExprEngine &eng,
205 bool wasInlined)
206 : Kind(visitKind), WasInlined(wasInlined), Checkers(checkers), Msg(msg),
207 Eng(eng) {}
208
209 CheckersTy::const_iterator checkers_begin() { return Checkers.begin(); }
210 CheckersTy::const_iterator checkers_end() { return Checkers.end(); }
211
212 void runChecker(CheckerManager::CheckObjCMessageFunc checkFn,
213 NodeBuilder &Bldr, ExplodedNode *Pred) {
214 llvm::TimeTraceScope TimeScope(
215 checkerScopeName("ObjCMsg", checkFn.Checker));
216 bool IsPreVisit;
217
218 switch (Kind) {
219 case ObjCMessageVisitKind::Pre:
220 IsPreVisit = true;
221 break;
222 case ObjCMessageVisitKind::MessageNil:
223 case ObjCMessageVisitKind::Post:
224 IsPreVisit = false;
225 break;
226 }
227
228 const ProgramPoint &L = Msg.getProgramPoint(IsPreVisit,checkFn.Checker);
229 CheckerContext C(Bldr, Eng, Pred, L, WasInlined);
230
231 checkFn(*Msg.cloneWithState<ObjCMethodCall>(Pred->getState()), C);
232 }
233 };
234
235} // namespace
236
237/// Run checkers for visiting obj-c messages.
239 ExplodedNodeSet &Dst,
240 const ExplodedNodeSet &Src,
241 const ObjCMethodCall &msg,
242 ExprEngine &Eng,
243 bool WasInlined) {
244 const auto &checkers = getObjCMessageCheckers(visitKind);
245 CheckObjCMessageContext C(visitKind, checkers, msg, Eng, WasInlined);
246 llvm::TimeTraceScope TimeScope("CheckerManager::runCheckersForObjCMessage");
247 expandGraphWithCheckers(C, Dst, Src);
248}
249
250const std::vector<CheckerManager::CheckObjCMessageFunc> &
251CheckerManager::getObjCMessageCheckers(ObjCMessageVisitKind Kind) const {
252 switch (Kind) {
254 return PreObjCMessageCheckers;
255 break;
257 return PostObjCMessageCheckers;
259 return ObjCMessageNilCheckers;
260 }
261 llvm_unreachable("Unknown Kind");
262}
263
264namespace {
265
266 // FIXME: This has all the same signatures as CheckObjCMessageContext.
267 // Is there a way we can merge the two?
268 struct CheckCallContext {
269 using CheckersTy = std::vector<CheckerManager::CheckCallFunc>;
270
271 bool IsPreVisit, WasInlined;
272 const CheckersTy &Checkers;
273 const CallEvent &Call;
274 ExprEngine &Eng;
275
276 CheckCallContext(bool isPreVisit, const CheckersTy &checkers,
277 const CallEvent &call, ExprEngine &eng,
278 bool wasInlined)
279 : IsPreVisit(isPreVisit), WasInlined(wasInlined), Checkers(checkers),
280 Call(call), Eng(eng) {}
281
282 CheckersTy::const_iterator checkers_begin() { return Checkers.begin(); }
283 CheckersTy::const_iterator checkers_end() { return Checkers.end(); }
284
285 void runChecker(CheckerManager::CheckCallFunc checkFn,
286 NodeBuilder &Bldr, ExplodedNode *Pred) {
287 llvm::TimeTraceScope TimeScope(checkerScopeName("Call", checkFn.Checker));
288 const ProgramPoint &L = Call.getProgramPoint(IsPreVisit,checkFn.Checker);
289 CheckerContext C(Bldr, Eng, Pred, L, WasInlined);
290
291 checkFn(*Call.cloneWithState(Pred->getState()), C);
292 }
293 };
294
295} // namespace
296
297/// Run checkers for visiting an abstract call event.
299 ExplodedNodeSet &Dst,
300 const ExplodedNodeSet &Src,
301 const CallEvent &Call,
302 ExprEngine &Eng,
303 bool WasInlined) {
304 CheckCallContext C(isPreVisit,
305 isPreVisit ? PreCallCheckers
306 : PostCallCheckers,
307 Call, Eng, WasInlined);
308 llvm::TimeTraceScope TimeScope(
309 isPreVisit ? "CheckerManager::runCheckersForCallEvent (Pre)"
310 : "CheckerManager::runCheckersForCallEvent (Post)");
311 expandGraphWithCheckers(C, Dst, Src);
312}
313
314namespace {
315
316 struct CheckLocationContext {
317 using CheckersTy = std::vector<CheckerManager::CheckLocationFunc>;
318
319 const CheckersTy &Checkers;
320 SVal Loc;
321 bool IsLoad;
322 const Stmt *NodeEx; /* Will become a CFGStmt */
323 const Stmt *BoundEx;
324 ExprEngine &Eng;
325
326 CheckLocationContext(const CheckersTy &checkers,
327 SVal loc, bool isLoad, const Stmt *NodeEx,
328 const Stmt *BoundEx,
329 ExprEngine &eng)
330 : Checkers(checkers), Loc(loc), IsLoad(isLoad), NodeEx(NodeEx),
331 BoundEx(BoundEx), Eng(eng) {}
332
333 CheckersTy::const_iterator checkers_begin() { return Checkers.begin(); }
334 CheckersTy::const_iterator checkers_end() { return Checkers.end(); }
335
336 void runChecker(CheckerManager::CheckLocationFunc checkFn,
337 NodeBuilder &Bldr, ExplodedNode *Pred) {
338 llvm::TimeTraceScope TimeScope(checkerScopeName("Loc", checkFn.Checker));
342 NodeEx, K, Pred->getStackFrame(), checkFn.Checker);
343 CheckerContext C(Bldr, Eng, Pred, L);
344 checkFn(Loc, IsLoad, BoundEx, C);
345 }
346 };
347
348} // namespace
349
350/// Run checkers for load/store of a location.
351
353 const ExplodedNodeSet &Src,
354 SVal location, bool isLoad,
355 const Stmt *NodeEx,
356 const Stmt *BoundEx,
357 ExprEngine &Eng) {
358 CheckLocationContext C(LocationCheckers, location, isLoad, NodeEx,
359 BoundEx, Eng);
360 llvm::TimeTraceScope TimeScope(
361 isLoad ? "CheckerManager::runCheckersForLocation (Load)"
362 : "CheckerManager::runCheckersForLocation (Store)");
363 expandGraphWithCheckers(C, Dst, Src);
364}
365
366namespace {
367
368 struct CheckBindContext {
369 using CheckersTy = std::vector<CheckerManager::CheckBindFunc>;
370
371 const CheckersTy &Checkers;
372 SVal Loc;
373 SVal Val;
374 const Stmt *S;
375 ExprEngine &Eng;
376 const ProgramPoint &PP;
377 bool AtDeclInit;
378
379 CheckBindContext(const CheckersTy &checkers, SVal loc, SVal val,
380 const Stmt *s, bool AtDeclInit, ExprEngine &eng,
381 const ProgramPoint &pp)
382 : Checkers(checkers), Loc(loc), Val(val), S(s), Eng(eng), PP(pp),
383 AtDeclInit(AtDeclInit) {}
384
385 CheckersTy::const_iterator checkers_begin() { return Checkers.begin(); }
386 CheckersTy::const_iterator checkers_end() { return Checkers.end(); }
387
388 void runChecker(CheckerManager::CheckBindFunc checkFn,
389 NodeBuilder &Bldr, ExplodedNode *Pred) {
390 llvm::TimeTraceScope TimeScope(checkerScopeName("Bind", checkFn.Checker));
391 const ProgramPoint &L = PP.withTag(checkFn.Checker);
392 CheckerContext C(Bldr, Eng, Pred, L);
393
394 checkFn(Loc, Val, S, AtDeclInit, C);
395 }
396 };
397
398 llvm::TimeTraceMetadata getTimeTraceBindMetadata(SVal Val) {
399 assert(llvm::timeTraceProfilerEnabled());
400 std::string Name;
401 llvm::raw_string_ostream OS(Name);
402 Val.dumpToStream(OS);
403 return llvm::TimeTraceMetadata{OS.str(), ""};
404 }
405
406} // namespace
407
408/// Run checkers for binding of a value to a location.
410 const ExplodedNodeSet &Src,
411 SVal location, SVal val, const Stmt *S,
412 bool AtDeclInit, ExprEngine &Eng,
413 const ProgramPoint &PP) {
414 CheckBindContext C(BindCheckers, location, val, S, AtDeclInit, Eng, PP);
415 llvm::TimeTraceScope TimeScope{
416 "CheckerManager::runCheckersForBind",
417 [&val]() { return getTimeTraceBindMetadata(val); }};
418 expandGraphWithCheckers(C, Dst, Src);
419}
420
421namespace {
422struct CheckBlockEntranceContext {
423 using CheckBlockEntranceFunc = CheckerManager::CheckBlockEntranceFunc;
424 using CheckersTy = std::vector<CheckBlockEntranceFunc>;
425
426 const CheckersTy &Checkers;
427 const BlockEntrance &Entrance;
428 ExprEngine &Eng;
429
430 CheckBlockEntranceContext(const CheckersTy &Checkers,
431 const BlockEntrance &Entrance, ExprEngine &Eng)
432 : Checkers(Checkers), Entrance(Entrance), Eng(Eng) {}
433
434 auto checkers_begin() const { return Checkers.begin(); }
435 auto checkers_end() const { return Checkers.end(); }
436
437 void runChecker(CheckBlockEntranceFunc CheckFn, NodeBuilder &Bldr,
438 ExplodedNode *Pred) {
439 llvm::TimeTraceScope TimeScope(
440 checkerScopeName("BlockEntrance", CheckFn.Checker));
441 CheckerContext C(Bldr, Eng, Pred, Entrance.withTag(CheckFn.Checker));
442 CheckFn(Entrance, C);
443 }
444};
445
446} // namespace
447
449 const ExplodedNodeSet &Src,
450 const BlockEntrance &Entrance,
451 ExprEngine &Eng) const {
452 CheckBlockEntranceContext C(BlockEntranceCheckers, Entrance, Eng);
453 llvm::TimeTraceScope TimeScope{"CheckerManager::runCheckersForBlockEntrance"};
454 expandGraphWithCheckers(C, Dst, Src);
455}
456
458 BugReporter &BR,
459 ExprEngine &Eng) {
460 for (const auto &EndAnalysisChecker : EndAnalysisCheckers)
461 EndAnalysisChecker(G, BR, Eng);
462}
463
464namespace {
465
466struct CheckBeginFunctionContext {
467 using CheckersTy = std::vector<CheckerManager::CheckBeginFunctionFunc>;
468
469 const CheckersTy &Checkers;
470 ExprEngine &Eng;
471 const ProgramPoint &PP;
472
473 CheckBeginFunctionContext(const CheckersTy &Checkers, ExprEngine &Eng,
474 const ProgramPoint &PP)
475 : Checkers(Checkers), Eng(Eng), PP(PP) {}
476
477 CheckersTy::const_iterator checkers_begin() { return Checkers.begin(); }
478 CheckersTy::const_iterator checkers_end() { return Checkers.end(); }
479
480 void runChecker(CheckerManager::CheckBeginFunctionFunc checkFn,
481 NodeBuilder &Bldr, ExplodedNode *Pred) {
482 llvm::TimeTraceScope TimeScope(checkerScopeName("Begin", checkFn.Checker));
483 const ProgramPoint &L = PP.withTag(checkFn.Checker);
484 CheckerContext C(Bldr, Eng, Pred, L);
485
486 checkFn(C);
487 }
488};
489
490} // namespace
491
493 const BlockEdge &L,
494 ExplodedNode *Pred,
495 ExprEngine &Eng) {
496 ExplodedNodeSet Src;
497 Src.insert(Pred);
498 CheckBeginFunctionContext C(BeginFunctionCheckers, Eng, L);
499 llvm::TimeTraceScope TimeScope("CheckerManager::runCheckersForBeginFunction");
500 expandGraphWithCheckers(C, Dst, Src);
501}
502
503/// Run checkers for end of path.
504// Note, We do not chain the checker output (like in expandGraphWithCheckers)
505// for this callback since end of path nodes are expected to be final.
507 ExplodedNode *Pred,
508 ExprEngine &Eng,
509 const ReturnStmt *RS) {
510 // We define the builder outside of the loop because if at least one checker
511 // creates a successor for Pred, we do not need to generate an
512 // autotransition for it.
513 NodeBuilder Bldr(Pred, Dst, Eng.getBuilderContext());
514 for (const auto &checkFn : EndFunctionCheckers) {
515 const ProgramPoint &L =
516 FunctionExitPoint(RS, Pred->getStackFrame(), checkFn.Checker);
517 CheckerContext C(Bldr, Eng, Pred, L);
518 llvm::TimeTraceScope TimeScope(checkerScopeName("End", checkFn.Checker));
519 checkFn(RS, C);
520 }
521}
522
523namespace {
524
525 struct CheckBranchConditionContext {
526 using CheckersTy = std::vector<CheckerManager::CheckBranchConditionFunc>;
527
528 const CheckersTy &Checkers;
529 const Stmt *Condition;
530 ExprEngine &Eng;
531
532 CheckBranchConditionContext(const CheckersTy &checkers,
533 const Stmt *Cond, ExprEngine &eng)
534 : Checkers(checkers), Condition(Cond), Eng(eng) {}
535
536 CheckersTy::const_iterator checkers_begin() { return Checkers.begin(); }
537 CheckersTy::const_iterator checkers_end() { return Checkers.end(); }
538
539 void runChecker(CheckerManager::CheckBranchConditionFunc checkFn,
540 NodeBuilder &Bldr, ExplodedNode *Pred) {
541 llvm::TimeTraceScope TimeScope(
542 checkerScopeName("BranchCond", checkFn.Checker));
543 ProgramPoint L =
544 PostCondition(Condition, Pred->getStackFrame(), checkFn.Checker);
545 CheckerContext C(Bldr, Eng, Pred, L);
546 checkFn(Condition, C);
547 }
548 };
549
550} // namespace
551
552/// Run checkers for branch condition.
554 ExplodedNodeSet &Dst,
555 ExplodedNode *Pred,
556 ExprEngine &Eng) {
557 ExplodedNodeSet Src;
558 Src.insert(Pred);
559 CheckBranchConditionContext C(BranchConditionCheckers, Condition, Eng);
560 llvm::TimeTraceScope TimeScope(
561 "CheckerManager::runCheckersForBranchCondition");
562 expandGraphWithCheckers(C, Dst, Src);
563}
564
565namespace {
566
567 struct CheckNewAllocatorContext {
568 using CheckersTy = std::vector<CheckerManager::CheckNewAllocatorFunc>;
569
570 const CheckersTy &Checkers;
571 const CXXAllocatorCall &Call;
572 bool WasInlined;
573 ExprEngine &Eng;
574
575 CheckNewAllocatorContext(const CheckersTy &Checkers,
576 const CXXAllocatorCall &Call, bool WasInlined,
577 ExprEngine &Eng)
578 : Checkers(Checkers), Call(Call), WasInlined(WasInlined), Eng(Eng) {}
579
580 CheckersTy::const_iterator checkers_begin() { return Checkers.begin(); }
581 CheckersTy::const_iterator checkers_end() { return Checkers.end(); }
582
583 void runChecker(CheckerManager::CheckNewAllocatorFunc checkFn,
584 NodeBuilder &Bldr, ExplodedNode *Pred) {
585 llvm::TimeTraceScope TimeScope(
586 checkerScopeName("Allocator", checkFn.Checker));
587 ProgramPoint L = PostAllocatorCall(
588 Call.getOriginExpr(), Pred->getStackFrame(), checkFn.Checker);
589 CheckerContext C(Bldr, Eng, Pred, L, WasInlined);
590 checkFn(cast<CXXAllocatorCall>(*Call.cloneWithState(Pred->getState())),
591 C);
592 }
593 };
594
595} // namespace
596
598 ExplodedNodeSet &Dst,
599 ExplodedNode *Pred,
600 ExprEngine &Eng,
601 bool WasInlined) {
602 ExplodedNodeSet Src;
603 Src.insert(Pred);
604 CheckNewAllocatorContext C(NewAllocatorCheckers, Call, WasInlined, Eng);
605 llvm::TimeTraceScope TimeScope("CheckerManager::runCheckersForNewAllocator");
606 expandGraphWithCheckers(C, Dst, Src);
607}
608
609/// Run checkers for live symbols.
611 SymbolReaper &SymReaper) {
612 for (const auto &LiveSymbolsChecker : LiveSymbolsCheckers)
613 LiveSymbolsChecker(state, SymReaper);
614}
615
616namespace {
617
618 struct CheckDeadSymbolsContext {
619 using CheckersTy = std::vector<CheckerManager::CheckDeadSymbolsFunc>;
620
621 const CheckersTy &Checkers;
622 SymbolReaper &SR;
623 const Stmt *S;
624 ExprEngine &Eng;
625 ProgramPoint::Kind ProgarmPointKind;
626
627 CheckDeadSymbolsContext(const CheckersTy &checkers, SymbolReaper &sr,
628 const Stmt *s, ExprEngine &eng,
630 : Checkers(checkers), SR(sr), S(s), Eng(eng), ProgarmPointKind(K) {}
631
632 CheckersTy::const_iterator checkers_begin() { return Checkers.begin(); }
633 CheckersTy::const_iterator checkers_end() { return Checkers.end(); }
634
635 void runChecker(CheckerManager::CheckDeadSymbolsFunc checkFn,
636 NodeBuilder &Bldr, ExplodedNode *Pred) {
637 llvm::TimeTraceScope TimeScope(
638 checkerScopeName("DeadSymbols", checkFn.Checker));
640 S, ProgarmPointKind, Pred->getStackFrame(), checkFn.Checker);
641 CheckerContext C(Bldr, Eng, Pred, L);
642
643 // Note, do not pass the statement to the checkers without letting them
644 // differentiate if we ran remove dead bindings before or after the
645 // statement.
646 checkFn(SR, C);
647 }
648 };
649
650} // namespace
651
652/// Run checkers for dead symbols.
654 const ExplodedNodeSet &Src,
655 SymbolReaper &SymReaper,
656 const Stmt *S,
657 ExprEngine &Eng,
659 CheckDeadSymbolsContext C(DeadSymbolsCheckers, SymReaper, S, Eng, K);
660 llvm::TimeTraceScope TimeScope("CheckerManager::runCheckersForDeadSymbols");
661 expandGraphWithCheckers(C, Dst, Src);
662}
663
664/// Run checkers for region changes.
666 ProgramStateRef state, const InvalidatedSymbols *invalidated,
667 ArrayRef<const MemRegion *> ExplicitRegions,
668 ArrayRef<const MemRegion *> Regions, const StackFrame *SF,
669 const CallEvent *Call) {
670 for (const auto &RegionChangesChecker : RegionChangesCheckers) {
671 // If any checker declares the state infeasible (or if it starts that way),
672 // bail out.
673 if (!state)
674 return nullptr;
675 state = RegionChangesChecker(state, invalidated, ExplicitRegions, Regions,
676 SF, Call);
677 }
678 return state;
679}
680
681/// Run checkers to process symbol escape event.
684 const InvalidatedSymbols &Escaped,
685 const CallEvent *Call,
688 assert((Call != nullptr ||
689 (Kind != PSK_DirectEscapeOnCall &&
690 Kind != PSK_IndirectEscapeOnCall)) &&
691 "Call must not be NULL when escaping on call");
692 for (const auto &PointerEscapeChecker : PointerEscapeCheckers) {
693 // If any checker declares the state infeasible (or if it starts that
694 // way), bail out.
695 if (!State)
696 return nullptr;
697 State = PointerEscapeChecker(State, Escaped, Call, Kind, ETraits);
698 }
699 return State;
700}
701
702/// Run checkers for handling assumptions on symbolic values.
705 SVal Cond, bool Assumption) {
706 for (const auto &EvalAssumeChecker : EvalAssumeCheckers) {
707 // If any checker declares the state infeasible (or if it starts that way),
708 // bail out.
709 if (!state)
710 return nullptr;
711 state = EvalAssumeChecker(state, Cond, Assumption);
712 }
713 return state;
714}
715
716/// Run checkers for evaluating a call.
717/// Only one checker will evaluate the call.
719 const ExplodedNodeSet &Src,
720 const CallEvent &Call,
721 ExprEngine &Eng,
722 const EvalCallOptions &CallOpts) {
723 for (auto *const Pred : Src) {
724 std::optional<StringRef> evaluatorChecker;
725
726 ExplodedNodeSet checkDst;
727 NodeBuilder B(Pred, checkDst, Eng.getBuilderContext());
728
729 ProgramStateRef State = Pred->getState();
730 CallEventRef<> UpdatedCall = Call.cloneWithState(State);
731
732 // Check if any of the EvalCall callbacks can evaluate the call.
733 for (const auto &EvalCallChecker : EvalCallCheckers) {
734 // TODO: Support the situation when the call doesn't correspond
735 // to any Expr.
737 UpdatedCall->getOriginExpr(), ProgramPoint::PostStmtKind,
738 Pred->getStackFrame(), EvalCallChecker.Checker);
739 bool evaluated = false;
740 { // CheckerContext generates transitions (populates checkDest) on
741 // destruction, so introduce the scope to make sure it gets properly
742 // populated.
743 CheckerContext C(B, Eng, Pred, L);
744 evaluated = EvalCallChecker(*UpdatedCall, C);
745 }
746#ifndef NDEBUG
747 if (evaluated && evaluatorChecker) {
748 const auto toString = [](const CallEvent &Call) -> std::string {
749 std::string Buf;
750 llvm::raw_string_ostream OS(Buf);
751 Call.dump(OS);
752 return Buf;
753 };
754 std::string AssertionMessage = llvm::formatv(
755 "The '{0}' call has been already evaluated by the {1} checker, "
756 "while the {2} checker also tried to evaluate the same call. At "
757 "most one checker supposed to evaluate a call.",
758 toString(Call), evaluatorChecker,
759 EvalCallChecker.Checker->getDebugTag());
760 llvm_unreachable(AssertionMessage.c_str());
761 }
762#endif
763 if (evaluated) {
764 evaluatorChecker = EvalCallChecker.Checker->getDebugTag();
765 Dst.insert(checkDst);
766#ifdef NDEBUG
767 break; // on release don't check that no other checker also evals.
768#endif
769 }
770 }
771
772 // If none of the checkers evaluated the call, ask ExprEngine to handle it.
773 if (!evaluatorChecker) {
774 NodeBuilder B(Pred, Dst, Eng.getBuilderContext());
775 Eng.defaultEvalCall(B, Pred, *UpdatedCall, CallOpts);
776 }
777 }
778}
779
780/// Run checkers for the entire Translation Unit.
782 const TranslationUnitDecl *TU,
783 AnalysisManager &mgr,
784 BugReporter &BR) {
785 for (const auto &EndOfTranslationUnitChecker : EndOfTranslationUnitCheckers)
786 EndOfTranslationUnitChecker(TU, mgr, BR);
787}
788
790 ProgramStateRef State,
791 const char *NL,
792 unsigned int Space,
793 bool IsDot) const {
794 Indent(Out, Space, IsDot) << "\"checker_messages\": ";
795
796 // Create a temporary stream to see whether we have any message.
797 SmallString<1024> TempBuf;
798 llvm::raw_svector_ostream TempOut(TempBuf);
799 unsigned int InnerSpace = Space + 2;
800
801 // Create the new-line in JSON with enough space.
802 SmallString<128> NewLine;
803 llvm::raw_svector_ostream NLOut(NewLine);
804 NLOut << "\", " << NL; // Inject the ending and a new line
805 Indent(NLOut, InnerSpace, IsDot) << "\""; // then begin the next message.
806
807 ++Space;
808 bool HasMessage = false;
809
810 // Store the last CheckerTag.
811 const void *LastCT = nullptr;
812 for (const auto &CT : CheckerTags) {
813 // See whether the current checker has a message.
814 CT.second->printState(TempOut, State, /*NL=*/NewLine.c_str(), /*Sep=*/"");
815
816 if (TempBuf.empty())
817 continue;
818
819 if (!HasMessage) {
820 Out << '[' << NL;
821 HasMessage = true;
822 }
823
824 LastCT = &CT;
825 TempBuf.clear();
826 }
827
828 for (const auto &CT : CheckerTags) {
829 // See whether the current checker has a message.
830 CT.second->printState(TempOut, State, /*NL=*/NewLine.c_str(), /*Sep=*/"");
831
832 if (TempBuf.empty())
833 continue;
834
835 Indent(Out, Space, IsDot) << "{ \"checker\": \"" << CT.second->getDebugTag()
836 << "\", \"messages\": [" << NL;
837 Indent(Out, InnerSpace, IsDot)
838 << '\"' << TempBuf.str().trim() << '\"' << NL;
839 Indent(Out, Space, IsDot) << "]}";
840
841 if (&CT != LastCT)
842 Out << ',';
843 Out << NL;
844
845 TempBuf.clear();
846 }
847
848 // It is the last element of the 'program_state' so do not add a comma.
849 if (HasMessage)
850 Indent(Out, --Space, IsDot) << "]";
851 else
852 Out << "null";
853
854 Out << NL;
855}
856
857//===----------------------------------------------------------------------===//
858// Internal registration functions for AST traversing.
859//===----------------------------------------------------------------------===//
860
862 HandlesDeclFunc isForDeclFn) {
863 DeclCheckerInfo info = { checkfn, isForDeclFn };
864 DeclCheckers.push_back(info);
865}
866
868 BodyCheckers.push_back(checkfn);
869}
870
871//===----------------------------------------------------------------------===//
872// Internal registration functions for path-sensitive checking.
873//===----------------------------------------------------------------------===//
874
876 HandlesStmtFunc isForStmtFn) {
877 StmtCheckerInfo info = { checkfn, isForStmtFn, /*IsPreVisit*/true };
878 StmtCheckers.push_back(info);
879}
880
882 HandlesStmtFunc isForStmtFn) {
883 StmtCheckerInfo info = { checkfn, isForStmtFn, /*IsPreVisit*/false };
884 StmtCheckers.push_back(info);
885}
886
888 PreObjCMessageCheckers.push_back(checkfn);
889}
890
892 ObjCMessageNilCheckers.push_back(checkfn);
893}
894
896 PostObjCMessageCheckers.push_back(checkfn);
897}
898
900 PreCallCheckers.push_back(checkfn);
901}
903 PostCallCheckers.push_back(checkfn);
904}
905
907 LocationCheckers.push_back(checkfn);
908}
909
911 BindCheckers.push_back(checkfn);
912}
913
915 BlockEntranceCheckers.push_back(checkfn);
916}
917
919 EndAnalysisCheckers.push_back(checkfn);
920}
921
923 BeginFunctionCheckers.push_back(checkfn);
924}
925
927 EndFunctionCheckers.push_back(checkfn);
928}
929
931 CheckBranchConditionFunc checkfn) {
932 BranchConditionCheckers.push_back(checkfn);
933}
934
936 NewAllocatorCheckers.push_back(checkfn);
937}
938
940 LiveSymbolsCheckers.push_back(checkfn);
941}
942
944 DeadSymbolsCheckers.push_back(checkfn);
945}
946
948 RegionChangesCheckers.push_back(checkfn);
949}
950
952 PointerEscapeCheckers.push_back(checkfn);
953}
954
956 CheckPointerEscapeFunc checkfn) {
957 PointerEscapeCheckers.push_back(checkfn);
958}
959
961 EvalAssumeCheckers.push_back(checkfn);
962}
963
965 EvalCallCheckers.push_back(checkfn);
966}
967
970 EndOfTranslationUnitCheckers.push_back(checkfn);
971}
972
973//===----------------------------------------------------------------------===//
974// Implementation details.
975//===----------------------------------------------------------------------===//
976
977const CheckerManager::CachedStmtCheckers &
978CheckerManager::getCachedStmtCheckersFor(const Stmt *S, bool isPreVisit) {
979 assert(S);
980
981 unsigned Key = (S->getStmtClass() << 1) | unsigned(isPreVisit);
982 auto [CCI, Inserted] = CachedStmtCheckersMap.try_emplace(Key);
983 CachedStmtCheckers &Checkers = CCI->second;
984 if (Inserted) {
985 // Find the checkers that should run for this Stmt and cache them.
986 for (const auto &Info : StmtCheckers)
987 if (Info.IsPreVisit == isPreVisit && Info.IsForStmtFn(S))
988 Checkers.push_back(Info.CheckFn);
989 }
990 return Checkers;
991}
static void expandGraphWithCheckers(CHECK_CTX checkCtx, ExplodedNodeSet &Dst, const ExplodedNodeSet &Src)
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
__device__ __2f16 float __ockl_bool s
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
virtual bool hasBody() const
Returns true if this Decl represents a declaration for a body of code, such as a function or method d...
Definition DeclBase.h:1106
Kind getKind() const
Definition DeclBase.h:450
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
static ProgramPoint getProgramPoint(const Stmt *S, ProgramPoint::Kind K, const StackFrame *SF, const ProgramPointTag *tag)
ProgramPoint withTag(const ProgramPointTag *tag) const
Create a new ProgramPoint object that is the same as the original except for using the specified tag ...
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition Stmt.h:3170
It represents a stack frame of the call stack.
Stmt - This represents one statement.
Definition Stmt.h:86
StmtClass getStmtClass() const
Definition Stmt.h:1503
The top declaration context.
Definition Decl.h:105
BugReporter is a utility class for generating PathDiagnostics for analysis.
Represents the memory allocation call in a C++ new-expression.
Definition CallEvent.h:1122
Represents an abstract call to a function or method along a particular path.
Definition CallEvent.h:152
CallEventRef< T > cloneWithState(ProgramStateRef NewState) const
Returns a copy of this CallEvent, but using the given state.
Definition CallEvent.h:1479
ProgramPoint getProgramPoint(bool IsPreVisit=false, const ProgramPointTag *Tag=nullptr) const
Returns an appropriate ProgramPoint for this call.
CheckerBackend is an abstract base class that serves as the common ancestor of all the Checker<....
Definition Checker.h:529
StringRef getDebugTag() const override
Attached to nodes created by this checker class when the ExplodedGraph is dumped for debugging.
Definition Checker.cpp:20
A CheckerFrontend instance is what the user recognizes as "one checker": it has a public canonical na...
Definition Checker.h:511
CheckerNameRef getName() const
Definition Checker.h:521
void _registerForLiveSymbols(CheckLiveSymbolsFunc checkfn)
void _registerForEndOfTranslationUnit(CheckEndOfTranslationUnit checkfn)
ProgramStateRef runCheckersForRegionChanges(ProgramStateRef state, const InvalidatedSymbols *invalidated, ArrayRef< const MemRegion * > ExplicitRegions, ArrayRef< const MemRegion * > Regions, const StackFrame *SF, const CallEvent *Call)
Run checkers for region changes.
void _registerForBeginFunction(CheckBeginFunctionFunc checkfn)
void _registerForNewAllocator(CheckNewAllocatorFunc checkfn)
CheckerFn< void(const Decl *, AnalysisManager &, BugReporter &)> CheckDeclFunc
void _registerForPreCall(CheckCallFunc checkfn)
CheckerFn< ProgramStateRef(ProgramStateRef, SVal cond, bool assumption)> EvalAssumeFunc
void _registerForObjCMessageNil(CheckObjCMessageFunc checkfn)
CheckerFn< ProgramStateRef(ProgramStateRef, const InvalidatedSymbols &Escaped, const CallEvent *Call, PointerEscapeKind Kind, RegionAndSymbolInvalidationTraits *ITraits)> CheckPointerEscapeFunc
bool(*)(const Decl *D) HandlesDeclFunc
void runCheckersForObjCMessage(ObjCMessageVisitKind visitKind, ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, const ObjCMethodCall &msg, ExprEngine &Eng, bool wasInlined=false)
Run checkers for visiting obj-c messages.
void runCheckersOnASTDecl(const Decl *D, AnalysisManager &mgr, BugReporter &BR)
Run checkers handling Decls.
void _registerForDecl(CheckDeclFunc checkfn, HandlesDeclFunc isForDeclFn)
CheckerFn< void(const ReturnStmt *, CheckerContext &)> CheckEndFunctionFunc
CheckerFn< void(const Stmt *, CheckerContext &)> CheckBranchConditionFunc
void _registerForPreObjCMessage(CheckObjCMessageFunc checkfn)
void runCheckersOnEndOfTranslationUnit(const TranslationUnitDecl *TU, AnalysisManager &mgr, BugReporter &BR)
Run checkers for the entire Translation Unit.
CheckerFn< bool(const CallEvent &, CheckerContext &)> EvalCallFunc
CheckerFn< void(CheckerContext &)> CheckBeginFunctionFunc
CheckerFn< void(ExplodedGraph &, BugReporter &, ExprEngine &)> CheckEndAnalysisFunc
void _registerForEvalAssume(EvalAssumeFunc checkfn)
void _registerForEndAnalysis(CheckEndAnalysisFunc checkfn)
void _registerForBody(CheckDeclFunc checkfn)
DiagnosticsEngine & getDiagnostics() const
void runCheckersForLocation(ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, SVal location, bool isLoad, const Stmt *NodeEx, const Stmt *BoundEx, ExprEngine &Eng)
Run checkers for load/store of a location.
CheckerFn< void(const Stmt *, CheckerContext &)> CheckStmtFunc
CheckerFn< void(SVal location, SVal val, const Stmt *S, bool AtDeclInit, CheckerContext &)> CheckBindFunc
void runCheckersForBind(ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, SVal location, SVal val, const Stmt *S, bool AtDeclInit, ExprEngine &Eng, const ProgramPoint &PP)
Run checkers for binding of a value to a location.
void reportInvalidCheckerOptionValue(const CheckerFrontend *Checker, StringRef OptionName, StringRef ExpectedValueDesc) const
Emits an error through a DiagnosticsEngine about an invalid user supplied checker option value.
void runCheckersForEndAnalysis(ExplodedGraph &G, BugReporter &BR, ExprEngine &Eng)
Run checkers for end of analysis.
CheckerFn< void(const CXXAllocatorCall &Call, CheckerContext &)> CheckNewAllocatorFunc
void runCheckersForPrintStateJson(raw_ostream &Out, ProgramStateRef State, const char *NL="\n", unsigned int Space=0, bool IsDot=false) const
Run checkers for debug-printing a ProgramState.
void _registerForDeadSymbols(CheckDeadSymbolsFunc checkfn)
void runCheckersForDeadSymbols(ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, SymbolReaper &SymReaper, const Stmt *S, ExprEngine &Eng, ProgramPoint::Kind K)
Run checkers for dead symbols.
void _registerForPostObjCMessage(CheckObjCMessageFunc checkfn)
void _registerForRegionChanges(CheckRegionChangesFunc checkfn)
void runCheckersForEndFunction(ExplodedNodeSet &Dst, ExplodedNode *Pred, ExprEngine &Eng, const ReturnStmt *RS)
Run checkers on end of function.
void _registerForBind(CheckBindFunc checkfn)
void runCheckersForLiveSymbols(ProgramStateRef state, SymbolReaper &SymReaper)
Run checkers for live symbols.
void _registerForPointerEscape(CheckPointerEscapeFunc checkfn)
CheckerFn< void(const TranslationUnitDecl *, AnalysisManager &, BugReporter &)> CheckEndOfTranslationUnit
void _registerForPreStmt(CheckStmtFunc checkfn, HandlesStmtFunc isForStmtFn)
void runCheckersForEvalCall(ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, const CallEvent &CE, ExprEngine &Eng, const EvalCallOptions &CallOpts)
Run checkers for evaluating a call.
void _registerForPostStmt(CheckStmtFunc checkfn, HandlesStmtFunc isForStmtFn)
void runCheckersForBeginFunction(ExplodedNodeSet &Dst, const BlockEdge &L, ExplodedNode *Pred, ExprEngine &Eng)
Run checkers on beginning of function.
void runCheckersForNewAllocator(const CXXAllocatorCall &Call, ExplodedNodeSet &Dst, ExplodedNode *Pred, ExprEngine &Eng, bool wasInlined=false)
Run checkers between C++ operator new and constructor calls.
CheckerFn< void(const CallEvent &, CheckerContext &)> CheckCallFunc
void _registerForBranchCondition(CheckBranchConditionFunc checkfn)
CheckerFn< void(SymbolReaper &, CheckerContext &)> CheckDeadSymbolsFunc
CheckerFn< void(SVal location, bool isLoad, const Stmt *S, CheckerContext &)> CheckLocationFunc
void runCheckersForBlockEntrance(ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, const BlockEntrance &Entrance, ExprEngine &Eng) const
Run checkers after taking a control flow edge.
void runCheckersForStmt(bool isPreVisit, ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, const Stmt *S, ExprEngine &Eng, bool wasInlined=false)
Run checkers for visiting Stmts.
void _registerForEvalCall(EvalCallFunc checkfn)
void _registerForEndFunction(CheckEndFunctionFunc checkfn)
void _registerForBlockEntrance(CheckBlockEntranceFunc checkfn)
CheckerFn< ProgramStateRef( ProgramStateRef, const InvalidatedSymbols *symbols, ArrayRef< const MemRegion * > ExplicitRegions, ArrayRef< const MemRegion * > Regions, const StackFrame *SF, const CallEvent *Call)> CheckRegionChangesFunc
void runCheckersForBranchCondition(const Stmt *condition, ExplodedNodeSet &Dst, ExplodedNode *Pred, ExprEngine &Eng)
Run checkers for branch condition.
CheckerFn< void(const ObjCMethodCall &, CheckerContext &)> CheckObjCMessageFunc
void _registerForLocation(CheckLocationFunc checkfn)
ProgramStateRef runCheckersForPointerEscape(ProgramStateRef State, const InvalidatedSymbols &Escaped, const CallEvent *Call, PointerEscapeKind Kind, RegionAndSymbolInvalidationTraits *ITraits)
Run checkers when pointers escape.
void _registerForConstPointerEscape(CheckPointerEscapeFunc checkfn)
CheckerFn< void(const BlockEntrance &, CheckerContext &)> CheckBlockEntranceFunc
CheckerFn< void(ProgramStateRef, SymbolReaper &)> CheckLiveSymbolsFunc
void runCheckersForCallEvent(bool isPreVisit, ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, const CallEvent &Call, ExprEngine &Eng, bool wasInlined=false)
Run checkers for visiting function calls (including methods, constructors, destructors etc.
bool(*)(const Stmt *D) HandlesStmtFunc
void _registerForPostCall(CheckCallFunc checkfn)
void runCheckersOnASTBody(const Decl *D, AnalysisManager &mgr, BugReporter &BR)
Run checkers handling Decls containing a Stmt body.
ProgramStateRef runCheckersForEvalAssume(ProgramStateRef state, SVal Cond, bool Assumption)
Run checkers for handling assumptions on symbolic values.
Simple checker classes that implement one frontend (i.e.
Definition Checker.h:550
ExplodedNodeSet is a set of ExplodedNode * elements with the invariant that its elements cannot be nu...
void insert(ExplodedNode *N)
const ProgramStateRef & getState() const
const StackFrame * getStackFrame() const
const NodeBuilderContext & getBuilderContext() const
Definition ExprEngine.h:263
void defaultEvalCall(NodeBuilder &B, ExplodedNode *Pred, const CallEvent &Call, const EvalCallOptions &CallOpts={})
Default implementation of call evaluation.
This is the simplest builder which generates nodes in the ExplodedGraph.
Definition CoreEngine.h:265
Represents any expression that calls an Objective-C method.
Definition CallEvent.h:1251
Information about invalidation for a particular region/symbol.
Definition MemRegion.h:1656
SVal - This represents a symbolic expression, which can be either an L-value or an R-value.
Definition SVals.h:56
void dumpToStream(raw_ostream &OS) const
Definition SVals.cpp:293
A class responsible for cleaning up unused symbols.
PointerEscapeKind
Describes the different reasons a pointer escapes during analysis.
@ PSK_DirectEscapeOnCall
The pointer has been passed to a function call directly.
@ PSK_IndirectEscapeOnCall
The pointer has been passed to a function indirectly.
llvm::DenseSet< SymbolRef > InvalidatedSymbols
Definition Store.h:50
IntrusiveRefCntPtr< const ProgramState > ProgramStateRef
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
const Fact * ProgramPoint
A ProgramPoint identifies a location in the CFG by pointing to a specific Fact.
Definition Facts.h:91
The JSON file list parser is used to communicate input to InstallAPI.
Expr * Cond
};
raw_ostream & Indent(raw_ostream &Out, const unsigned int Space, bool IsDot)
Definition JsonSupport.h:21
U cast(CodeGen::Address addr)
Definition Address.h:327
Hints for figuring out if a call should be inlined during evalCall().
Definition ExprEngine.h:93