MacOSKeychainAPIChecker.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633
  1. //==--- MacOSKeychainAPIChecker.cpp ------------------------------*- C++ -*-==//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. // This checker flags misuses of KeyChainAPI. In particular, the password data
  10. // allocated/returned by SecKeychainItemCopyContent,
  11. // SecKeychainFindGenericPassword, SecKeychainFindInternetPassword functions has
  12. // to be freed using a call to SecKeychainItemFreeContent.
  13. //===----------------------------------------------------------------------===//
  14. #include "ClangSACheckers.h"
  15. #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
  16. #include "clang/StaticAnalyzer/Core/Checker.h"
  17. #include "clang/StaticAnalyzer/Core/CheckerManager.h"
  18. #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
  19. #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
  20. #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
  21. #include "llvm/ADT/SmallString.h"
  22. #include "llvm/Support/raw_ostream.h"
  23. using namespace clang;
  24. using namespace ento;
  25. namespace {
  26. class MacOSKeychainAPIChecker : public Checker<check::PreStmt<CallExpr>,
  27. check::PostStmt<CallExpr>,
  28. check::DeadSymbols> {
  29. mutable std::unique_ptr<BugType> BT;
  30. public:
  31. /// AllocationState is a part of the checker specific state together with the
  32. /// MemRegion corresponding to the allocated data.
  33. struct AllocationState {
  34. /// The index of the allocator function.
  35. unsigned int AllocatorIdx;
  36. SymbolRef Region;
  37. AllocationState(const Expr *E, unsigned int Idx, SymbolRef R) :
  38. AllocatorIdx(Idx),
  39. Region(R) {}
  40. bool operator==(const AllocationState &X) const {
  41. return (AllocatorIdx == X.AllocatorIdx &&
  42. Region == X.Region);
  43. }
  44. void Profile(llvm::FoldingSetNodeID &ID) const {
  45. ID.AddInteger(AllocatorIdx);
  46. ID.AddPointer(Region);
  47. }
  48. };
  49. void checkPreStmt(const CallExpr *S, CheckerContext &C) const;
  50. void checkPostStmt(const CallExpr *S, CheckerContext &C) const;
  51. void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const;
  52. private:
  53. typedef std::pair<SymbolRef, const AllocationState*> AllocationPair;
  54. typedef SmallVector<AllocationPair, 2> AllocationPairVec;
  55. enum APIKind {
  56. /// Denotes functions tracked by this checker.
  57. ValidAPI = 0,
  58. /// The functions commonly/mistakenly used in place of the given API.
  59. ErrorAPI = 1,
  60. /// The functions which may allocate the data. These are tracked to reduce
  61. /// the false alarm rate.
  62. PossibleAPI = 2
  63. };
  64. /// Stores the information about the allocator and deallocator functions -
  65. /// these are the functions the checker is tracking.
  66. struct ADFunctionInfo {
  67. const char* Name;
  68. unsigned int Param;
  69. unsigned int DeallocatorIdx;
  70. APIKind Kind;
  71. };
  72. static const unsigned InvalidIdx = 100000;
  73. static const unsigned FunctionsToTrackSize = 8;
  74. static const ADFunctionInfo FunctionsToTrack[FunctionsToTrackSize];
  75. /// The value, which represents no error return value for allocator functions.
  76. static const unsigned NoErr = 0;
  77. /// Given the function name, returns the index of the allocator/deallocator
  78. /// function.
  79. static unsigned getTrackedFunctionIndex(StringRef Name, bool IsAllocator);
  80. inline void initBugType() const {
  81. if (!BT)
  82. BT.reset(new BugType(this, "Improper use of SecKeychain API",
  83. "API Misuse (Apple)"));
  84. }
  85. void generateDeallocatorMismatchReport(const AllocationPair &AP,
  86. const Expr *ArgExpr,
  87. CheckerContext &C) const;
  88. /// Find the allocation site for Sym on the path leading to the node N.
  89. const ExplodedNode *getAllocationNode(const ExplodedNode *N, SymbolRef Sym,
  90. CheckerContext &C) const;
  91. BugReport *generateAllocatedDataNotReleasedReport(const AllocationPair &AP,
  92. ExplodedNode *N,
  93. CheckerContext &C) const;
  94. /// Check if RetSym evaluates to an error value in the current state.
  95. bool definitelyReturnedError(SymbolRef RetSym,
  96. ProgramStateRef State,
  97. SValBuilder &Builder,
  98. bool noError = false) const;
  99. /// Check if RetSym evaluates to a NoErr value in the current state.
  100. bool definitelyDidnotReturnError(SymbolRef RetSym,
  101. ProgramStateRef State,
  102. SValBuilder &Builder) const {
  103. return definitelyReturnedError(RetSym, State, Builder, true);
  104. }
  105. /// Mark an AllocationPair interesting for diagnostic reporting.
  106. void markInteresting(BugReport *R, const AllocationPair &AP) const {
  107. R->markInteresting(AP.first);
  108. R->markInteresting(AP.second->Region);
  109. }
  110. /// The bug visitor which allows us to print extra diagnostics along the
  111. /// BugReport path. For example, showing the allocation site of the leaked
  112. /// region.
  113. class SecKeychainBugVisitor
  114. : public BugReporterVisitorImpl<SecKeychainBugVisitor> {
  115. protected:
  116. // The allocated region symbol tracked by the main analysis.
  117. SymbolRef Sym;
  118. public:
  119. SecKeychainBugVisitor(SymbolRef S) : Sym(S) {}
  120. ~SecKeychainBugVisitor() override {}
  121. void Profile(llvm::FoldingSetNodeID &ID) const override {
  122. static int X = 0;
  123. ID.AddPointer(&X);
  124. ID.AddPointer(Sym);
  125. }
  126. PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
  127. const ExplodedNode *PrevN,
  128. BugReporterContext &BRC,
  129. BugReport &BR) override;
  130. };
  131. };
  132. }
  133. /// ProgramState traits to store the currently allocated (and not yet freed)
  134. /// symbols. This is a map from the allocated content symbol to the
  135. /// corresponding AllocationState.
  136. REGISTER_MAP_WITH_PROGRAMSTATE(AllocatedData,
  137. SymbolRef,
  138. MacOSKeychainAPIChecker::AllocationState)
  139. static bool isEnclosingFunctionParam(const Expr *E) {
  140. E = E->IgnoreParenCasts();
  141. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  142. const ValueDecl *VD = DRE->getDecl();
  143. if (isa<ImplicitParamDecl>(VD) || isa<ParmVarDecl>(VD))
  144. return true;
  145. }
  146. return false;
  147. }
  148. const MacOSKeychainAPIChecker::ADFunctionInfo
  149. MacOSKeychainAPIChecker::FunctionsToTrack[FunctionsToTrackSize] = {
  150. {"SecKeychainItemCopyContent", 4, 3, ValidAPI}, // 0
  151. {"SecKeychainFindGenericPassword", 6, 3, ValidAPI}, // 1
  152. {"SecKeychainFindInternetPassword", 13, 3, ValidAPI}, // 2
  153. {"SecKeychainItemFreeContent", 1, InvalidIdx, ValidAPI}, // 3
  154. {"SecKeychainItemCopyAttributesAndData", 5, 5, ValidAPI}, // 4
  155. {"SecKeychainItemFreeAttributesAndData", 1, InvalidIdx, ValidAPI}, // 5
  156. {"free", 0, InvalidIdx, ErrorAPI}, // 6
  157. {"CFStringCreateWithBytesNoCopy", 1, InvalidIdx, PossibleAPI}, // 7
  158. };
  159. unsigned MacOSKeychainAPIChecker::getTrackedFunctionIndex(StringRef Name,
  160. bool IsAllocator) {
  161. for (unsigned I = 0; I < FunctionsToTrackSize; ++I) {
  162. ADFunctionInfo FI = FunctionsToTrack[I];
  163. if (FI.Name != Name)
  164. continue;
  165. // Make sure the function is of the right type (allocator vs deallocator).
  166. if (IsAllocator && (FI.DeallocatorIdx == InvalidIdx))
  167. return InvalidIdx;
  168. if (!IsAllocator && (FI.DeallocatorIdx != InvalidIdx))
  169. return InvalidIdx;
  170. return I;
  171. }
  172. // The function is not tracked.
  173. return InvalidIdx;
  174. }
  175. static bool isBadDeallocationArgument(const MemRegion *Arg) {
  176. if (!Arg)
  177. return false;
  178. if (isa<AllocaRegion>(Arg) ||
  179. isa<BlockDataRegion>(Arg) ||
  180. isa<TypedRegion>(Arg)) {
  181. return true;
  182. }
  183. return false;
  184. }
  185. /// Given the address expression, retrieve the value it's pointing to. Assume
  186. /// that value is itself an address, and return the corresponding symbol.
  187. static SymbolRef getAsPointeeSymbol(const Expr *Expr,
  188. CheckerContext &C) {
  189. ProgramStateRef State = C.getState();
  190. SVal ArgV = State->getSVal(Expr, C.getLocationContext());
  191. if (Optional<loc::MemRegionVal> X = ArgV.getAs<loc::MemRegionVal>()) {
  192. StoreManager& SM = C.getStoreManager();
  193. SymbolRef sym = SM.getBinding(State->getStore(), *X).getAsLocSymbol();
  194. if (sym)
  195. return sym;
  196. }
  197. return nullptr;
  198. }
  199. // When checking for error code, we need to consider the following cases:
  200. // 1) noErr / [0]
  201. // 2) someErr / [1, inf]
  202. // 3) unknown
  203. // If noError, returns true iff (1).
  204. // If !noError, returns true iff (2).
  205. bool MacOSKeychainAPIChecker::definitelyReturnedError(SymbolRef RetSym,
  206. ProgramStateRef State,
  207. SValBuilder &Builder,
  208. bool noError) const {
  209. DefinedOrUnknownSVal NoErrVal = Builder.makeIntVal(NoErr,
  210. Builder.getSymbolManager().getType(RetSym));
  211. DefinedOrUnknownSVal NoErr = Builder.evalEQ(State, NoErrVal,
  212. nonloc::SymbolVal(RetSym));
  213. ProgramStateRef ErrState = State->assume(NoErr, noError);
  214. if (ErrState == State) {
  215. return true;
  216. }
  217. return false;
  218. }
  219. // Report deallocator mismatch. Remove the region from tracking - reporting a
  220. // missing free error after this one is redundant.
  221. void MacOSKeychainAPIChecker::
  222. generateDeallocatorMismatchReport(const AllocationPair &AP,
  223. const Expr *ArgExpr,
  224. CheckerContext &C) const {
  225. ProgramStateRef State = C.getState();
  226. State = State->remove<AllocatedData>(AP.first);
  227. ExplodedNode *N = C.addTransition(State);
  228. if (!N)
  229. return;
  230. initBugType();
  231. SmallString<80> sbuf;
  232. llvm::raw_svector_ostream os(sbuf);
  233. unsigned int PDeallocIdx =
  234. FunctionsToTrack[AP.second->AllocatorIdx].DeallocatorIdx;
  235. os << "Deallocator doesn't match the allocator: '"
  236. << FunctionsToTrack[PDeallocIdx].Name << "' should be used.";
  237. BugReport *Report = new BugReport(*BT, os.str(), N);
  238. Report->addVisitor(llvm::make_unique<SecKeychainBugVisitor>(AP.first));
  239. Report->addRange(ArgExpr->getSourceRange());
  240. markInteresting(Report, AP);
  241. C.emitReport(Report);
  242. }
  243. void MacOSKeychainAPIChecker::checkPreStmt(const CallExpr *CE,
  244. CheckerContext &C) const {
  245. unsigned idx = InvalidIdx;
  246. ProgramStateRef State = C.getState();
  247. const FunctionDecl *FD = C.getCalleeDecl(CE);
  248. if (!FD || FD->getKind() != Decl::Function)
  249. return;
  250. StringRef funName = C.getCalleeName(FD);
  251. if (funName.empty())
  252. return;
  253. // If it is a call to an allocator function, it could be a double allocation.
  254. idx = getTrackedFunctionIndex(funName, true);
  255. if (idx != InvalidIdx) {
  256. unsigned paramIdx = FunctionsToTrack[idx].Param;
  257. if (CE->getNumArgs() <= paramIdx)
  258. return;
  259. const Expr *ArgExpr = CE->getArg(paramIdx);
  260. if (SymbolRef V = getAsPointeeSymbol(ArgExpr, C))
  261. if (const AllocationState *AS = State->get<AllocatedData>(V)) {
  262. if (!definitelyReturnedError(AS->Region, State, C.getSValBuilder())) {
  263. // Remove the value from the state. The new symbol will be added for
  264. // tracking when the second allocator is processed in checkPostStmt().
  265. State = State->remove<AllocatedData>(V);
  266. ExplodedNode *N = C.addTransition(State);
  267. if (!N)
  268. return;
  269. initBugType();
  270. SmallString<128> sbuf;
  271. llvm::raw_svector_ostream os(sbuf);
  272. unsigned int DIdx = FunctionsToTrack[AS->AllocatorIdx].DeallocatorIdx;
  273. os << "Allocated data should be released before another call to "
  274. << "the allocator: missing a call to '"
  275. << FunctionsToTrack[DIdx].Name
  276. << "'.";
  277. BugReport *Report = new BugReport(*BT, os.str(), N);
  278. Report->addVisitor(llvm::make_unique<SecKeychainBugVisitor>(V));
  279. Report->addRange(ArgExpr->getSourceRange());
  280. Report->markInteresting(AS->Region);
  281. C.emitReport(Report);
  282. }
  283. }
  284. return;
  285. }
  286. // Is it a call to one of deallocator functions?
  287. idx = getTrackedFunctionIndex(funName, false);
  288. if (idx == InvalidIdx)
  289. return;
  290. unsigned paramIdx = FunctionsToTrack[idx].Param;
  291. if (CE->getNumArgs() <= paramIdx)
  292. return;
  293. // Check the argument to the deallocator.
  294. const Expr *ArgExpr = CE->getArg(paramIdx);
  295. SVal ArgSVal = State->getSVal(ArgExpr, C.getLocationContext());
  296. // Undef is reported by another checker.
  297. if (ArgSVal.isUndef())
  298. return;
  299. SymbolRef ArgSM = ArgSVal.getAsLocSymbol();
  300. // If the argument is coming from the heap, globals, or unknown, do not
  301. // report it.
  302. bool RegionArgIsBad = false;
  303. if (!ArgSM) {
  304. if (!isBadDeallocationArgument(ArgSVal.getAsRegion()))
  305. return;
  306. RegionArgIsBad = true;
  307. }
  308. // Is the argument to the call being tracked?
  309. const AllocationState *AS = State->get<AllocatedData>(ArgSM);
  310. if (!AS && FunctionsToTrack[idx].Kind != ValidAPI) {
  311. return;
  312. }
  313. // If trying to free data which has not been allocated yet, report as a bug.
  314. // TODO: We might want a more precise diagnostic for double free
  315. // (that would involve tracking all the freed symbols in the checker state).
  316. if (!AS || RegionArgIsBad) {
  317. // It is possible that this is a false positive - the argument might
  318. // have entered as an enclosing function parameter.
  319. if (isEnclosingFunctionParam(ArgExpr))
  320. return;
  321. ExplodedNode *N = C.addTransition(State);
  322. if (!N)
  323. return;
  324. initBugType();
  325. BugReport *Report = new BugReport(*BT,
  326. "Trying to free data which has not been allocated.", N);
  327. Report->addRange(ArgExpr->getSourceRange());
  328. if (AS)
  329. Report->markInteresting(AS->Region);
  330. C.emitReport(Report);
  331. return;
  332. }
  333. // Process functions which might deallocate.
  334. if (FunctionsToTrack[idx].Kind == PossibleAPI) {
  335. if (funName == "CFStringCreateWithBytesNoCopy") {
  336. const Expr *DeallocatorExpr = CE->getArg(5)->IgnoreParenCasts();
  337. // NULL ~ default deallocator, so warn.
  338. if (DeallocatorExpr->isNullPointerConstant(C.getASTContext(),
  339. Expr::NPC_ValueDependentIsNotNull)) {
  340. const AllocationPair AP = std::make_pair(ArgSM, AS);
  341. generateDeallocatorMismatchReport(AP, ArgExpr, C);
  342. return;
  343. }
  344. // One of the default allocators, so warn.
  345. if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(DeallocatorExpr)) {
  346. StringRef DeallocatorName = DE->getFoundDecl()->getName();
  347. if (DeallocatorName == "kCFAllocatorDefault" ||
  348. DeallocatorName == "kCFAllocatorSystemDefault" ||
  349. DeallocatorName == "kCFAllocatorMalloc") {
  350. const AllocationPair AP = std::make_pair(ArgSM, AS);
  351. generateDeallocatorMismatchReport(AP, ArgExpr, C);
  352. return;
  353. }
  354. // If kCFAllocatorNull, which does not deallocate, we still have to
  355. // find the deallocator.
  356. if (DE->getFoundDecl()->getName() == "kCFAllocatorNull")
  357. return;
  358. }
  359. // In all other cases, assume the user supplied a correct deallocator
  360. // that will free memory so stop tracking.
  361. State = State->remove<AllocatedData>(ArgSM);
  362. C.addTransition(State);
  363. return;
  364. }
  365. llvm_unreachable("We know of no other possible APIs.");
  366. }
  367. // The call is deallocating a value we previously allocated, so remove it
  368. // from the next state.
  369. State = State->remove<AllocatedData>(ArgSM);
  370. // Check if the proper deallocator is used.
  371. unsigned int PDeallocIdx = FunctionsToTrack[AS->AllocatorIdx].DeallocatorIdx;
  372. if (PDeallocIdx != idx || (FunctionsToTrack[idx].Kind == ErrorAPI)) {
  373. const AllocationPair AP = std::make_pair(ArgSM, AS);
  374. generateDeallocatorMismatchReport(AP, ArgExpr, C);
  375. return;
  376. }
  377. // If the buffer can be null and the return status can be an error,
  378. // report a bad call to free.
  379. if (State->assume(ArgSVal.castAs<DefinedSVal>(), false) &&
  380. !definitelyDidnotReturnError(AS->Region, State, C.getSValBuilder())) {
  381. ExplodedNode *N = C.addTransition(State);
  382. if (!N)
  383. return;
  384. initBugType();
  385. BugReport *Report = new BugReport(*BT,
  386. "Only call free if a valid (non-NULL) buffer was returned.", N);
  387. Report->addVisitor(llvm::make_unique<SecKeychainBugVisitor>(ArgSM));
  388. Report->addRange(ArgExpr->getSourceRange());
  389. Report->markInteresting(AS->Region);
  390. C.emitReport(Report);
  391. return;
  392. }
  393. C.addTransition(State);
  394. }
  395. void MacOSKeychainAPIChecker::checkPostStmt(const CallExpr *CE,
  396. CheckerContext &C) const {
  397. ProgramStateRef State = C.getState();
  398. const FunctionDecl *FD = C.getCalleeDecl(CE);
  399. if (!FD || FD->getKind() != Decl::Function)
  400. return;
  401. StringRef funName = C.getCalleeName(FD);
  402. // If a value has been allocated, add it to the set for tracking.
  403. unsigned idx = getTrackedFunctionIndex(funName, true);
  404. if (idx == InvalidIdx)
  405. return;
  406. const Expr *ArgExpr = CE->getArg(FunctionsToTrack[idx].Param);
  407. // If the argument entered as an enclosing function parameter, skip it to
  408. // avoid false positives.
  409. if (isEnclosingFunctionParam(ArgExpr) &&
  410. C.getLocationContext()->getParent() == nullptr)
  411. return;
  412. if (SymbolRef V = getAsPointeeSymbol(ArgExpr, C)) {
  413. // If the argument points to something that's not a symbolic region, it
  414. // can be:
  415. // - unknown (cannot reason about it)
  416. // - undefined (already reported by other checker)
  417. // - constant (null - should not be tracked,
  418. // other constant will generate a compiler warning)
  419. // - goto (should be reported by other checker)
  420. // The call return value symbol should stay alive for as long as the
  421. // allocated value symbol, since our diagnostics depend on the value
  422. // returned by the call. Ex: Data should only be freed if noErr was
  423. // returned during allocation.)
  424. SymbolRef RetStatusSymbol =
  425. State->getSVal(CE, C.getLocationContext()).getAsSymbol();
  426. C.getSymbolManager().addSymbolDependency(V, RetStatusSymbol);
  427. // Track the allocated value in the checker state.
  428. State = State->set<AllocatedData>(V, AllocationState(ArgExpr, idx,
  429. RetStatusSymbol));
  430. assert(State);
  431. C.addTransition(State);
  432. }
  433. }
  434. // TODO: This logic is the same as in Malloc checker.
  435. const ExplodedNode *
  436. MacOSKeychainAPIChecker::getAllocationNode(const ExplodedNode *N,
  437. SymbolRef Sym,
  438. CheckerContext &C) const {
  439. const LocationContext *LeakContext = N->getLocationContext();
  440. // Walk the ExplodedGraph backwards and find the first node that referred to
  441. // the tracked symbol.
  442. const ExplodedNode *AllocNode = N;
  443. while (N) {
  444. if (!N->getState()->get<AllocatedData>(Sym))
  445. break;
  446. // Allocation node, is the last node in the current or parent context in
  447. // which the symbol was tracked.
  448. const LocationContext *NContext = N->getLocationContext();
  449. if (NContext == LeakContext ||
  450. NContext->isParentOf(LeakContext))
  451. AllocNode = N;
  452. N = N->pred_empty() ? nullptr : *(N->pred_begin());
  453. }
  454. return AllocNode;
  455. }
  456. BugReport *MacOSKeychainAPIChecker::
  457. generateAllocatedDataNotReleasedReport(const AllocationPair &AP,
  458. ExplodedNode *N,
  459. CheckerContext &C) const {
  460. const ADFunctionInfo &FI = FunctionsToTrack[AP.second->AllocatorIdx];
  461. initBugType();
  462. SmallString<70> sbuf;
  463. llvm::raw_svector_ostream os(sbuf);
  464. os << "Allocated data is not released: missing a call to '"
  465. << FunctionsToTrack[FI.DeallocatorIdx].Name << "'.";
  466. // Most bug reports are cached at the location where they occurred.
  467. // With leaks, we want to unique them by the location where they were
  468. // allocated, and only report a single path.
  469. PathDiagnosticLocation LocUsedForUniqueing;
  470. const ExplodedNode *AllocNode = getAllocationNode(N, AP.first, C);
  471. const Stmt *AllocStmt = nullptr;
  472. ProgramPoint P = AllocNode->getLocation();
  473. if (Optional<CallExitEnd> Exit = P.getAs<CallExitEnd>())
  474. AllocStmt = Exit->getCalleeContext()->getCallSite();
  475. else if (Optional<clang::PostStmt> PS = P.getAs<clang::PostStmt>())
  476. AllocStmt = PS->getStmt();
  477. if (AllocStmt)
  478. LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocStmt,
  479. C.getSourceManager(),
  480. AllocNode->getLocationContext());
  481. BugReport *Report = new BugReport(*BT, os.str(), N, LocUsedForUniqueing,
  482. AllocNode->getLocationContext()->getDecl());
  483. Report->addVisitor(llvm::make_unique<SecKeychainBugVisitor>(AP.first));
  484. markInteresting(Report, AP);
  485. return Report;
  486. }
  487. void MacOSKeychainAPIChecker::checkDeadSymbols(SymbolReaper &SR,
  488. CheckerContext &C) const {
  489. ProgramStateRef State = C.getState();
  490. AllocatedDataTy ASet = State->get<AllocatedData>();
  491. if (ASet.isEmpty())
  492. return;
  493. bool Changed = false;
  494. AllocationPairVec Errors;
  495. for (AllocatedDataTy::iterator I = ASet.begin(), E = ASet.end(); I != E; ++I) {
  496. if (SR.isLive(I->first))
  497. continue;
  498. Changed = true;
  499. State = State->remove<AllocatedData>(I->first);
  500. // If the allocated symbol is null or if the allocation call might have
  501. // returned an error, do not report.
  502. ConstraintManager &CMgr = State->getConstraintManager();
  503. ConditionTruthVal AllocFailed = CMgr.isNull(State, I.getKey());
  504. if (AllocFailed.isConstrainedTrue() ||
  505. definitelyReturnedError(I->second.Region, State, C.getSValBuilder()))
  506. continue;
  507. Errors.push_back(std::make_pair(I->first, &I->second));
  508. }
  509. if (!Changed) {
  510. // Generate the new, cleaned up state.
  511. C.addTransition(State);
  512. return;
  513. }
  514. static CheckerProgramPointTag Tag(this, "DeadSymbolsLeak");
  515. ExplodedNode *N = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
  516. // Generate the error reports.
  517. for (AllocationPairVec::iterator I = Errors.begin(), E = Errors.end();
  518. I != E; ++I) {
  519. C.emitReport(generateAllocatedDataNotReleasedReport(*I, N, C));
  520. }
  521. // Generate the new, cleaned up state.
  522. C.addTransition(State, N);
  523. }
  524. PathDiagnosticPiece *MacOSKeychainAPIChecker::SecKeychainBugVisitor::VisitNode(
  525. const ExplodedNode *N,
  526. const ExplodedNode *PrevN,
  527. BugReporterContext &BRC,
  528. BugReport &BR) {
  529. const AllocationState *AS = N->getState()->get<AllocatedData>(Sym);
  530. if (!AS)
  531. return nullptr;
  532. const AllocationState *ASPrev = PrevN->getState()->get<AllocatedData>(Sym);
  533. if (ASPrev)
  534. return nullptr;
  535. // (!ASPrev && AS) ~ We started tracking symbol in node N, it must be the
  536. // allocation site.
  537. const CallExpr *CE =
  538. cast<CallExpr>(N->getLocation().castAs<StmtPoint>().getStmt());
  539. const FunctionDecl *funDecl = CE->getDirectCallee();
  540. assert(funDecl && "We do not support indirect function calls as of now.");
  541. StringRef funName = funDecl->getName();
  542. // Get the expression of the corresponding argument.
  543. unsigned Idx = getTrackedFunctionIndex(funName, true);
  544. assert(Idx != InvalidIdx && "This should be a call to an allocator.");
  545. const Expr *ArgExpr = CE->getArg(FunctionsToTrack[Idx].Param);
  546. PathDiagnosticLocation Pos(ArgExpr, BRC.getSourceManager(),
  547. N->getLocationContext());
  548. return new PathDiagnosticEventPiece(Pos, "Data is allocated here.");
  549. }
  550. void ento::registerMacOSKeychainAPIChecker(CheckerManager &mgr) {
  551. mgr.registerChecker<MacOSKeychainAPIChecker>();
  552. }