StackProtector.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  1. //===- StackProtector.cpp - Stack Protector Insertion ---------------------===//
  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 pass inserts stack protectors into functions which need them. A variable
  10. // with a random value in it is stored onto the stack before the local variables
  11. // are allocated. Upon exiting the block, the stored value is checked. If it's
  12. // changed, then there was some sort of violation and the program aborts.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #include "llvm/CodeGen/StackProtector.h"
  16. #include "llvm/ADT/SmallPtrSet.h"
  17. #include "llvm/ADT/Statistic.h"
  18. #include "llvm/Analysis/BranchProbabilityInfo.h"
  19. #include "llvm/Analysis/CaptureTracking.h"
  20. #include "llvm/Analysis/EHPersonalities.h"
  21. #include "llvm/Analysis/OptimizationRemarkEmitter.h"
  22. #include "llvm/CodeGen/Passes.h"
  23. #include "llvm/CodeGen/TargetLowering.h"
  24. #include "llvm/CodeGen/TargetPassConfig.h"
  25. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  26. #include "llvm/IR/Attributes.h"
  27. #include "llvm/IR/BasicBlock.h"
  28. #include "llvm/IR/Constants.h"
  29. #include "llvm/IR/DataLayout.h"
  30. #include "llvm/IR/DebugInfo.h"
  31. #include "llvm/IR/DebugLoc.h"
  32. #include "llvm/IR/DerivedTypes.h"
  33. #include "llvm/IR/Dominators.h"
  34. #include "llvm/IR/Function.h"
  35. #include "llvm/IR/IRBuilder.h"
  36. #include "llvm/IR/Instruction.h"
  37. #include "llvm/IR/Instructions.h"
  38. #include "llvm/IR/IntrinsicInst.h"
  39. #include "llvm/IR/Intrinsics.h"
  40. #include "llvm/IR/MDBuilder.h"
  41. #include "llvm/IR/Module.h"
  42. #include "llvm/IR/Type.h"
  43. #include "llvm/IR/User.h"
  44. #include "llvm/Pass.h"
  45. #include "llvm/Support/Casting.h"
  46. #include "llvm/Support/CommandLine.h"
  47. #include "llvm/Target/TargetMachine.h"
  48. #include "llvm/Target/TargetOptions.h"
  49. #include <utility>
  50. using namespace llvm;
  51. #define DEBUG_TYPE "stack-protector"
  52. STATISTIC(NumFunProtected, "Number of functions protected");
  53. STATISTIC(NumAddrTaken, "Number of local variables that have their address"
  54. " taken.");
  55. static cl::opt<bool> EnableSelectionDAGSP("enable-selectiondag-sp",
  56. cl::init(true), cl::Hidden);
  57. char StackProtector::ID = 0;
  58. INITIALIZE_PASS_BEGIN(StackProtector, DEBUG_TYPE,
  59. "Insert stack protectors", false, true)
  60. INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
  61. INITIALIZE_PASS_END(StackProtector, DEBUG_TYPE,
  62. "Insert stack protectors", false, true)
  63. FunctionPass *llvm::createStackProtectorPass() { return new StackProtector(); }
  64. void StackProtector::getAnalysisUsage(AnalysisUsage &AU) const {
  65. AU.addRequired<TargetPassConfig>();
  66. AU.addPreserved<DominatorTreeWrapperPass>();
  67. }
  68. bool StackProtector::runOnFunction(Function &Fn) {
  69. F = &Fn;
  70. M = F->getParent();
  71. DominatorTreeWrapperPass *DTWP =
  72. getAnalysisIfAvailable<DominatorTreeWrapperPass>();
  73. DT = DTWP ? &DTWP->getDomTree() : nullptr;
  74. TM = &getAnalysis<TargetPassConfig>().getTM<TargetMachine>();
  75. Trip = TM->getTargetTriple();
  76. TLI = TM->getSubtargetImpl(Fn)->getTargetLowering();
  77. HasPrologue = false;
  78. HasIRCheck = false;
  79. Attribute Attr = Fn.getFnAttribute("stack-protector-buffer-size");
  80. if (Attr.isStringAttribute() &&
  81. Attr.getValueAsString().getAsInteger(10, SSPBufferSize))
  82. return false; // Invalid integer string
  83. if (!RequiresStackProtector())
  84. return false;
  85. // TODO(etienneb): Functions with funclets are not correctly supported now.
  86. // Do nothing if this is funclet-based personality.
  87. if (Fn.hasPersonalityFn()) {
  88. EHPersonality Personality = classifyEHPersonality(Fn.getPersonalityFn());
  89. if (isFuncletEHPersonality(Personality))
  90. return false;
  91. }
  92. ++NumFunProtected;
  93. return InsertStackProtectors();
  94. }
  95. /// \param [out] IsLarge is set to true if a protectable array is found and
  96. /// it is "large" ( >= ssp-buffer-size). In the case of a structure with
  97. /// multiple arrays, this gets set if any of them is large.
  98. bool StackProtector::ContainsProtectableArray(Type *Ty, bool &IsLarge,
  99. bool Strong,
  100. bool InStruct) const {
  101. if (!Ty)
  102. return false;
  103. if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
  104. if (!AT->getElementType()->isIntegerTy(8)) {
  105. // If we're on a non-Darwin platform or we're inside of a structure, don't
  106. // add stack protectors unless the array is a character array.
  107. // However, in strong mode any array, regardless of type and size,
  108. // triggers a protector.
  109. if (!Strong && (InStruct || !Trip.isOSDarwin()))
  110. return false;
  111. }
  112. // If an array has more than SSPBufferSize bytes of allocated space, then we
  113. // emit stack protectors.
  114. if (SSPBufferSize <= M->getDataLayout().getTypeAllocSize(AT)) {
  115. IsLarge = true;
  116. return true;
  117. }
  118. if (Strong)
  119. // Require a protector for all arrays in strong mode
  120. return true;
  121. }
  122. const StructType *ST = dyn_cast<StructType>(Ty);
  123. if (!ST)
  124. return false;
  125. bool NeedsProtector = false;
  126. for (StructType::element_iterator I = ST->element_begin(),
  127. E = ST->element_end();
  128. I != E; ++I)
  129. if (ContainsProtectableArray(*I, IsLarge, Strong, true)) {
  130. // If the element is a protectable array and is large (>= SSPBufferSize)
  131. // then we are done. If the protectable array is not large, then
  132. // keep looking in case a subsequent element is a large array.
  133. if (IsLarge)
  134. return true;
  135. NeedsProtector = true;
  136. }
  137. return NeedsProtector;
  138. }
  139. /// Search for the first call to the llvm.stackprotector intrinsic and return it
  140. /// if present.
  141. static const CallInst *findStackProtectorIntrinsic(Function &F) {
  142. for (const BasicBlock &BB : F)
  143. for (const Instruction &I : BB)
  144. if (const CallInst *CI = dyn_cast<CallInst>(&I))
  145. if (CI->getCalledFunction() ==
  146. Intrinsic::getDeclaration(F.getParent(), Intrinsic::stackprotector))
  147. return CI;
  148. return nullptr;
  149. }
  150. /// Check whether or not this function needs a stack protector based
  151. /// upon the stack protector level.
  152. ///
  153. /// We use two heuristics: a standard (ssp) and strong (sspstrong).
  154. /// The standard heuristic which will add a guard variable to functions that
  155. /// call alloca with a either a variable size or a size >= SSPBufferSize,
  156. /// functions with character buffers larger than SSPBufferSize, and functions
  157. /// with aggregates containing character buffers larger than SSPBufferSize. The
  158. /// strong heuristic will add a guard variables to functions that call alloca
  159. /// regardless of size, functions with any buffer regardless of type and size,
  160. /// functions with aggregates that contain any buffer regardless of type and
  161. /// size, and functions that contain stack-based variables that have had their
  162. /// address taken.
  163. bool StackProtector::RequiresStackProtector() {
  164. bool Strong = false;
  165. bool NeedsProtector = false;
  166. HasPrologue = findStackProtectorIntrinsic(*F);
  167. if (F->hasFnAttribute(Attribute::SafeStack))
  168. return false;
  169. // We are constructing the OptimizationRemarkEmitter on the fly rather than
  170. // using the analysis pass to avoid building DominatorTree and LoopInfo which
  171. // are not available this late in the IR pipeline.
  172. OptimizationRemarkEmitter ORE(F);
  173. if (F->hasFnAttribute(Attribute::StackProtectReq)) {
  174. ORE.emit([&]() {
  175. return OptimizationRemark(DEBUG_TYPE, "StackProtectorRequested", F)
  176. << "Stack protection applied to function "
  177. << ore::NV("Function", F)
  178. << " due to a function attribute or command-line switch";
  179. });
  180. NeedsProtector = true;
  181. Strong = true; // Use the same heuristic as strong to determine SSPLayout
  182. } else if (F->hasFnAttribute(Attribute::StackProtectStrong))
  183. Strong = true;
  184. else if (HasPrologue)
  185. NeedsProtector = true;
  186. else if (!F->hasFnAttribute(Attribute::StackProtect))
  187. return false;
  188. for (const BasicBlock &BB : *F) {
  189. for (const Instruction &I : BB) {
  190. if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
  191. if (AI->isArrayAllocation()) {
  192. auto RemarkBuilder = [&]() {
  193. return OptimizationRemark(DEBUG_TYPE, "StackProtectorAllocaOrArray",
  194. &I)
  195. << "Stack protection applied to function "
  196. << ore::NV("Function", F)
  197. << " due to a call to alloca or use of a variable length "
  198. "array";
  199. };
  200. if (const auto *CI = dyn_cast<ConstantInt>(AI->getArraySize())) {
  201. if (CI->getLimitedValue(SSPBufferSize) >= SSPBufferSize) {
  202. // A call to alloca with size >= SSPBufferSize requires
  203. // stack protectors.
  204. Layout.insert(std::make_pair(AI,
  205. MachineFrameInfo::SSPLK_LargeArray));
  206. ORE.emit(RemarkBuilder);
  207. NeedsProtector = true;
  208. } else if (Strong) {
  209. // Require protectors for all alloca calls in strong mode.
  210. Layout.insert(std::make_pair(AI,
  211. MachineFrameInfo::SSPLK_SmallArray));
  212. ORE.emit(RemarkBuilder);
  213. NeedsProtector = true;
  214. }
  215. } else {
  216. // A call to alloca with a variable size requires protectors.
  217. Layout.insert(std::make_pair(AI,
  218. MachineFrameInfo::SSPLK_LargeArray));
  219. ORE.emit(RemarkBuilder);
  220. NeedsProtector = true;
  221. }
  222. continue;
  223. }
  224. bool IsLarge = false;
  225. if (ContainsProtectableArray(AI->getAllocatedType(), IsLarge, Strong)) {
  226. Layout.insert(std::make_pair(AI, IsLarge
  227. ? MachineFrameInfo::SSPLK_LargeArray
  228. : MachineFrameInfo::SSPLK_SmallArray));
  229. ORE.emit([&]() {
  230. return OptimizationRemark(DEBUG_TYPE, "StackProtectorBuffer", &I)
  231. << "Stack protection applied to function "
  232. << ore::NV("Function", F)
  233. << " due to a stack allocated buffer or struct containing a "
  234. "buffer";
  235. });
  236. NeedsProtector = true;
  237. continue;
  238. }
  239. if (Strong && PointerMayBeCaptured(AI,
  240. /* ReturnCaptures */ false,
  241. /* StoreCaptures */ true)) {
  242. ++NumAddrTaken;
  243. Layout.insert(std::make_pair(AI, MachineFrameInfo::SSPLK_AddrOf));
  244. ORE.emit([&]() {
  245. return OptimizationRemark(DEBUG_TYPE, "StackProtectorAddressTaken",
  246. &I)
  247. << "Stack protection applied to function "
  248. << ore::NV("Function", F)
  249. << " due to the address of a local variable being taken";
  250. });
  251. NeedsProtector = true;
  252. }
  253. }
  254. }
  255. }
  256. return NeedsProtector;
  257. }
  258. /// Create a stack guard loading and populate whether SelectionDAG SSP is
  259. /// supported.
  260. static Value *getStackGuard(const TargetLoweringBase *TLI, Module *M,
  261. IRBuilder<> &B,
  262. bool *SupportsSelectionDAGSP = nullptr) {
  263. if (Value *Guard = TLI->getIRStackGuard(B))
  264. return B.CreateLoad(B.getInt8PtrTy(), Guard, true, "StackGuard");
  265. // Use SelectionDAG SSP handling, since there isn't an IR guard.
  266. //
  267. // This is more or less weird, since we optionally output whether we
  268. // should perform a SelectionDAG SP here. The reason is that it's strictly
  269. // defined as !TLI->getIRStackGuard(B), where getIRStackGuard is also
  270. // mutating. There is no way to get this bit without mutating the IR, so
  271. // getting this bit has to happen in this right time.
  272. //
  273. // We could have define a new function TLI::supportsSelectionDAGSP(), but that
  274. // will put more burden on the backends' overriding work, especially when it
  275. // actually conveys the same information getIRStackGuard() already gives.
  276. if (SupportsSelectionDAGSP)
  277. *SupportsSelectionDAGSP = true;
  278. TLI->insertSSPDeclarations(*M);
  279. return B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackguard));
  280. }
  281. /// Insert code into the entry block that stores the stack guard
  282. /// variable onto the stack:
  283. ///
  284. /// entry:
  285. /// StackGuardSlot = alloca i8*
  286. /// StackGuard = <stack guard>
  287. /// call void @llvm.stackprotector(StackGuard, StackGuardSlot)
  288. ///
  289. /// Returns true if the platform/triple supports the stackprotectorcreate pseudo
  290. /// node.
  291. static bool CreatePrologue(Function *F, Module *M, ReturnInst *RI,
  292. const TargetLoweringBase *TLI, AllocaInst *&AI) {
  293. bool SupportsSelectionDAGSP = false;
  294. IRBuilder<> B(&F->getEntryBlock().front());
  295. PointerType *PtrTy = Type::getInt8PtrTy(RI->getContext());
  296. AI = B.CreateAlloca(PtrTy, nullptr, "StackGuardSlot");
  297. Value *GuardSlot = getStackGuard(TLI, M, B, &SupportsSelectionDAGSP);
  298. B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackprotector),
  299. {GuardSlot, AI});
  300. return SupportsSelectionDAGSP;
  301. }
  302. /// InsertStackProtectors - Insert code into the prologue and epilogue of the
  303. /// function.
  304. ///
  305. /// - The prologue code loads and stores the stack guard onto the stack.
  306. /// - The epilogue checks the value stored in the prologue against the original
  307. /// value. It calls __stack_chk_fail if they differ.
  308. bool StackProtector::InsertStackProtectors() {
  309. // If the target wants to XOR the frame pointer into the guard value, it's
  310. // impossible to emit the check in IR, so the target *must* support stack
  311. // protection in SDAG.
  312. bool SupportsSelectionDAGSP =
  313. TLI->useStackGuardXorFP() ||
  314. (EnableSelectionDAGSP && !TM->Options.EnableFastISel &&
  315. !TM->Options.EnableGlobalISel);
  316. AllocaInst *AI = nullptr; // Place on stack that stores the stack guard.
  317. for (Function::iterator I = F->begin(), E = F->end(); I != E;) {
  318. BasicBlock *BB = &*I++;
  319. ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
  320. if (!RI)
  321. continue;
  322. // Generate prologue instrumentation if not already generated.
  323. if (!HasPrologue) {
  324. HasPrologue = true;
  325. SupportsSelectionDAGSP &= CreatePrologue(F, M, RI, TLI, AI);
  326. }
  327. // SelectionDAG based code generation. Nothing else needs to be done here.
  328. // The epilogue instrumentation is postponed to SelectionDAG.
  329. if (SupportsSelectionDAGSP)
  330. break;
  331. // Find the stack guard slot if the prologue was not created by this pass
  332. // itself via a previous call to CreatePrologue().
  333. if (!AI) {
  334. const CallInst *SPCall = findStackProtectorIntrinsic(*F);
  335. assert(SPCall && "Call to llvm.stackprotector is missing");
  336. AI = cast<AllocaInst>(SPCall->getArgOperand(1));
  337. }
  338. // Set HasIRCheck to true, so that SelectionDAG will not generate its own
  339. // version. SelectionDAG called 'shouldEmitSDCheck' to check whether
  340. // instrumentation has already been generated.
  341. HasIRCheck = true;
  342. // Generate epilogue instrumentation. The epilogue intrumentation can be
  343. // function-based or inlined depending on which mechanism the target is
  344. // providing.
  345. if (Function *GuardCheck = TLI->getSSPStackGuardCheck(*M)) {
  346. // Generate the function-based epilogue instrumentation.
  347. // The target provides a guard check function, generate a call to it.
  348. IRBuilder<> B(RI);
  349. LoadInst *Guard = B.CreateLoad(B.getInt8PtrTy(), AI, true, "Guard");
  350. CallInst *Call = B.CreateCall(GuardCheck, {Guard});
  351. Call->setAttributes(GuardCheck->getAttributes());
  352. Call->setCallingConv(GuardCheck->getCallingConv());
  353. } else {
  354. // Generate the epilogue with inline instrumentation.
  355. // If we do not support SelectionDAG based tail calls, generate IR level
  356. // tail calls.
  357. //
  358. // For each block with a return instruction, convert this:
  359. //
  360. // return:
  361. // ...
  362. // ret ...
  363. //
  364. // into this:
  365. //
  366. // return:
  367. // ...
  368. // %1 = <stack guard>
  369. // %2 = load StackGuardSlot
  370. // %3 = cmp i1 %1, %2
  371. // br i1 %3, label %SP_return, label %CallStackCheckFailBlk
  372. //
  373. // SP_return:
  374. // ret ...
  375. //
  376. // CallStackCheckFailBlk:
  377. // call void @__stack_chk_fail()
  378. // unreachable
  379. // Create the FailBB. We duplicate the BB every time since the MI tail
  380. // merge pass will merge together all of the various BB into one including
  381. // fail BB generated by the stack protector pseudo instruction.
  382. BasicBlock *FailBB = CreateFailBB();
  383. // Split the basic block before the return instruction.
  384. BasicBlock *NewBB = BB->splitBasicBlock(RI->getIterator(), "SP_return");
  385. // Update the dominator tree if we need to.
  386. if (DT && DT->isReachableFromEntry(BB)) {
  387. DT->addNewBlock(NewBB, BB);
  388. DT->addNewBlock(FailBB, BB);
  389. }
  390. // Remove default branch instruction to the new BB.
  391. BB->getTerminator()->eraseFromParent();
  392. // Move the newly created basic block to the point right after the old
  393. // basic block so that it's in the "fall through" position.
  394. NewBB->moveAfter(BB);
  395. // Generate the stack protector instructions in the old basic block.
  396. IRBuilder<> B(BB);
  397. Value *Guard = getStackGuard(TLI, M, B);
  398. LoadInst *LI2 = B.CreateLoad(B.getInt8PtrTy(), AI, true);
  399. Value *Cmp = B.CreateICmpEQ(Guard, LI2);
  400. auto SuccessProb =
  401. BranchProbabilityInfo::getBranchProbStackProtector(true);
  402. auto FailureProb =
  403. BranchProbabilityInfo::getBranchProbStackProtector(false);
  404. MDNode *Weights = MDBuilder(F->getContext())
  405. .createBranchWeights(SuccessProb.getNumerator(),
  406. FailureProb.getNumerator());
  407. B.CreateCondBr(Cmp, NewBB, FailBB, Weights);
  408. }
  409. }
  410. // Return if we didn't modify any basic blocks. i.e., there are no return
  411. // statements in the function.
  412. return HasPrologue;
  413. }
  414. /// CreateFailBB - Create a basic block to jump to when the stack protector
  415. /// check fails.
  416. BasicBlock *StackProtector::CreateFailBB() {
  417. LLVMContext &Context = F->getContext();
  418. BasicBlock *FailBB = BasicBlock::Create(Context, "CallStackCheckFailBlk", F);
  419. IRBuilder<> B(FailBB);
  420. B.SetCurrentDebugLocation(DebugLoc::get(0, 0, F->getSubprogram()));
  421. if (Trip.isOSOpenBSD()) {
  422. FunctionCallee StackChkFail = M->getOrInsertFunction(
  423. "__stack_smash_handler", Type::getVoidTy(Context),
  424. Type::getInt8PtrTy(Context));
  425. B.CreateCall(StackChkFail, B.CreateGlobalStringPtr(F->getName(), "SSH"));
  426. } else {
  427. FunctionCallee StackChkFail =
  428. M->getOrInsertFunction("__stack_chk_fail", Type::getVoidTy(Context));
  429. B.CreateCall(StackChkFail, {});
  430. }
  431. B.CreateUnreachable();
  432. return FailBB;
  433. }
  434. bool StackProtector::shouldEmitSDCheck(const BasicBlock &BB) const {
  435. return HasPrologue && !HasIRCheck && isa<ReturnInst>(BB.getTerminator());
  436. }
  437. void StackProtector::copyToMachineFrameInfo(MachineFrameInfo &MFI) const {
  438. if (Layout.empty())
  439. return;
  440. for (int I = 0, E = MFI.getObjectIndexEnd(); I != E; ++I) {
  441. if (MFI.isDeadObjectIndex(I))
  442. continue;
  443. const AllocaInst *AI = MFI.getObjectAllocation(I);
  444. if (!AI)
  445. continue;
  446. SSPLayoutMap::const_iterator LI = Layout.find(AI);
  447. if (LI == Layout.end())
  448. continue;
  449. MFI.setObjectSSPLayout(I, LI->second);
  450. }
  451. }