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