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