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