1 //=== FuchsiaHandleChecker.cpp - Find handle leaks/double closes -*- 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 checker checks if the handle of Fuchsia is properly used according to
10 // following rules.
11 //   - If a handle is acquired, it should be released before execution
12 //        ends.
13 //   - If a handle is released, it should not be released again.
14 //   - If a handle is released, it should not be used for other purposes
15 //        such as I/O.
16 //
17 // In this checker, each tracked handle is associated with a state. When the
18 // handle variable is passed to different function calls or syscalls, its state
19 // changes. The state changes can be generally represented by following ASCII
20 // Art:
21 //
22 //
23 //                              +-+---------v-+         +------------+
24 //       acquire_func succeeded |             | Escape  |            |
25 //            +----------------->  Allocated  +--------->  Escaped   <--+
26 //            |                 |             |         |            |  |
27 //            |                 +-----+------++         +------------+  |
28 //            |                       |      |                          |
29 //            |         release_func  |      +--+                       |
30 //            |                       |         | handle  +--------+    |
31 //            |                       |         | dies    |        |    |
32 //            |                  +----v-----+   +---------> Leaked |    |
33 //            |                  |          |             |(REPORT)|    |
34 // +----------+--+               | Released | Escape      +--------+    |
35 // |             |               |          +---------------------------+
36 // | Not tracked <--+            +----+---+-+
37 // |             |  |                 |   |        As argument by value
38 // +------+------+  |    release_func |   +------+ in function call
39 //        |         |                 |          | or by reference in
40 //        |         |                 |          | use_func call
41 //        +---------+            +----v-----+    |     +-----------+
42 //        acquire_func failed    | Double   |    +-----> Use after |
43 //                               | released |          | released  |
44 //                               | (REPORT) |          | (REPORT)  |
45 //                               +----------+          +-----------+
46 //
47 // acquire_func represents the functions or syscalls that may acquire a handle.
48 // release_func represents the functions or syscalls that may release a handle.
49 // use_func represents the functions or syscall that requires an open handle.
50 //
51 // If a tracked handle dies in "Released" or "Not Tracked" state, we assume it
52 // is properly used. Otherwise a bug and will be reported.
53 //
54 // Note that, the analyzer does not always know for sure if a function failed
55 // or succeeded. In those cases we use the state MaybeAllocated.
56 // Thus, the diagram above captures the intent, not implementation details.
57 //
58 // Due to the fact that the number of handle related syscalls in Fuchsia
59 // is large, we adopt the annotation attributes to descript syscalls'
60 // operations(acquire/release/use) on handles instead of hardcoding
61 // everything in the checker.
62 //
63 // We use following annotation attributes for handle related syscalls or
64 // functions:
65 //  1. __attribute__((acquire_handle("Fuchsia"))) |handle will be acquired
66 //  2. __attribute__((release_handle("Fuchsia"))) |handle will be released
67 //  3. __attribute__((use_handle("Fuchsia"))) |handle will not transit to
68 //     escaped state, it also needs to be open.
69 //
70 // For example, an annotated syscall:
71 //   zx_status_t zx_channel_create(
72 //   uint32_t options,
73 //   zx_handle_t* out0 __attribute__((acquire_handle("Fuchsia"))) ,
74 //   zx_handle_t* out1 __attribute__((acquire_handle("Fuchsia"))));
75 // denotes a syscall which will acquire two handles and save them to 'out0' and
76 // 'out1' when succeeded.
77 //
78 //===----------------------------------------------------------------------===//
79 
80 #include "clang/AST/Attr.h"
81 #include "clang/AST/Decl.h"
82 #include "clang/AST/Type.h"
83 #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
84 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
85 #include "clang/StaticAnalyzer/Core/Checker.h"
86 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
87 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
88 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
89 #include "clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h"
90 #include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
91 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
92 #include "clang/StaticAnalyzer/Core/PathSensitive/SymExpr.h"
93 #include "llvm/ADT/StringExtras.h"
94 
95 using namespace clang;
96 using namespace ento;
97 
98 namespace {
99 
100 static const StringRef HandleTypeName = "zx_handle_t";
101 static const StringRef ErrorTypeName = "zx_status_t";
102 
103 class HandleState {
104 private:
105   enum class Kind { MaybeAllocated, Allocated, Released, Escaped } K;
106   SymbolRef ErrorSym;
107   HandleState(Kind K, SymbolRef ErrorSym) : K(K), ErrorSym(ErrorSym) {}
108 
109 public:
110   bool operator==(const HandleState &Other) const {
111     return K == Other.K && ErrorSym == Other.ErrorSym;
112   }
113   bool isAllocated() const { return K == Kind::Allocated; }
114   bool maybeAllocated() const { return K == Kind::MaybeAllocated; }
115   bool isReleased() const { return K == Kind::Released; }
116   bool isEscaped() const { return K == Kind::Escaped; }
117 
118   static HandleState getMaybeAllocated(SymbolRef ErrorSym) {
119     return HandleState(Kind::MaybeAllocated, ErrorSym);
120   }
121   static HandleState getAllocated(ProgramStateRef State, HandleState S) {
122     assert(S.maybeAllocated());
123     assert(State->getConstraintManager()
124                .isNull(State, S.getErrorSym())
125                .isConstrained());
126     return HandleState(Kind::Allocated, nullptr);
127   }
128   static HandleState getReleased() {
129     return HandleState(Kind::Released, nullptr);
130   }
131   static HandleState getEscaped() {
132     return HandleState(Kind::Escaped, nullptr);
133   }
134 
135   SymbolRef getErrorSym() const { return ErrorSym; }
136 
137   void Profile(llvm::FoldingSetNodeID &ID) const {
138     ID.AddInteger(static_cast<int>(K));
139     ID.AddPointer(ErrorSym);
140   }
141 
142   LLVM_DUMP_METHOD void dump(raw_ostream &OS) const {
143     switch (K) {
144 #define CASE(ID)                                                               \
145   case ID:                                                                     \
146     OS << #ID;                                                                 \
147     break;
148       CASE(Kind::MaybeAllocated)
149       CASE(Kind::Allocated)
150       CASE(Kind::Released)
151       CASE(Kind::Escaped)
152     }
153     if (ErrorSym) {
154       OS << " ErrorSym: ";
155       ErrorSym->dumpToStream(OS);
156     }
157   }
158 
159   LLVM_DUMP_METHOD void dump() const { dump(llvm::errs()); }
160 };
161 
162 template <typename Attr> static bool hasFuchsiaAttr(const Decl *D) {
163   return D->hasAttr<Attr>() && D->getAttr<Attr>()->getHandleType() == "Fuchsia";
164 }
165 
166 class FuchsiaHandleChecker
167     : public Checker<check::PostCall, check::PreCall, check::DeadSymbols,
168                      check::PointerEscape, eval::Assume> {
169   BugType LeakBugType{this, "Fuchsia handle leak", "Fuchsia Handle Error",
170                       /*SuppressOnSink=*/true};
171   BugType DoubleReleaseBugType{this, "Fuchsia handle double release",
172                                "Fuchsia Handle Error"};
173   BugType UseAfterReleaseBugType{this, "Fuchsia handle use after release",
174                                  "Fuchsia Handle Error"};
175 
176 public:
177   void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
178   void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
179   void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
180   ProgramStateRef evalAssume(ProgramStateRef State, SVal Cond,
181                              bool Assumption) const;
182   ProgramStateRef checkPointerEscape(ProgramStateRef State,
183                                      const InvalidatedSymbols &Escaped,
184                                      const CallEvent *Call,
185                                      PointerEscapeKind Kind) const;
186 
187   ExplodedNode *reportLeaks(ArrayRef<SymbolRef> LeakedHandles,
188                             CheckerContext &C, ExplodedNode *Pred) const;
189 
190   void reportDoubleRelease(SymbolRef HandleSym, const SourceRange &Range,
191                            CheckerContext &C) const;
192 
193   void reportUseAfterFree(SymbolRef HandleSym, const SourceRange &Range,
194                           CheckerContext &C) const;
195 
196   void reportBug(SymbolRef Sym, ExplodedNode *ErrorNode, CheckerContext &C,
197                  const SourceRange *Range, const BugType &Type,
198                  StringRef Msg) const;
199 
200   void printState(raw_ostream &Out, ProgramStateRef State, const char *NL,
201                   const char *Sep) const override;
202 };
203 } // end anonymous namespace
204 
205 REGISTER_MAP_WITH_PROGRAMSTATE(HStateMap, SymbolRef, HandleState)
206 
207 static const ExplodedNode *getAcquireSite(const ExplodedNode *N, SymbolRef Sym,
208                                           CheckerContext &Ctx) {
209   ProgramStateRef State = N->getState();
210   // When bug type is handle leak, exploded node N does not have state info for
211   // leaking handle. Get the predecessor of N instead.
212   if (!State->get<HStateMap>(Sym))
213     N = N->getFirstPred();
214 
215   const ExplodedNode *Pred = N;
216   while (N) {
217     State = N->getState();
218     if (!State->get<HStateMap>(Sym)) {
219       const HandleState *HState = Pred->getState()->get<HStateMap>(Sym);
220       if (HState && (HState->isAllocated() || HState->maybeAllocated()))
221         return N;
222     }
223     Pred = N;
224     N = N->getFirstPred();
225   }
226   return nullptr;
227 }
228 
229 namespace {
230 class FuchsiaHandleSymbolVisitor final : public SymbolVisitor {
231 public:
232   FuchsiaHandleSymbolVisitor(ProgramStateRef State) : State(std::move(State)) {}
233   ProgramStateRef getState() const { return State; }
234 
235   bool VisitSymbol(SymbolRef S) override {
236     if (const auto *HandleType = S->getType()->getAs<TypedefType>())
237       if (HandleType->getDecl()->getName() == HandleTypeName)
238         Symbols.push_back(S);
239     return true;
240   }
241 
242   SmallVector<SymbolRef, 1024> GetSymbols() { return Symbols; }
243 
244 private:
245   SmallVector<SymbolRef, 1024> Symbols;
246   ProgramStateRef State;
247 };
248 } // end anonymous namespace
249 
250 /// Returns the symbols extracted from the argument or empty vector if it cannot
251 /// be found. It is unlikely to have over 1024 symbols in one argument.
252 static SmallVector<SymbolRef, 1024>
253 getFuchsiaHandleSymbols(QualType QT, SVal Arg, ProgramStateRef State) {
254   int PtrToHandleLevel = 0;
255   while (QT->isAnyPointerType() || QT->isReferenceType()) {
256     ++PtrToHandleLevel;
257     QT = QT->getPointeeType();
258   }
259   if (QT->isStructureType()) {
260     // If we see a structure, see if there is any handle referenced by the
261     // structure.
262     FuchsiaHandleSymbolVisitor Visitor(State);
263     State->scanReachableSymbols(Arg, Visitor);
264     return Visitor.GetSymbols();
265   }
266   if (const auto *HandleType = QT->getAs<TypedefType>()) {
267     if (HandleType->getDecl()->getName() != HandleTypeName)
268       return {};
269     if (PtrToHandleLevel > 1)
270       // Not supported yet.
271       return {};
272 
273     if (PtrToHandleLevel == 0) {
274       SymbolRef Sym = Arg.getAsSymbol();
275       if (Sym) {
276         return {Sym};
277       } else {
278         return {};
279       }
280     } else {
281       assert(PtrToHandleLevel == 1);
282       if (Optional<Loc> ArgLoc = Arg.getAs<Loc>()) {
283         SymbolRef Sym = State->getSVal(*ArgLoc).getAsSymbol();
284         if (Sym) {
285           return {Sym};
286         } else {
287           return {};
288         }
289       }
290     }
291   }
292   return {};
293 }
294 
295 void FuchsiaHandleChecker::checkPreCall(const CallEvent &Call,
296                                         CheckerContext &C) const {
297   ProgramStateRef State = C.getState();
298   const FunctionDecl *FuncDecl = dyn_cast_or_null<FunctionDecl>(Call.getDecl());
299   if (!FuncDecl) {
300     // Unknown call, escape by value handles. They are not covered by
301     // PointerEscape callback.
302     for (unsigned Arg = 0; Arg < Call.getNumArgs(); ++Arg) {
303       if (SymbolRef Handle = Call.getArgSVal(Arg).getAsSymbol())
304         State = State->set<HStateMap>(Handle, HandleState::getEscaped());
305     }
306     C.addTransition(State);
307     return;
308   }
309 
310   for (unsigned Arg = 0; Arg < Call.getNumArgs(); ++Arg) {
311     if (Arg >= FuncDecl->getNumParams())
312       break;
313     const ParmVarDecl *PVD = FuncDecl->getParamDecl(Arg);
314     SmallVector<SymbolRef, 1024> Handles =
315         getFuchsiaHandleSymbols(PVD->getType(), Call.getArgSVal(Arg), State);
316 
317     // Handled in checkPostCall.
318     if (hasFuchsiaAttr<ReleaseHandleAttr>(PVD) ||
319         hasFuchsiaAttr<AcquireHandleAttr>(PVD))
320       continue;
321 
322     for (SymbolRef Handle : Handles) {
323       const HandleState *HState = State->get<HStateMap>(Handle);
324       if (!HState || HState->isEscaped())
325         continue;
326 
327       if (hasFuchsiaAttr<UseHandleAttr>(PVD) ||
328           PVD->getType()->isIntegerType()) {
329         if (HState->isReleased()) {
330           reportUseAfterFree(Handle, Call.getArgSourceRange(Arg), C);
331           return;
332         }
333       }
334       if (!hasFuchsiaAttr<UseHandleAttr>(PVD) &&
335           PVD->getType()->isIntegerType()) {
336         // Working around integer by-value escapes.
337         State = State->set<HStateMap>(Handle, HandleState::getEscaped());
338       }
339     }
340   }
341   C.addTransition(State);
342 }
343 
344 void FuchsiaHandleChecker::checkPostCall(const CallEvent &Call,
345                                          CheckerContext &C) const {
346   const FunctionDecl *FuncDecl = dyn_cast_or_null<FunctionDecl>(Call.getDecl());
347   if (!FuncDecl)
348     return;
349 
350   ProgramStateRef State = C.getState();
351 
352   std::vector<std::function<std::string(BugReport & BR)>> Notes;
353   SymbolRef ResultSymbol = nullptr;
354   if (const auto *TypeDefTy = FuncDecl->getReturnType()->getAs<TypedefType>())
355     if (TypeDefTy->getDecl()->getName() == ErrorTypeName)
356       ResultSymbol = Call.getReturnValue().getAsSymbol();
357 
358   // Function returns an open handle.
359   if (hasFuchsiaAttr<AcquireHandleAttr>(FuncDecl)) {
360     SymbolRef RetSym = Call.getReturnValue().getAsSymbol();
361     Notes.push_back([RetSym, FuncDecl](BugReport &BR) -> std::string {
362       auto *PathBR = static_cast<PathSensitiveBugReport *>(&BR);
363       if (auto IsInteresting = PathBR->getInterestingnessKind(RetSym)) {
364         std::string SBuf;
365         llvm::raw_string_ostream OS(SBuf);
366         OS << "Function '" << FuncDecl->getDeclName()
367            << "' returns an open handle";
368         return OS.str();
369       } else
370         return "";
371     });
372     State =
373         State->set<HStateMap>(RetSym, HandleState::getMaybeAllocated(nullptr));
374   }
375 
376   for (unsigned Arg = 0; Arg < Call.getNumArgs(); ++Arg) {
377     if (Arg >= FuncDecl->getNumParams())
378       break;
379     const ParmVarDecl *PVD = FuncDecl->getParamDecl(Arg);
380     unsigned ParamDiagIdx = PVD->getFunctionScopeIndex() + 1;
381     SmallVector<SymbolRef, 1024> Handles =
382         getFuchsiaHandleSymbols(PVD->getType(), Call.getArgSVal(Arg), State);
383 
384     for (SymbolRef Handle : Handles) {
385       const HandleState *HState = State->get<HStateMap>(Handle);
386       if (HState && HState->isEscaped())
387         continue;
388       if (hasFuchsiaAttr<ReleaseHandleAttr>(PVD)) {
389         if (HState && HState->isReleased()) {
390           reportDoubleRelease(Handle, Call.getArgSourceRange(Arg), C);
391           return;
392         } else {
393           Notes.push_back([Handle, ParamDiagIdx](BugReport &BR) -> std::string {
394             auto *PathBR = static_cast<PathSensitiveBugReport *>(&BR);
395             if (auto IsInteresting = PathBR->getInterestingnessKind(Handle)) {
396               std::string SBuf;
397               llvm::raw_string_ostream OS(SBuf);
398               OS << "Handle released through " << ParamDiagIdx
399                  << llvm::getOrdinalSuffix(ParamDiagIdx) << " parameter";
400               return OS.str();
401             } else
402               return "";
403           });
404           State = State->set<HStateMap>(Handle, HandleState::getReleased());
405         }
406       } else if (hasFuchsiaAttr<AcquireHandleAttr>(PVD)) {
407         Notes.push_back([Handle, ParamDiagIdx](BugReport &BR) -> std::string {
408           auto *PathBR = static_cast<PathSensitiveBugReport *>(&BR);
409           if (auto IsInteresting = PathBR->getInterestingnessKind(Handle)) {
410             std::string SBuf;
411             llvm::raw_string_ostream OS(SBuf);
412             OS << "Handle allocated through " << ParamDiagIdx
413                << llvm::getOrdinalSuffix(ParamDiagIdx) << " parameter";
414             return OS.str();
415           } else
416             return "";
417         });
418         State = State->set<HStateMap>(
419             Handle, HandleState::getMaybeAllocated(ResultSymbol));
420       }
421     }
422   }
423   const NoteTag *T = nullptr;
424   if (!Notes.empty()) {
425     T = C.getNoteTag([this, Notes{std::move(Notes)}](
426                          PathSensitiveBugReport &BR) -> std::string {
427       if (&BR.getBugType() != &UseAfterReleaseBugType &&
428           &BR.getBugType() != &LeakBugType &&
429           &BR.getBugType() != &DoubleReleaseBugType)
430         return "";
431       for (auto &Note : Notes) {
432         std::string Text = Note(BR);
433         if (!Text.empty())
434           return Text;
435       }
436       return "";
437     });
438   }
439   C.addTransition(State, T);
440 }
441 
442 void FuchsiaHandleChecker::checkDeadSymbols(SymbolReaper &SymReaper,
443                                             CheckerContext &C) const {
444   ProgramStateRef State = C.getState();
445   SmallVector<SymbolRef, 2> LeakedSyms;
446   HStateMapTy TrackedHandles = State->get<HStateMap>();
447   for (auto &CurItem : TrackedHandles) {
448     SymbolRef ErrorSym = CurItem.second.getErrorSym();
449     // Keeping zombie handle symbols. In case the error symbol is dying later
450     // than the handle symbol we might produce spurious leak warnings (in case
451     // we find out later from the status code that the handle allocation failed
452     // in the first place).
453     if (!SymReaper.isDead(CurItem.first) ||
454         (ErrorSym && !SymReaper.isDead(ErrorSym)))
455       continue;
456     if (CurItem.second.isAllocated() || CurItem.second.maybeAllocated())
457       LeakedSyms.push_back(CurItem.first);
458     State = State->remove<HStateMap>(CurItem.first);
459   }
460 
461   ExplodedNode *N = C.getPredecessor();
462   if (!LeakedSyms.empty())
463     N = reportLeaks(LeakedSyms, C, N);
464 
465   C.addTransition(State, N);
466 }
467 
468 // Acquiring a handle is not always successful. In Fuchsia most functions
469 // return a status code that determines the status of the handle.
470 // When we split the path based on this status code we know that on one
471 // path we do have the handle and on the other path the acquire failed.
472 // This method helps avoiding false positive leak warnings on paths where
473 // the function failed.
474 // Moreover, when a handle is known to be zero (the invalid handle),
475 // we no longer can follow the symbol on the path, becaue the constant
476 // zero will be used instead of the symbol. We also do not need to release
477 // an invalid handle, so we remove the corresponding symbol from the state.
478 ProgramStateRef FuchsiaHandleChecker::evalAssume(ProgramStateRef State,
479                                                  SVal Cond,
480                                                  bool Assumption) const {
481   // TODO: add notes about successes/fails for APIs.
482   ConstraintManager &Cmr = State->getConstraintManager();
483   HStateMapTy TrackedHandles = State->get<HStateMap>();
484   for (auto &CurItem : TrackedHandles) {
485     ConditionTruthVal HandleVal = Cmr.isNull(State, CurItem.first);
486     if (HandleVal.isConstrainedTrue()) {
487       // The handle is invalid. We can no longer follow the symbol on this path.
488       State = State->remove<HStateMap>(CurItem.first);
489     }
490     SymbolRef ErrorSym = CurItem.second.getErrorSym();
491     if (!ErrorSym)
492       continue;
493     ConditionTruthVal ErrorVal = Cmr.isNull(State, ErrorSym);
494     if (ErrorVal.isConstrainedTrue()) {
495       // Allocation succeeded.
496       if (CurItem.second.maybeAllocated())
497         State = State->set<HStateMap>(
498             CurItem.first, HandleState::getAllocated(State, CurItem.second));
499     } else if (ErrorVal.isConstrainedFalse()) {
500       // Allocation failed.
501       if (CurItem.second.maybeAllocated())
502         State = State->remove<HStateMap>(CurItem.first);
503     }
504   }
505   return State;
506 }
507 
508 ProgramStateRef FuchsiaHandleChecker::checkPointerEscape(
509     ProgramStateRef State, const InvalidatedSymbols &Escaped,
510     const CallEvent *Call, PointerEscapeKind Kind) const {
511   const FunctionDecl *FuncDecl =
512       Call ? dyn_cast_or_null<FunctionDecl>(Call->getDecl()) : nullptr;
513 
514   llvm::DenseSet<SymbolRef> UnEscaped;
515   // Not all calls should escape our symbols.
516   if (FuncDecl &&
517       (Kind == PSK_DirectEscapeOnCall || Kind == PSK_IndirectEscapeOnCall ||
518        Kind == PSK_EscapeOutParameters)) {
519     for (unsigned Arg = 0; Arg < Call->getNumArgs(); ++Arg) {
520       if (Arg >= FuncDecl->getNumParams())
521         break;
522       const ParmVarDecl *PVD = FuncDecl->getParamDecl(Arg);
523       SmallVector<SymbolRef, 1024> Handles =
524           getFuchsiaHandleSymbols(PVD->getType(), Call->getArgSVal(Arg), State);
525       for (SymbolRef Handle : Handles) {
526         if (hasFuchsiaAttr<UseHandleAttr>(PVD) ||
527             hasFuchsiaAttr<ReleaseHandleAttr>(PVD)) {
528           UnEscaped.insert(Handle);
529         }
530       }
531     }
532   }
533 
534   // For out params, we have to deal with derived symbols. See
535   // MacOSKeychainAPIChecker for details.
536   for (auto I : State->get<HStateMap>()) {
537     if (Escaped.count(I.first) && !UnEscaped.count(I.first))
538       State = State->set<HStateMap>(I.first, HandleState::getEscaped());
539     if (const auto *SD = dyn_cast<SymbolDerived>(I.first)) {
540       auto ParentSym = SD->getParentSymbol();
541       if (Escaped.count(ParentSym))
542         State = State->set<HStateMap>(I.first, HandleState::getEscaped());
543     }
544   }
545 
546   return State;
547 }
548 
549 ExplodedNode *
550 FuchsiaHandleChecker::reportLeaks(ArrayRef<SymbolRef> LeakedHandles,
551                                   CheckerContext &C, ExplodedNode *Pred) const {
552   ExplodedNode *ErrNode = C.generateNonFatalErrorNode(C.getState(), Pred);
553   for (SymbolRef LeakedHandle : LeakedHandles) {
554     reportBug(LeakedHandle, ErrNode, C, nullptr, LeakBugType,
555               "Potential leak of handle");
556   }
557   return ErrNode;
558 }
559 
560 void FuchsiaHandleChecker::reportDoubleRelease(SymbolRef HandleSym,
561                                                const SourceRange &Range,
562                                                CheckerContext &C) const {
563   ExplodedNode *ErrNode = C.generateErrorNode(C.getState());
564   reportBug(HandleSym, ErrNode, C, &Range, DoubleReleaseBugType,
565             "Releasing a previously released handle");
566 }
567 
568 void FuchsiaHandleChecker::reportUseAfterFree(SymbolRef HandleSym,
569                                               const SourceRange &Range,
570                                               CheckerContext &C) const {
571   ExplodedNode *ErrNode = C.generateErrorNode(C.getState());
572   reportBug(HandleSym, ErrNode, C, &Range, UseAfterReleaseBugType,
573             "Using a previously released handle");
574 }
575 
576 void FuchsiaHandleChecker::reportBug(SymbolRef Sym, ExplodedNode *ErrorNode,
577                                      CheckerContext &C,
578                                      const SourceRange *Range,
579                                      const BugType &Type, StringRef Msg) const {
580   if (!ErrorNode)
581     return;
582 
583   std::unique_ptr<PathSensitiveBugReport> R;
584   if (Type.isSuppressOnSink()) {
585     const ExplodedNode *AcquireNode = getAcquireSite(ErrorNode, Sym, C);
586     if (AcquireNode) {
587       PathDiagnosticLocation LocUsedForUniqueing =
588           PathDiagnosticLocation::createBegin(
589               AcquireNode->getStmtForDiagnostics(), C.getSourceManager(),
590               AcquireNode->getLocationContext());
591 
592       R = std::make_unique<PathSensitiveBugReport>(
593           Type, Msg, ErrorNode, LocUsedForUniqueing,
594           AcquireNode->getLocationContext()->getDecl());
595     }
596   }
597   if (!R)
598     R = std::make_unique<PathSensitiveBugReport>(Type, Msg, ErrorNode);
599   if (Range)
600     R->addRange(*Range);
601   R->markInteresting(Sym);
602   C.emitReport(std::move(R));
603 }
604 
605 void ento::registerFuchsiaHandleChecker(CheckerManager &mgr) {
606   mgr.registerChecker<FuchsiaHandleChecker>();
607 }
608 
609 bool ento::shouldRegisterFuchsiaHandleChecker(const CheckerManager &mgr) {
610   return true;
611 }
612 
613 void FuchsiaHandleChecker::printState(raw_ostream &Out, ProgramStateRef State,
614                                       const char *NL, const char *Sep) const {
615 
616   HStateMapTy StateMap = State->get<HStateMap>();
617 
618   if (!StateMap.isEmpty()) {
619     Out << Sep << "FuchsiaHandleChecker :" << NL;
620     for (HStateMapTy::iterator I = StateMap.begin(), E = StateMap.end(); I != E;
621          ++I) {
622       I.getKey()->dumpToStream(Out);
623       Out << " : ";
624       I.getData().dump(Out);
625       Out << NL;
626     }
627   }
628 }
629