StackAddrEscapeChecker.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. //=== StackAddrEscapeChecker.cpp ----------------------------------*- C++ -*--//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file defines stack address leak checker, which checks if an invalid
  10. // stack address is stored into a global or heap location. See CERT DCL30-C.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/AST/ExprCXX.h"
  14. #include "clang/Basic/SourceManager.h"
  15. #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
  16. #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
  17. #include "clang/StaticAnalyzer/Core/Checker.h"
  18. #include "clang/StaticAnalyzer/Core/CheckerManager.h"
  19. #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
  20. #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
  21. #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
  22. #include "llvm/ADT/SmallString.h"
  23. #include "llvm/Support/raw_ostream.h"
  24. using namespace clang;
  25. using namespace ento;
  26. namespace {
  27. class StackAddrEscapeChecker
  28. : public Checker<check::PreCall, check::PreStmt<ReturnStmt>,
  29. check::EndFunction> {
  30. mutable IdentifierInfo *dispatch_semaphore_tII;
  31. mutable std::unique_ptr<BuiltinBug> BT_stackleak;
  32. mutable std::unique_ptr<BuiltinBug> BT_returnstack;
  33. mutable std::unique_ptr<BuiltinBug> BT_capturedstackasync;
  34. mutable std::unique_ptr<BuiltinBug> BT_capturedstackret;
  35. public:
  36. enum CheckKind {
  37. CK_StackAddrEscapeChecker,
  38. CK_StackAddrAsyncEscapeChecker,
  39. CK_NumCheckKinds
  40. };
  41. bool ChecksEnabled[CK_NumCheckKinds] = {false};
  42. CheckerNameRef CheckNames[CK_NumCheckKinds];
  43. void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
  44. void checkPreStmt(const ReturnStmt *RS, CheckerContext &C) const;
  45. void checkEndFunction(const ReturnStmt *RS, CheckerContext &Ctx) const;
  46. private:
  47. void checkReturnedBlockCaptures(const BlockDataRegion &B,
  48. CheckerContext &C) const;
  49. void checkAsyncExecutedBlockCaptures(const BlockDataRegion &B,
  50. CheckerContext &C) const;
  51. void EmitStackError(CheckerContext &C, const MemRegion *R,
  52. const Expr *RetE) const;
  53. bool isSemaphoreCaptured(const BlockDecl &B) const;
  54. static SourceRange genName(raw_ostream &os, const MemRegion *R,
  55. ASTContext &Ctx);
  56. static SmallVector<const MemRegion *, 4>
  57. getCapturedStackRegions(const BlockDataRegion &B, CheckerContext &C);
  58. static bool isNotInCurrentFrame(const MemRegion *R, CheckerContext &C);
  59. };
  60. } // namespace
  61. SourceRange StackAddrEscapeChecker::genName(raw_ostream &os, const MemRegion *R,
  62. ASTContext &Ctx) {
  63. // Get the base region, stripping away fields and elements.
  64. R = R->getBaseRegion();
  65. SourceManager &SM = Ctx.getSourceManager();
  66. SourceRange range;
  67. os << "Address of ";
  68. // Check if the region is a compound literal.
  69. if (const auto *CR = dyn_cast<CompoundLiteralRegion>(R)) {
  70. const CompoundLiteralExpr *CL = CR->getLiteralExpr();
  71. os << "stack memory associated with a compound literal "
  72. "declared on line "
  73. << SM.getExpansionLineNumber(CL->getBeginLoc()) << " returned to caller";
  74. range = CL->getSourceRange();
  75. } else if (const auto *AR = dyn_cast<AllocaRegion>(R)) {
  76. const Expr *ARE = AR->getExpr();
  77. SourceLocation L = ARE->getBeginLoc();
  78. range = ARE->getSourceRange();
  79. os << "stack memory allocated by call to alloca() on line "
  80. << SM.getExpansionLineNumber(L);
  81. } else if (const auto *BR = dyn_cast<BlockDataRegion>(R)) {
  82. const BlockDecl *BD = BR->getCodeRegion()->getDecl();
  83. SourceLocation L = BD->getBeginLoc();
  84. range = BD->getSourceRange();
  85. os << "stack-allocated block declared on line "
  86. << SM.getExpansionLineNumber(L);
  87. } else if (const auto *VR = dyn_cast<VarRegion>(R)) {
  88. os << "stack memory associated with local variable '" << VR->getString()
  89. << '\'';
  90. range = VR->getDecl()->getSourceRange();
  91. } else if (const auto *TOR = dyn_cast<CXXTempObjectRegion>(R)) {
  92. QualType Ty = TOR->getValueType().getLocalUnqualifiedType();
  93. os << "stack memory associated with temporary object of type '";
  94. Ty.print(os, Ctx.getPrintingPolicy());
  95. os << "'";
  96. range = TOR->getExpr()->getSourceRange();
  97. } else {
  98. llvm_unreachable("Invalid region in ReturnStackAddressChecker.");
  99. }
  100. return range;
  101. }
  102. bool StackAddrEscapeChecker::isNotInCurrentFrame(const MemRegion *R,
  103. CheckerContext &C) {
  104. const StackSpaceRegion *S = cast<StackSpaceRegion>(R->getMemorySpace());
  105. return S->getStackFrame() != C.getStackFrame();
  106. }
  107. bool StackAddrEscapeChecker::isSemaphoreCaptured(const BlockDecl &B) const {
  108. if (!dispatch_semaphore_tII)
  109. dispatch_semaphore_tII = &B.getASTContext().Idents.get("dispatch_semaphore_t");
  110. for (const auto &C : B.captures()) {
  111. const auto *T = C.getVariable()->getType()->getAs<TypedefType>();
  112. if (T && T->getDecl()->getIdentifier() == dispatch_semaphore_tII)
  113. return true;
  114. }
  115. return false;
  116. }
  117. SmallVector<const MemRegion *, 4>
  118. StackAddrEscapeChecker::getCapturedStackRegions(const BlockDataRegion &B,
  119. CheckerContext &C) {
  120. SmallVector<const MemRegion *, 4> Regions;
  121. BlockDataRegion::referenced_vars_iterator I = B.referenced_vars_begin();
  122. BlockDataRegion::referenced_vars_iterator E = B.referenced_vars_end();
  123. for (; I != E; ++I) {
  124. SVal Val = C.getState()->getSVal(I.getCapturedRegion());
  125. const MemRegion *Region = Val.getAsRegion();
  126. if (Region && isa<StackSpaceRegion>(Region->getMemorySpace()))
  127. Regions.push_back(Region);
  128. }
  129. return Regions;
  130. }
  131. void StackAddrEscapeChecker::EmitStackError(CheckerContext &C,
  132. const MemRegion *R,
  133. const Expr *RetE) const {
  134. ExplodedNode *N = C.generateNonFatalErrorNode();
  135. if (!N)
  136. return;
  137. if (!BT_returnstack)
  138. BT_returnstack = std::make_unique<BuiltinBug>(
  139. CheckNames[CK_StackAddrEscapeChecker],
  140. "Return of address to stack-allocated memory");
  141. // Generate a report for this bug.
  142. SmallString<128> buf;
  143. llvm::raw_svector_ostream os(buf);
  144. SourceRange range = genName(os, R, C.getASTContext());
  145. os << " returned to caller";
  146. auto report =
  147. std::make_unique<PathSensitiveBugReport>(*BT_returnstack, os.str(), N);
  148. report->addRange(RetE->getSourceRange());
  149. if (range.isValid())
  150. report->addRange(range);
  151. C.emitReport(std::move(report));
  152. }
  153. void StackAddrEscapeChecker::checkAsyncExecutedBlockCaptures(
  154. const BlockDataRegion &B, CheckerContext &C) const {
  155. // There is a not-too-uncommon idiom
  156. // where a block passed to dispatch_async captures a semaphore
  157. // and then the thread (which called dispatch_async) is blocked on waiting
  158. // for the completion of the execution of the block
  159. // via dispatch_semaphore_wait. To avoid false-positives (for now)
  160. // we ignore all the blocks which have captured
  161. // a variable of the type "dispatch_semaphore_t".
  162. if (isSemaphoreCaptured(*B.getDecl()))
  163. return;
  164. for (const MemRegion *Region : getCapturedStackRegions(B, C)) {
  165. // The block passed to dispatch_async may capture another block
  166. // created on the stack. However, there is no leak in this situaton,
  167. // no matter if ARC or no ARC is enabled:
  168. // dispatch_async copies the passed "outer" block (via Block_copy)
  169. // and if the block has captured another "inner" block,
  170. // the "inner" block will be copied as well.
  171. if (isa<BlockDataRegion>(Region))
  172. continue;
  173. ExplodedNode *N = C.generateNonFatalErrorNode();
  174. if (!N)
  175. continue;
  176. if (!BT_capturedstackasync)
  177. BT_capturedstackasync = std::make_unique<BuiltinBug>(
  178. CheckNames[CK_StackAddrAsyncEscapeChecker],
  179. "Address of stack-allocated memory is captured");
  180. SmallString<128> Buf;
  181. llvm::raw_svector_ostream Out(Buf);
  182. SourceRange Range = genName(Out, Region, C.getASTContext());
  183. Out << " is captured by an asynchronously-executed block";
  184. auto Report = std::make_unique<PathSensitiveBugReport>(
  185. *BT_capturedstackasync, Out.str(), N);
  186. if (Range.isValid())
  187. Report->addRange(Range);
  188. C.emitReport(std::move(Report));
  189. }
  190. }
  191. void StackAddrEscapeChecker::checkReturnedBlockCaptures(
  192. const BlockDataRegion &B, CheckerContext &C) const {
  193. for (const MemRegion *Region : getCapturedStackRegions(B, C)) {
  194. if (isNotInCurrentFrame(Region, C))
  195. continue;
  196. ExplodedNode *N = C.generateNonFatalErrorNode();
  197. if (!N)
  198. continue;
  199. if (!BT_capturedstackret)
  200. BT_capturedstackret = std::make_unique<BuiltinBug>(
  201. CheckNames[CK_StackAddrEscapeChecker],
  202. "Address of stack-allocated memory is captured");
  203. SmallString<128> Buf;
  204. llvm::raw_svector_ostream Out(Buf);
  205. SourceRange Range = genName(Out, Region, C.getASTContext());
  206. Out << " is captured by a returned block";
  207. auto Report = std::make_unique<PathSensitiveBugReport>(*BT_capturedstackret,
  208. Out.str(), N);
  209. if (Range.isValid())
  210. Report->addRange(Range);
  211. C.emitReport(std::move(Report));
  212. }
  213. }
  214. void StackAddrEscapeChecker::checkPreCall(const CallEvent &Call,
  215. CheckerContext &C) const {
  216. if (!ChecksEnabled[CK_StackAddrAsyncEscapeChecker])
  217. return;
  218. if (!Call.isGlobalCFunction("dispatch_after") &&
  219. !Call.isGlobalCFunction("dispatch_async"))
  220. return;
  221. for (unsigned Idx = 0, NumArgs = Call.getNumArgs(); Idx < NumArgs; ++Idx) {
  222. if (const BlockDataRegion *B = dyn_cast_or_null<BlockDataRegion>(
  223. Call.getArgSVal(Idx).getAsRegion()))
  224. checkAsyncExecutedBlockCaptures(*B, C);
  225. }
  226. }
  227. void StackAddrEscapeChecker::checkPreStmt(const ReturnStmt *RS,
  228. CheckerContext &C) const {
  229. if (!ChecksEnabled[CK_StackAddrEscapeChecker])
  230. return;
  231. const Expr *RetE = RS->getRetValue();
  232. if (!RetE)
  233. return;
  234. RetE = RetE->IgnoreParens();
  235. SVal V = C.getSVal(RetE);
  236. const MemRegion *R = V.getAsRegion();
  237. if (!R)
  238. return;
  239. if (const BlockDataRegion *B = dyn_cast<BlockDataRegion>(R))
  240. checkReturnedBlockCaptures(*B, C);
  241. if (!isa<StackSpaceRegion>(R->getMemorySpace()) || isNotInCurrentFrame(R, C))
  242. return;
  243. // Returning a record by value is fine. (In this case, the returned
  244. // expression will be a copy-constructor, possibly wrapped in an
  245. // ExprWithCleanups node.)
  246. if (const ExprWithCleanups *Cleanup = dyn_cast<ExprWithCleanups>(RetE))
  247. RetE = Cleanup->getSubExpr();
  248. if (isa<CXXConstructExpr>(RetE) && RetE->getType()->isRecordType())
  249. return;
  250. // The CK_CopyAndAutoreleaseBlockObject cast causes the block to be copied
  251. // so the stack address is not escaping here.
  252. if (const auto *ICE = dyn_cast<ImplicitCastExpr>(RetE)) {
  253. if (isa<BlockDataRegion>(R) &&
  254. ICE->getCastKind() == CK_CopyAndAutoreleaseBlockObject) {
  255. return;
  256. }
  257. }
  258. EmitStackError(C, R, RetE);
  259. }
  260. void StackAddrEscapeChecker::checkEndFunction(const ReturnStmt *RS,
  261. CheckerContext &Ctx) const {
  262. if (!ChecksEnabled[CK_StackAddrEscapeChecker])
  263. return;
  264. ProgramStateRef State = Ctx.getState();
  265. // Iterate over all bindings to global variables and see if it contains
  266. // a memory region in the stack space.
  267. class CallBack : public StoreManager::BindingsHandler {
  268. private:
  269. CheckerContext &Ctx;
  270. const StackFrameContext *PoppedFrame;
  271. /// Look for stack variables referring to popped stack variables.
  272. /// Returns true only if it found some dangling stack variables
  273. /// referred by an other stack variable from different stack frame.
  274. bool checkForDanglingStackVariable(const MemRegion *Referrer,
  275. const MemRegion *Referred) {
  276. const auto *ReferrerMemSpace =
  277. Referrer->getMemorySpace()->getAs<StackSpaceRegion>();
  278. const auto *ReferredMemSpace =
  279. Referred->getMemorySpace()->getAs<StackSpaceRegion>();
  280. if (!ReferrerMemSpace || !ReferredMemSpace)
  281. return false;
  282. const auto *ReferrerFrame = ReferrerMemSpace->getStackFrame();
  283. const auto *ReferredFrame = ReferredMemSpace->getStackFrame();
  284. if (ReferrerMemSpace && ReferredMemSpace) {
  285. if (ReferredFrame == PoppedFrame &&
  286. ReferrerFrame->isParentOf(PoppedFrame)) {
  287. V.emplace_back(Referrer, Referred);
  288. return true;
  289. }
  290. }
  291. return false;
  292. }
  293. public:
  294. SmallVector<std::pair<const MemRegion *, const MemRegion *>, 10> V;
  295. CallBack(CheckerContext &CC) : Ctx(CC), PoppedFrame(CC.getStackFrame()) {}
  296. bool HandleBinding(StoreManager &SMgr, Store S, const MemRegion *Region,
  297. SVal Val) override {
  298. const MemRegion *VR = Val.getAsRegion();
  299. if (!VR)
  300. return true;
  301. if (checkForDanglingStackVariable(Region, VR))
  302. return true;
  303. // Check the globals for the same.
  304. if (!isa<GlobalsSpaceRegion>(Region->getMemorySpace()))
  305. return true;
  306. if (VR && VR->hasStackStorage() && !isNotInCurrentFrame(VR, Ctx))
  307. V.emplace_back(Region, VR);
  308. return true;
  309. }
  310. };
  311. CallBack Cb(Ctx);
  312. State->getStateManager().getStoreManager().iterBindings(State->getStore(),
  313. Cb);
  314. if (Cb.V.empty())
  315. return;
  316. // Generate an error node.
  317. ExplodedNode *N = Ctx.generateNonFatalErrorNode(State);
  318. if (!N)
  319. return;
  320. if (!BT_stackleak)
  321. BT_stackleak = std::make_unique<BuiltinBug>(
  322. CheckNames[CK_StackAddrEscapeChecker],
  323. "Stack address stored into global variable",
  324. "Stack address was saved into a global variable. "
  325. "This is dangerous because the address will become "
  326. "invalid after returning from the function");
  327. for (const auto &P : Cb.V) {
  328. const MemRegion *Referrer = P.first;
  329. const MemRegion *Referred = P.second;
  330. // Generate a report for this bug.
  331. const StringRef CommonSuffix =
  332. "upon returning to the caller. This will be a dangling reference";
  333. SmallString<128> Buf;
  334. llvm::raw_svector_ostream Out(Buf);
  335. const SourceRange Range = genName(Out, Referred, Ctx.getASTContext());
  336. if (isa<CXXTempObjectRegion>(Referrer)) {
  337. Out << " is still referred to by a temporary object on the stack "
  338. << CommonSuffix;
  339. auto Report =
  340. std::make_unique<PathSensitiveBugReport>(*BT_stackleak, Out.str(), N);
  341. Ctx.emitReport(std::move(Report));
  342. return;
  343. }
  344. const StringRef ReferrerMemorySpace = [](const MemSpaceRegion *Space) {
  345. if (isa<StaticGlobalSpaceRegion>(Space))
  346. return "static";
  347. if (isa<GlobalsSpaceRegion>(Space))
  348. return "global";
  349. assert(isa<StackSpaceRegion>(Space));
  350. return "stack";
  351. }(Referrer->getMemorySpace());
  352. // This cast supposed to succeed.
  353. const VarRegion *ReferrerVar = cast<VarRegion>(Referrer->getBaseRegion());
  354. const std::string ReferrerVarName =
  355. ReferrerVar->getDecl()->getDeclName().getAsString();
  356. Out << " is still referred to by the " << ReferrerMemorySpace
  357. << " variable '" << ReferrerVarName << "' " << CommonSuffix;
  358. auto Report =
  359. std::make_unique<PathSensitiveBugReport>(*BT_stackleak, Out.str(), N);
  360. if (Range.isValid())
  361. Report->addRange(Range);
  362. Ctx.emitReport(std::move(Report));
  363. }
  364. }
  365. void ento::registerStackAddrEscapeBase(CheckerManager &mgr) {
  366. mgr.registerChecker<StackAddrEscapeChecker>();
  367. }
  368. bool ento::shouldRegisterStackAddrEscapeBase(const CheckerManager &mgr) {
  369. return true;
  370. }
  371. #define REGISTER_CHECKER(name) \
  372. void ento::register##name(CheckerManager &Mgr) { \
  373. StackAddrEscapeChecker *Chk = Mgr.getChecker<StackAddrEscapeChecker>(); \
  374. Chk->ChecksEnabled[StackAddrEscapeChecker::CK_##name] = true; \
  375. Chk->CheckNames[StackAddrEscapeChecker::CK_##name] = \
  376. Mgr.getCurrentCheckerName(); \
  377. } \
  378. \
  379. bool ento::shouldRegister##name(const CheckerManager &mgr) { return true; }
  380. REGISTER_CHECKER(StackAddrEscapeChecker)
  381. REGISTER_CHECKER(StackAddrAsyncEscapeChecker)