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 diagramm 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 
94 using namespace clang;
95 using namespace ento;
96 
97 namespace {
98 
99 static const StringRef HandleTypeName = "zx_handle_t";
100 static const StringRef ErrorTypeName = "zx_status_t";
101 
102 class HandleState {
103 private:
104   enum class Kind { MaybeAllocated, Allocated, Released, Escaped } K;
105   SymbolRef ErrorSym;
106   HandleState(Kind K, SymbolRef ErrorSym) : K(K), ErrorSym(ErrorSym) {}
107 
108 public:
109   bool operator==(const HandleState &Other) const {
110     return K == Other.K && ErrorSym == Other.ErrorSym;
111   }
112   bool isAllocated() const { return K == Kind::Allocated; }
113   bool maybeAllocated() const { return K == Kind::MaybeAllocated; }
114   bool isReleased() const { return K == Kind::Released; }
115   bool isEscaped() const { return K == Kind::Escaped; }
116 
117   static HandleState getMaybeAllocated(SymbolRef ErrorSym) {
118     return HandleState(Kind::MaybeAllocated, ErrorSym);
119   }
120   static HandleState getAllocated(ProgramStateRef State, HandleState S) {
121     assert(S.maybeAllocated());
122     assert(State->getConstraintManager()
123                .isNull(State, S.getErrorSym())
124                .isConstrained());
125     return HandleState(Kind::Allocated, nullptr);
126   }
127   static HandleState getReleased() {
128     return HandleState(Kind::Released, nullptr);
129   }
130   static HandleState getEscaped() {
131     return HandleState(Kind::Escaped, nullptr);
132   }
133 
134   SymbolRef getErrorSym() const { return ErrorSym; }
135 
136   void Profile(llvm::FoldingSetNodeID &ID) const {
137     ID.AddInteger(static_cast<int>(K));
138     ID.AddPointer(ErrorSym);
139   }
140 
141   LLVM_DUMP_METHOD void dump(raw_ostream &OS) const {
142     switch (K) {
143 #define CASE(ID)                                                               \
144   case ID:                                                                     \
145     OS << #ID;                                                                 \
146     break;
147       CASE(Kind::MaybeAllocated)
148       CASE(Kind::Allocated)
149       CASE(Kind::Released)
150       CASE(Kind::Escaped)
151     }
152     if (ErrorSym) {
153       OS << " ErrorSym: ";
154       ErrorSym->dumpToStream(OS);
155     }
156   }
157 
158   LLVM_DUMP_METHOD void dump() const { dump(llvm::errs()); }
159 };
160 
161 template <typename Attr> static bool hasFuchsiaAttr(const Decl *D) {
162   return D->hasAttr<Attr>() && D->getAttr<Attr>()->getHandleType() == "Fuchsia";
163 }
164 
165 class FuchsiaHandleChecker
166     : public Checker<check::PostCall, check::PreCall, check::DeadSymbols,
167                      check::PointerEscape, eval::Assume> {
168   BugType LeakBugType{this, "Fuchsia handle leak", "Fuchsia Handle Error",
169                       /*SuppressOnSink=*/true};
170   BugType DoubleReleaseBugType{this, "Fuchsia handle double release",
171                                "Fuchsia Handle Error"};
172   BugType UseAfterReleaseBugType{this, "Fuchsia handle use after release",
173                                  "Fuchsia Handle Error"};
174 
175 public:
176   void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
177   void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
178   void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
179   ProgramStateRef evalAssume(ProgramStateRef State, SVal Cond,
180                              bool Assumption) const;
181   ProgramStateRef checkPointerEscape(ProgramStateRef State,
182                                      const InvalidatedSymbols &Escaped,
183                                      const CallEvent *Call,
184                                      PointerEscapeKind Kind) const;
185 
186   ExplodedNode *reportLeaks(ArrayRef<SymbolRef> LeakedHandles,
187                             CheckerContext &C, ExplodedNode *Pred) const;
188 
189   void reportDoubleRelease(SymbolRef HandleSym, const SourceRange &Range,
190                            CheckerContext &C) const;
191 
192   void reportUseAfterFree(SymbolRef HandleSym, const SourceRange &Range,
193                           CheckerContext &C) const;
194 
195   void reportBug(SymbolRef Sym, ExplodedNode *ErrorNode, CheckerContext &C,
196                  const SourceRange *Range, const BugType &Type,
197                  StringRef Msg) const;
198 
199   void printState(raw_ostream &Out, ProgramStateRef State, const char *NL,
200                   const char *Sep) const override;
201 };
202 } // end anonymous namespace
203 
204 REGISTER_MAP_WITH_PROGRAMSTATE(HStateMap, SymbolRef, HandleState)
205 
206 static const ExplodedNode *getAcquireSite(const ExplodedNode *N, SymbolRef Sym,
207                                           CheckerContext &Ctx) {
208   ProgramStateRef State = N->getState();
209   // When bug type is handle leak, exploded node N does not have state info for
210   // leaking handle. Get the predecessor of N instead.
211   if (!State->get<HStateMap>(Sym))
212     N = N->getFirstPred();
213 
214   const ExplodedNode *Pred = N;
215   while (N) {
216     State = N->getState();
217     if (!State->get<HStateMap>(Sym)) {
218       const HandleState *HState = Pred->getState()->get<HStateMap>(Sym);
219       if (HState && (HState->isAllocated() || HState->maybeAllocated()))
220         return N;
221     }
222     Pred = N;
223     N = N->getFirstPred();
224   }
225   return nullptr;
226 }
227 
228 /// Returns the symbols extracted from the argument or null if it cannot be
229 /// found.
230 static SymbolRef getFuchsiaHandleSymbol(QualType QT, SVal Arg,
231                                         ProgramStateRef State) {
232   int PtrToHandleLevel = 0;
233   while (QT->isAnyPointerType() || QT->isReferenceType()) {
234     ++PtrToHandleLevel;
235     QT = QT->getPointeeType();
236   }
237   if (const auto *HandleType = QT->getAs<TypedefType>()) {
238     if (HandleType->getDecl()->getName() != HandleTypeName)
239       return nullptr;
240     if (PtrToHandleLevel > 1) {
241       // Not supported yet.
242       return nullptr;
243     }
244 
245     if (PtrToHandleLevel == 0) {
246       return Arg.getAsSymbol();
247     } else {
248       assert(PtrToHandleLevel == 1);
249       if (Optional<Loc> ArgLoc = Arg.getAs<Loc>())
250         return State->getSVal(*ArgLoc).getAsSymbol();
251     }
252   }
253   return nullptr;
254 }
255 
256 void FuchsiaHandleChecker::checkPreCall(const CallEvent &Call,
257                                         CheckerContext &C) const {
258   ProgramStateRef State = C.getState();
259   const FunctionDecl *FuncDecl = dyn_cast_or_null<FunctionDecl>(Call.getDecl());
260   if (!FuncDecl) {
261     // Unknown call, escape by value handles. They are not covered by
262     // PointerEscape callback.
263     for (unsigned Arg = 0; Arg < Call.getNumArgs(); ++Arg) {
264       if (SymbolRef Handle = Call.getArgSVal(Arg).getAsSymbol())
265         State = State->set<HStateMap>(Handle, HandleState::getEscaped());
266     }
267     C.addTransition(State);
268     return;
269   }
270 
271   for (unsigned Arg = 0; Arg < Call.getNumArgs(); ++Arg) {
272     if (Arg >= FuncDecl->getNumParams())
273       break;
274     const ParmVarDecl *PVD = FuncDecl->getParamDecl(Arg);
275     SymbolRef Handle =
276         getFuchsiaHandleSymbol(PVD->getType(), Call.getArgSVal(Arg), State);
277     if (!Handle)
278       continue;
279 
280     // Handled in checkPostCall.
281     if (hasFuchsiaAttr<ReleaseHandleAttr>(PVD) ||
282         hasFuchsiaAttr<AcquireHandleAttr>(PVD))
283       continue;
284 
285     const HandleState *HState = State->get<HStateMap>(Handle);
286     if (!HState || HState->isEscaped())
287       continue;
288 
289     if (hasFuchsiaAttr<UseHandleAttr>(PVD) || PVD->getType()->isIntegerType()) {
290       if (HState->isReleased()) {
291         reportUseAfterFree(Handle, Call.getArgSourceRange(Arg), C);
292         return;
293       }
294     }
295     if (!hasFuchsiaAttr<UseHandleAttr>(PVD) &&
296         PVD->getType()->isIntegerType()) {
297       // Working around integer by-value escapes.
298       State = State->set<HStateMap>(Handle, HandleState::getEscaped());
299     }
300   }
301   C.addTransition(State);
302 }
303 
304 void FuchsiaHandleChecker::checkPostCall(const CallEvent &Call,
305                                          CheckerContext &C) const {
306   const FunctionDecl *FuncDecl = dyn_cast_or_null<FunctionDecl>(Call.getDecl());
307   if (!FuncDecl)
308     return;
309 
310   ProgramStateRef State = C.getState();
311 
312   std::vector<std::function<std::string(BugReport & BR)>> Notes;
313   SymbolRef ResultSymbol = nullptr;
314   if (const auto *TypeDefTy = FuncDecl->getReturnType()->getAs<TypedefType>())
315     if (TypeDefTy->getDecl()->getName() == ErrorTypeName)
316       ResultSymbol = Call.getReturnValue().getAsSymbol();
317 
318   // Function returns an open handle.
319   if (hasFuchsiaAttr<AcquireHandleAttr>(FuncDecl)) {
320     SymbolRef RetSym = Call.getReturnValue().getAsSymbol();
321     Notes.push_back([RetSym, FuncDecl](BugReport &BR) -> std::string {
322       auto *PathBR = static_cast<PathSensitiveBugReport *>(&BR);
323       if (auto IsInteresting = PathBR->getInterestingnessKind(RetSym)) {
324         std::string SBuf;
325         llvm::raw_string_ostream OS(SBuf);
326         OS << "Function '" << FuncDecl->getNameAsString()
327            << "' returns an open handle";
328         return OS.str();
329       } else
330         return "";
331     });
332     State =
333         State->set<HStateMap>(RetSym, HandleState::getMaybeAllocated(nullptr));
334   }
335 
336   for (unsigned Arg = 0; Arg < Call.getNumArgs(); ++Arg) {
337     if (Arg >= FuncDecl->getNumParams())
338       break;
339     const ParmVarDecl *PVD = FuncDecl->getParamDecl(Arg);
340     unsigned ParamDiagIdx = PVD->getFunctionScopeIndex() + 1;
341     SymbolRef Handle =
342         getFuchsiaHandleSymbol(PVD->getType(), Call.getArgSVal(Arg), State);
343     if (!Handle)
344       continue;
345 
346     const HandleState *HState = State->get<HStateMap>(Handle);
347     if (HState && HState->isEscaped())
348       continue;
349     if (hasFuchsiaAttr<ReleaseHandleAttr>(PVD)) {
350       if (HState && HState->isReleased()) {
351         reportDoubleRelease(Handle, Call.getArgSourceRange(Arg), C);
352         return;
353       } else {
354         Notes.push_back([Handle, ParamDiagIdx](BugReport &BR) -> std::string {
355           auto *PathBR = static_cast<PathSensitiveBugReport *>(&BR);
356           if (auto IsInteresting = PathBR->getInterestingnessKind(Handle)) {
357             std::string SBuf;
358             llvm::raw_string_ostream OS(SBuf);
359             OS << "Handle released through " << ParamDiagIdx
360                << llvm::getOrdinalSuffix(ParamDiagIdx) << " parameter";
361             return OS.str();
362           } else
363             return "";
364         });
365         State = State->set<HStateMap>(Handle, HandleState::getReleased());
366       }
367     } else if (hasFuchsiaAttr<AcquireHandleAttr>(PVD)) {
368       Notes.push_back([Handle, ParamDiagIdx](BugReport &BR) -> std::string {
369         auto *PathBR = static_cast<PathSensitiveBugReport *>(&BR);
370         if (auto IsInteresting = PathBR->getInterestingnessKind(Handle)) {
371           std::string SBuf;
372           llvm::raw_string_ostream OS(SBuf);
373           OS << "Handle allocated through " << ParamDiagIdx
374              << llvm::getOrdinalSuffix(ParamDiagIdx) << " parameter";
375           return OS.str();
376         } else
377           return "";
378       });
379       State = State->set<HStateMap>(
380           Handle, HandleState::getMaybeAllocated(ResultSymbol));
381     }
382   }
383   const NoteTag *T = nullptr;
384   if (!Notes.empty()) {
385     T = C.getNoteTag(
386         [this, Notes{std::move(Notes)}](BugReport &BR) -> std::string {
387           if (&BR.getBugType() != &UseAfterReleaseBugType &&
388               &BR.getBugType() != &LeakBugType &&
389               &BR.getBugType() != &DoubleReleaseBugType)
390             return "";
391           for (auto &Note : Notes) {
392             std::string Text = Note(BR);
393             if (!Text.empty())
394               return Text;
395           }
396           return "";
397         });
398   }
399   C.addTransition(State, T);
400 }
401 
402 void FuchsiaHandleChecker::checkDeadSymbols(SymbolReaper &SymReaper,
403                                             CheckerContext &C) const {
404   ProgramStateRef State = C.getState();
405   SmallVector<SymbolRef, 2> LeakedSyms;
406   HStateMapTy TrackedHandles = State->get<HStateMap>();
407   for (auto &CurItem : TrackedHandles) {
408     SymbolRef ErrorSym = CurItem.second.getErrorSym();
409     // Keeping zombie handle symbols. In case the error symbol is dying later
410     // than the handle symbol we might produce spurious leak warnings (in case
411     // we find out later from the status code that the handle allocation failed
412     // in the first place).
413     if (!SymReaper.isDead(CurItem.first) ||
414         (ErrorSym && !SymReaper.isDead(ErrorSym)))
415       continue;
416     if (CurItem.second.isAllocated() || CurItem.second.maybeAllocated())
417       LeakedSyms.push_back(CurItem.first);
418     State = State->remove<HStateMap>(CurItem.first);
419   }
420 
421   ExplodedNode *N = C.getPredecessor();
422   if (!LeakedSyms.empty())
423     N = reportLeaks(LeakedSyms, C, N);
424 
425   C.addTransition(State, N);
426 }
427 
428 // Acquiring a handle is not always successful. In Fuchsia most functions
429 // return a status code that determines the status of the handle.
430 // When we split the path based on this status code we know that on one
431 // path we do have the handle and on the other path the acquire failed.
432 // This method helps avoiding false positive leak warnings on paths where
433 // the function failed.
434 // Moreover, when a handle is known to be zero (the invalid handle),
435 // we no longer can follow the symbol on the path, becaue the constant
436 // zero will be used instead of the symbol. We also do not need to release
437 // an invalid handle, so we remove the corresponding symbol from the state.
438 ProgramStateRef FuchsiaHandleChecker::evalAssume(ProgramStateRef State,
439                                                  SVal Cond,
440                                                  bool Assumption) const {
441   // TODO: add notes about successes/fails for APIs.
442   ConstraintManager &Cmr = State->getConstraintManager();
443   HStateMapTy TrackedHandles = State->get<HStateMap>();
444   for (auto &CurItem : TrackedHandles) {
445     ConditionTruthVal HandleVal = Cmr.isNull(State, CurItem.first);
446     if (HandleVal.isConstrainedTrue()) {
447       // The handle is invalid. We can no longer follow the symbol on this path.
448       State = State->remove<HStateMap>(CurItem.first);
449     }
450     SymbolRef ErrorSym = CurItem.second.getErrorSym();
451     if (!ErrorSym)
452       continue;
453     ConditionTruthVal ErrorVal = Cmr.isNull(State, ErrorSym);
454     if (ErrorVal.isConstrainedTrue()) {
455       // Allocation succeeded.
456       if (CurItem.second.maybeAllocated())
457         State = State->set<HStateMap>(
458             CurItem.first, HandleState::getAllocated(State, CurItem.second));
459     } else if (ErrorVal.isConstrainedFalse()) {
460       // Allocation failed.
461       if (CurItem.second.maybeAllocated())
462         State = State->remove<HStateMap>(CurItem.first);
463     }
464   }
465   return State;
466 }
467 
468 ProgramStateRef FuchsiaHandleChecker::checkPointerEscape(
469     ProgramStateRef State, const InvalidatedSymbols &Escaped,
470     const CallEvent *Call, PointerEscapeKind Kind) const {
471   const FunctionDecl *FuncDecl =
472       Call ? dyn_cast_or_null<FunctionDecl>(Call->getDecl()) : nullptr;
473 
474   llvm::DenseSet<SymbolRef> UnEscaped;
475   // Not all calls should escape our symbols.
476   if (FuncDecl &&
477       (Kind == PSK_DirectEscapeOnCall || Kind == PSK_IndirectEscapeOnCall ||
478        Kind == PSK_EscapeOutParameters)) {
479     for (unsigned Arg = 0; Arg < Call->getNumArgs(); ++Arg) {
480       if (Arg >= FuncDecl->getNumParams())
481         break;
482       const ParmVarDecl *PVD = FuncDecl->getParamDecl(Arg);
483       SymbolRef Handle =
484           getFuchsiaHandleSymbol(PVD->getType(), Call->getArgSVal(Arg), State);
485       if (!Handle)
486         continue;
487       if (hasFuchsiaAttr<UseHandleAttr>(PVD) ||
488           hasFuchsiaAttr<ReleaseHandleAttr>(PVD))
489         UnEscaped.insert(Handle);
490     }
491   }
492 
493   // For out params, we have to deal with derived symbols. See
494   // MacOSKeychainAPIChecker for details.
495   for (auto I : State->get<HStateMap>()) {
496     if (Escaped.count(I.first) && !UnEscaped.count(I.first))
497       State = State->set<HStateMap>(I.first, HandleState::getEscaped());
498     if (const auto *SD = dyn_cast<SymbolDerived>(I.first)) {
499       auto ParentSym = SD->getParentSymbol();
500       if (Escaped.count(ParentSym))
501         State = State->set<HStateMap>(I.first, HandleState::getEscaped());
502     }
503   }
504 
505   return State;
506 }
507 
508 ExplodedNode *
509 FuchsiaHandleChecker::reportLeaks(ArrayRef<SymbolRef> LeakedHandles,
510                                   CheckerContext &C, ExplodedNode *Pred) const {
511   ExplodedNode *ErrNode = C.generateNonFatalErrorNode(C.getState(), Pred);
512   for (SymbolRef LeakedHandle : LeakedHandles) {
513     reportBug(LeakedHandle, ErrNode, C, nullptr, LeakBugType,
514               "Potential leak of handle");
515   }
516   return ErrNode;
517 }
518 
519 void FuchsiaHandleChecker::reportDoubleRelease(SymbolRef HandleSym,
520                                                const SourceRange &Range,
521                                                CheckerContext &C) const {
522   ExplodedNode *ErrNode = C.generateErrorNode(C.getState());
523   reportBug(HandleSym, ErrNode, C, &Range, DoubleReleaseBugType,
524             "Releasing a previously released handle");
525 }
526 
527 void FuchsiaHandleChecker::reportUseAfterFree(SymbolRef HandleSym,
528                                               const SourceRange &Range,
529                                               CheckerContext &C) const {
530   ExplodedNode *ErrNode = C.generateErrorNode(C.getState());
531   reportBug(HandleSym, ErrNode, C, &Range, UseAfterReleaseBugType,
532             "Using a previously released handle");
533 }
534 
535 void FuchsiaHandleChecker::reportBug(SymbolRef Sym, ExplodedNode *ErrorNode,
536                                      CheckerContext &C,
537                                      const SourceRange *Range,
538                                      const BugType &Type, StringRef Msg) const {
539   if (!ErrorNode)
540     return;
541 
542   std::unique_ptr<PathSensitiveBugReport> R;
543   if (Type.isSuppressOnSink()) {
544     const ExplodedNode *AcquireNode = getAcquireSite(ErrorNode, Sym, C);
545     if (AcquireNode) {
546       PathDiagnosticLocation LocUsedForUniqueing =
547           PathDiagnosticLocation::createBegin(
548               AcquireNode->getStmtForDiagnostics(), C.getSourceManager(),
549               AcquireNode->getLocationContext());
550 
551       R = std::make_unique<PathSensitiveBugReport>(
552           Type, Msg, ErrorNode, LocUsedForUniqueing,
553           AcquireNode->getLocationContext()->getDecl());
554     }
555   }
556   if (!R)
557     R = std::make_unique<PathSensitiveBugReport>(Type, Msg, ErrorNode);
558   if (Range)
559     R->addRange(*Range);
560   R->markInteresting(Sym);
561   C.emitReport(std::move(R));
562 }
563 
564 void ento::registerFuchsiaHandleChecker(CheckerManager &mgr) {
565   mgr.registerChecker<FuchsiaHandleChecker>();
566 }
567 
568 bool ento::shouldRegisterFuchsiaHandleChecker(const LangOptions &LO) {
569   return true;
570 }
571 
572 void FuchsiaHandleChecker::printState(raw_ostream &Out, ProgramStateRef State,
573                                       const char *NL, const char *Sep) const {
574 
575   HStateMapTy StateMap = State->get<HStateMap>();
576 
577   if (!StateMap.isEmpty()) {
578     Out << Sep << "FuchsiaHandleChecker :" << NL;
579     for (HStateMapTy::iterator I = StateMap.begin(), E = StateMap.end(); I != E;
580          ++I) {
581       I.getKey()->dumpToStream(Out);
582       Out << " : ";
583       I.getData().dump(Out);
584       Out << NL;
585     }
586   }
587 }
588