MacOSKeychainAPIChecker.cpp 24 KB

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