MacOSKeychainAPIChecker.cpp 24 KB

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