MacOSKeychainAPIChecker.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620
  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/Checker.h"
  16. #include "clang/StaticAnalyzer/Core/CheckerManager.h"
  17. #include "clang/StaticAnalyzer/Core/BugReporter/BugType.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. using namespace clang;
  23. using namespace ento;
  24. namespace {
  25. class MacOSKeychainAPIChecker : public Checker<check::PreStmt<CallExpr>,
  26. check::PreStmt<ReturnStmt>,
  27. check::PostStmt<CallExpr>,
  28. check::EndPath,
  29. check::DeadSymbols> {
  30. mutable OwningPtr<BugType> BT;
  31. public:
  32. /// AllocationState is a part of the checker specific state together with the
  33. /// MemRegion corresponding to the allocated data.
  34. struct AllocationState {
  35. /// The index of the allocator function.
  36. unsigned int AllocatorIdx;
  37. SymbolRef Region;
  38. AllocationState(const Expr *E, unsigned int Idx, SymbolRef R) :
  39. AllocatorIdx(Idx),
  40. Region(R) {}
  41. bool operator==(const AllocationState &X) const {
  42. return (AllocatorIdx == X.AllocatorIdx &&
  43. Region == X.Region);
  44. }
  45. void Profile(llvm::FoldingSetNodeID &ID) const {
  46. ID.AddInteger(AllocatorIdx);
  47. ID.AddPointer(Region);
  48. }
  49. };
  50. void checkPreStmt(const CallExpr *S, CheckerContext &C) const;
  51. void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
  52. void checkPostStmt(const CallExpr *S, CheckerContext &C) const;
  53. void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const;
  54. void checkEndPath(CheckerContext &Ctx) const;
  55. private:
  56. typedef std::pair<SymbolRef, const AllocationState*> AllocationPair;
  57. typedef llvm::SmallVector<AllocationPair, 2> AllocationPairVec;
  58. enum APIKind {
  59. /// Denotes functions tracked by this checker.
  60. ValidAPI = 0,
  61. /// The functions commonly/mistakenly used in place of the given API.
  62. ErrorAPI = 1,
  63. /// The functions which may allocate the data. These are tracked to reduce
  64. /// the false alarm rate.
  65. PossibleAPI = 2
  66. };
  67. /// Stores the information about the allocator and deallocator functions -
  68. /// these are the functions the checker is tracking.
  69. struct ADFunctionInfo {
  70. const char* Name;
  71. unsigned int Param;
  72. unsigned int DeallocatorIdx;
  73. APIKind Kind;
  74. };
  75. static const unsigned InvalidIdx = 100000;
  76. static const unsigned FunctionsToTrackSize = 8;
  77. static const ADFunctionInfo FunctionsToTrack[FunctionsToTrackSize];
  78. /// The value, which represents no error return value for allocator functions.
  79. static const unsigned NoErr = 0;
  80. /// Given the function name, returns the index of the allocator/deallocator
  81. /// function.
  82. static unsigned getTrackedFunctionIndex(StringRef Name, bool IsAllocator);
  83. inline void initBugType() const {
  84. if (!BT)
  85. BT.reset(new BugType("Improper use of SecKeychain API", "Mac OS API"));
  86. }
  87. void generateDeallocatorMismatchReport(const AllocationPair &AP,
  88. const Expr *ArgExpr,
  89. CheckerContext &C) const;
  90. BugReport *generateAllocatedDataNotReleasedReport(const AllocationPair &AP,
  91. ExplodedNode *N) const;
  92. /// Check if RetSym evaluates to an error value in the current state.
  93. bool definitelyReturnedError(SymbolRef RetSym,
  94. ProgramStateRef State,
  95. SValBuilder &Builder,
  96. bool noError = false) const;
  97. /// Check if RetSym evaluates to a NoErr value in the current state.
  98. bool definitelyDidnotReturnError(SymbolRef RetSym,
  99. ProgramStateRef State,
  100. SValBuilder &Builder) const {
  101. return definitelyReturnedError(RetSym, State, Builder, true);
  102. }
  103. /// The bug visitor which allows us to print extra diagnostics along the
  104. /// BugReport path. For example, showing the allocation site of the leaked
  105. /// region.
  106. class SecKeychainBugVisitor : public BugReporterVisitor {
  107. protected:
  108. // The allocated region symbol tracked by the main analysis.
  109. SymbolRef Sym;
  110. public:
  111. SecKeychainBugVisitor(SymbolRef S) : Sym(S) {}
  112. virtual ~SecKeychainBugVisitor() {}
  113. void Profile(llvm::FoldingSetNodeID &ID) const {
  114. static int X = 0;
  115. ID.AddPointer(&X);
  116. ID.AddPointer(Sym);
  117. }
  118. PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
  119. const ExplodedNode *PrevN,
  120. BugReporterContext &BRC,
  121. BugReport &BR);
  122. };
  123. };
  124. }
  125. /// ProgramState traits to store the currently allocated (and not yet freed)
  126. /// symbols. This is a map from the allocated content symbol to the
  127. /// corresponding AllocationState.
  128. typedef llvm::ImmutableMap<SymbolRef,
  129. MacOSKeychainAPIChecker::AllocationState> AllocatedSetTy;
  130. namespace { struct AllocatedData {}; }
  131. namespace clang { namespace ento {
  132. template<> struct ProgramStateTrait<AllocatedData>
  133. : public ProgramStatePartialTrait<AllocatedSetTy > {
  134. static void *GDMIndex() { static int index = 0; return &index; }
  135. };
  136. }}
  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 SymbolRef getSymbolForRegion(CheckerContext &C,
  174. const MemRegion *R) {
  175. // Implicit casts (ex: void* -> char*) can turn Symbolic region into element
  176. // region, if that is the case, get the underlining region.
  177. R = R->StripCasts();
  178. if (!isa<SymbolicRegion>(R)) {
  179. return 0;
  180. }
  181. return cast<SymbolicRegion>(R)->getSymbol();
  182. }
  183. static bool isBadDeallocationArgument(const MemRegion *Arg) {
  184. if (isa<AllocaRegion>(Arg) ||
  185. isa<BlockDataRegion>(Arg) ||
  186. isa<TypedRegion>(Arg)) {
  187. return true;
  188. }
  189. return false;
  190. }
  191. /// Given the address expression, retrieve the value it's pointing to. Assume
  192. /// that value is itself an address, and return the corresponding symbol.
  193. static SymbolRef getAsPointeeSymbol(const Expr *Expr,
  194. CheckerContext &C) {
  195. ProgramStateRef State = C.getState();
  196. SVal ArgV = State->getSVal(Expr, C.getLocationContext());
  197. if (const loc::MemRegionVal *X = dyn_cast<loc::MemRegionVal>(&ArgV)) {
  198. StoreManager& SM = C.getStoreManager();
  199. const MemRegion *V = SM.getBinding(State->getStore(), *X).getAsRegion();
  200. if (V)
  201. return getSymbolForRegion(C, V);
  202. }
  203. return 0;
  204. }
  205. // When checking for error code, we need to consider the following cases:
  206. // 1) noErr / [0]
  207. // 2) someErr / [1, inf]
  208. // 3) unknown
  209. // If noError, returns true iff (1).
  210. // If !noError, returns true iff (2).
  211. bool MacOSKeychainAPIChecker::definitelyReturnedError(SymbolRef RetSym,
  212. ProgramStateRef State,
  213. SValBuilder &Builder,
  214. bool noError) const {
  215. DefinedOrUnknownSVal NoErrVal = Builder.makeIntVal(NoErr,
  216. Builder.getSymbolManager().getType(RetSym));
  217. DefinedOrUnknownSVal NoErr = Builder.evalEQ(State, NoErrVal,
  218. nonloc::SymbolVal(RetSym));
  219. ProgramStateRef ErrState = State->assume(NoErr, noError);
  220. if (ErrState == State) {
  221. return true;
  222. }
  223. return false;
  224. }
  225. // Report deallocator mismatch. Remove the region from tracking - reporting a
  226. // missing free error after this one is redundant.
  227. void MacOSKeychainAPIChecker::
  228. generateDeallocatorMismatchReport(const AllocationPair &AP,
  229. const Expr *ArgExpr,
  230. CheckerContext &C) const {
  231. ProgramStateRef State = C.getState();
  232. State = State->remove<AllocatedData>(AP.first);
  233. ExplodedNode *N = C.addTransition(State);
  234. if (!N)
  235. return;
  236. initBugType();
  237. SmallString<80> sbuf;
  238. llvm::raw_svector_ostream os(sbuf);
  239. unsigned int PDeallocIdx =
  240. FunctionsToTrack[AP.second->AllocatorIdx].DeallocatorIdx;
  241. os << "Deallocator doesn't match the allocator: '"
  242. << FunctionsToTrack[PDeallocIdx].Name << "' should be used.";
  243. BugReport *Report = new BugReport(*BT, os.str(), N);
  244. Report->addVisitor(new SecKeychainBugVisitor(AP.first));
  245. Report->addRange(ArgExpr->getSourceRange());
  246. C.EmitReport(Report);
  247. }
  248. void MacOSKeychainAPIChecker::checkPreStmt(const CallExpr *CE,
  249. CheckerContext &C) const {
  250. unsigned idx = InvalidIdx;
  251. ProgramStateRef State = C.getState();
  252. StringRef funName = C.getCalleeName(CE);
  253. if (funName.empty())
  254. return;
  255. // If it is a call to an allocator function, it could be a double allocation.
  256. idx = getTrackedFunctionIndex(funName, true);
  257. if (idx != InvalidIdx) {
  258. const Expr *ArgExpr = CE->getArg(FunctionsToTrack[idx].Param);
  259. if (SymbolRef V = getAsPointeeSymbol(ArgExpr, C))
  260. if (const AllocationState *AS = State->get<AllocatedData>(V)) {
  261. if (!definitelyReturnedError(AS->Region, State, C.getSValBuilder())) {
  262. // Remove the value from the state. The new symbol will be added for
  263. // tracking when the second allocator is processed in checkPostStmt().
  264. State = State->remove<AllocatedData>(V);
  265. ExplodedNode *N = C.addTransition(State);
  266. if (!N)
  267. return;
  268. initBugType();
  269. SmallString<128> sbuf;
  270. llvm::raw_svector_ostream os(sbuf);
  271. unsigned int DIdx = FunctionsToTrack[AS->AllocatorIdx].DeallocatorIdx;
  272. os << "Allocated data should be released before another call to "
  273. << "the allocator: missing a call to '"
  274. << FunctionsToTrack[DIdx].Name
  275. << "'.";
  276. BugReport *Report = new BugReport(*BT, os.str(), N);
  277. Report->addVisitor(new SecKeychainBugVisitor(V));
  278. Report->addRange(ArgExpr->getSourceRange());
  279. C.EmitReport(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. // Check the argument to the deallocator.
  289. const Expr *ArgExpr = CE->getArg(FunctionsToTrack[idx].Param);
  290. SVal ArgSVal = State->getSVal(ArgExpr, C.getLocationContext());
  291. // Undef is reported by another checker.
  292. if (ArgSVal.isUndef())
  293. return;
  294. const MemRegion *Arg = ArgSVal.getAsRegion();
  295. if (!Arg)
  296. return;
  297. SymbolRef ArgSM = getSymbolForRegion(C, Arg);
  298. bool RegionArgIsBad = ArgSM ? false : isBadDeallocationArgument(Arg);
  299. // If the argument is coming from the heap, globals, or unknown, do not
  300. // report it.
  301. if (!ArgSM && !RegionArgIsBad)
  302. return;
  303. // Is the argument to the call being tracked?
  304. const AllocationState *AS = State->get<AllocatedData>(ArgSM);
  305. if (!AS && FunctionsToTrack[idx].Kind != ValidAPI) {
  306. return;
  307. }
  308. // If trying to free data which has not been allocated yet, report as a bug.
  309. // TODO: We might want a more precise diagnostic for double free
  310. // (that would involve tracking all the freed symbols in the checker state).
  311. if (!AS || RegionArgIsBad) {
  312. // It is possible that this is a false positive - the argument might
  313. // have entered as an enclosing function parameter.
  314. if (isEnclosingFunctionParam(ArgExpr))
  315. return;
  316. ExplodedNode *N = C.addTransition(State);
  317. if (!N)
  318. return;
  319. initBugType();
  320. BugReport *Report = new BugReport(*BT,
  321. "Trying to free data which has not been allocated.", N);
  322. Report->addRange(ArgExpr->getSourceRange());
  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. Otherwise, assume that the user had written a
  349. // custom deallocator which does the right thing.
  350. if (DE->getFoundDecl()->getName() != "kCFAllocatorNull") {
  351. State = State->remove<AllocatedData>(ArgSM);
  352. C.addTransition(State);
  353. return;
  354. }
  355. }
  356. }
  357. return;
  358. }
  359. // The call is deallocating a value we previously allocated, so remove it
  360. // from the next state.
  361. State = State->remove<AllocatedData>(ArgSM);
  362. // Check if the proper deallocator is used.
  363. unsigned int PDeallocIdx = FunctionsToTrack[AS->AllocatorIdx].DeallocatorIdx;
  364. if (PDeallocIdx != idx || (FunctionsToTrack[idx].Kind == ErrorAPI)) {
  365. const AllocationPair AP = std::make_pair(ArgSM, AS);
  366. generateDeallocatorMismatchReport(AP, ArgExpr, C);
  367. return;
  368. }
  369. // If the buffer can be null and the return status can be an error,
  370. // report a bad call to free.
  371. if (State->assume(cast<DefinedSVal>(ArgSVal), false) &&
  372. !definitelyDidnotReturnError(AS->Region, State, C.getSValBuilder())) {
  373. ExplodedNode *N = C.addTransition(State);
  374. if (!N)
  375. return;
  376. initBugType();
  377. BugReport *Report = new BugReport(*BT,
  378. "Only call free if a valid (non-NULL) buffer was returned.", N);
  379. Report->addVisitor(new SecKeychainBugVisitor(ArgSM));
  380. Report->addRange(ArgExpr->getSourceRange());
  381. C.EmitReport(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. StringRef funName = C.getCalleeName(CE);
  390. // If a value has been allocated, add it to the set for tracking.
  391. unsigned idx = getTrackedFunctionIndex(funName, true);
  392. if (idx == InvalidIdx)
  393. return;
  394. const Expr *ArgExpr = CE->getArg(FunctionsToTrack[idx].Param);
  395. // If the argument entered as an enclosing function parameter, skip it to
  396. // avoid false positives.
  397. if (isEnclosingFunctionParam(ArgExpr))
  398. return;
  399. if (SymbolRef V = getAsPointeeSymbol(ArgExpr, C)) {
  400. // If the argument points to something that's not a symbolic region, it
  401. // can be:
  402. // - unknown (cannot reason about it)
  403. // - undefined (already reported by other checker)
  404. // - constant (null - should not be tracked,
  405. // other constant will generate a compiler warning)
  406. // - goto (should be reported by other checker)
  407. // The call return value symbol should stay alive for as long as the
  408. // allocated value symbol, since our diagnostics depend on the value
  409. // returned by the call. Ex: Data should only be freed if noErr was
  410. // returned during allocation.)
  411. SymbolRef RetStatusSymbol =
  412. State->getSVal(CE, C.getLocationContext()).getAsSymbol();
  413. C.getSymbolManager().addSymbolDependency(V, RetStatusSymbol);
  414. // Track the allocated value in the checker state.
  415. State = State->set<AllocatedData>(V, AllocationState(ArgExpr, idx,
  416. RetStatusSymbol));
  417. assert(State);
  418. C.addTransition(State);
  419. }
  420. }
  421. void MacOSKeychainAPIChecker::checkPreStmt(const ReturnStmt *S,
  422. CheckerContext &C) const {
  423. const Expr *retExpr = S->getRetValue();
  424. if (!retExpr)
  425. return;
  426. // Check if the value is escaping through the return.
  427. ProgramStateRef state = C.getState();
  428. const MemRegion *V =
  429. state->getSVal(retExpr, C.getLocationContext()).getAsRegion();
  430. if (!V)
  431. return;
  432. state = state->remove<AllocatedData>(getSymbolForRegion(C, V));
  433. // Proceed from the new state.
  434. C.addTransition(state);
  435. }
  436. BugReport *MacOSKeychainAPIChecker::
  437. generateAllocatedDataNotReleasedReport(const AllocationPair &AP,
  438. ExplodedNode *N) const {
  439. const ADFunctionInfo &FI = FunctionsToTrack[AP.second->AllocatorIdx];
  440. initBugType();
  441. SmallString<70> sbuf;
  442. llvm::raw_svector_ostream os(sbuf);
  443. os << "Allocated data is not released: missing a call to '"
  444. << FunctionsToTrack[FI.DeallocatorIdx].Name << "'.";
  445. BugReport *Report = new BugReport(*BT, os.str(), N);
  446. Report->addVisitor(new SecKeychainBugVisitor(AP.first));
  447. Report->addRange(SourceRange());
  448. return Report;
  449. }
  450. void MacOSKeychainAPIChecker::checkDeadSymbols(SymbolReaper &SR,
  451. CheckerContext &C) const {
  452. ProgramStateRef State = C.getState();
  453. AllocatedSetTy ASet = State->get<AllocatedData>();
  454. if (ASet.isEmpty())
  455. return;
  456. bool Changed = false;
  457. AllocationPairVec Errors;
  458. for (AllocatedSetTy::iterator I = ASet.begin(), E = ASet.end(); I != E; ++I) {
  459. if (SR.isLive(I->first))
  460. continue;
  461. Changed = true;
  462. State = State->remove<AllocatedData>(I->first);
  463. // If the allocated symbol is null or if the allocation call might have
  464. // returned an error, do not report.
  465. if (State->getSymVal(I->first) ||
  466. definitelyReturnedError(I->second.Region, State, C.getSValBuilder()))
  467. continue;
  468. Errors.push_back(std::make_pair(I->first, &I->second));
  469. }
  470. if (!Changed)
  471. return;
  472. // Generate the new, cleaned up state.
  473. ExplodedNode *N = C.addTransition(State);
  474. if (!N)
  475. return;
  476. // Generate the error reports.
  477. for (AllocationPairVec::iterator I = Errors.begin(), E = Errors.end();
  478. I != E; ++I) {
  479. C.EmitReport(generateAllocatedDataNotReleasedReport(*I, N));
  480. }
  481. }
  482. // TODO: Remove this after we ensure that checkDeadSymbols are always called.
  483. void MacOSKeychainAPIChecker::checkEndPath(CheckerContext &Ctx) const {
  484. ProgramStateRef state = Ctx.getState();
  485. AllocatedSetTy AS = state->get<AllocatedData>();
  486. if (AS.isEmpty())
  487. return;
  488. // Anything which has been allocated but not freed (nor escaped) will be
  489. // found here, so report it.
  490. bool Changed = false;
  491. AllocationPairVec Errors;
  492. for (AllocatedSetTy::iterator I = AS.begin(), E = AS.end(); I != E; ++I ) {
  493. Changed = true;
  494. state = state->remove<AllocatedData>(I->first);
  495. // If the allocated symbol is null or if error code was returned at
  496. // allocation, do not report.
  497. if (state->getSymVal(I.getKey()) ||
  498. definitelyReturnedError(I->second.Region, state,
  499. Ctx.getSValBuilder())) {
  500. continue;
  501. }
  502. Errors.push_back(std::make_pair(I->first, &I->second));
  503. }
  504. // If no change, do not generate a new state.
  505. if (!Changed)
  506. return;
  507. ExplodedNode *N = Ctx.addTransition(state);
  508. if (!N)
  509. return;
  510. // Generate the error reports.
  511. for (AllocationPairVec::iterator I = Errors.begin(), E = Errors.end();
  512. I != E; ++I) {
  513. Ctx.EmitReport(generateAllocatedDataNotReleasedReport(*I, N));
  514. }
  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 0;
  524. const AllocationState *ASPrev = PrevN->getState()->get<AllocatedData>(Sym);
  525. if (ASPrev)
  526. return 0;
  527. // (!ASPrev && AS) ~ We started tracking symbol in node N, it must be the
  528. // allocation site.
  529. const CallExpr *CE = cast<CallExpr>(cast<StmtPoint>(N->getLocation())
  530. .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. }