MacOSKeychainAPIChecker.cpp 24 KB

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