StackProtector.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  1. //===- StackProtector.cpp - Stack Protector Insertion ---------------------===//
  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. //
  10. // This pass inserts stack protectors into functions which need them. A variable
  11. // with a random value in it is stored onto the stack before the local variables
  12. // are allocated. Upon exiting the block, the stored value is checked. If it's
  13. // changed, then there was some sort of violation and the program aborts.
  14. //
  15. //===----------------------------------------------------------------------===//
  16. #include "llvm/CodeGen/StackProtector.h"
  17. #include "llvm/ADT/SmallPtrSet.h"
  18. #include "llvm/ADT/Statistic.h"
  19. #include "llvm/Analysis/BranchProbabilityInfo.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. static bool isLifetimeInst(const Instruction *I) {
  140. if (const auto Intrinsic = dyn_cast<IntrinsicInst>(I)) {
  141. const auto Id = Intrinsic->getIntrinsicID();
  142. return Id == Intrinsic::lifetime_start || Id == Intrinsic::lifetime_end;
  143. }
  144. return false;
  145. }
  146. bool StackProtector::HasAddressTaken(const Instruction *AI) {
  147. for (const User *U : AI->users()) {
  148. if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
  149. if (AI == SI->getValueOperand())
  150. return true;
  151. } else if (const PtrToIntInst *SI = dyn_cast<PtrToIntInst>(U)) {
  152. if (AI == SI->getOperand(0))
  153. return true;
  154. } else if (const CallInst *CI = dyn_cast<CallInst>(U)) {
  155. // Ignore intrinsics that are not calls. TODO: Use isLoweredToCall().
  156. if (!isa<DbgInfoIntrinsic>(CI) && !isLifetimeInst(CI))
  157. return true;
  158. } else if (isa<InvokeInst>(U)) {
  159. return true;
  160. } else if (const SelectInst *SI = dyn_cast<SelectInst>(U)) {
  161. if (HasAddressTaken(SI))
  162. return true;
  163. } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
  164. // Keep track of what PHI nodes we have already visited to ensure
  165. // they are only visited once.
  166. if (VisitedPHIs.insert(PN).second)
  167. if (HasAddressTaken(PN))
  168. return true;
  169. } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
  170. if (HasAddressTaken(GEP))
  171. return true;
  172. } else if (const BitCastInst *BI = dyn_cast<BitCastInst>(U)) {
  173. if (HasAddressTaken(BI))
  174. return true;
  175. }
  176. }
  177. return false;
  178. }
  179. /// Check whether or not this function needs a stack protector based
  180. /// upon the stack protector level.
  181. ///
  182. /// We use two heuristics: a standard (ssp) and strong (sspstrong).
  183. /// The standard heuristic which will add a guard variable to functions that
  184. /// call alloca with a either a variable size or a size >= SSPBufferSize,
  185. /// functions with character buffers larger than SSPBufferSize, and functions
  186. /// with aggregates containing character buffers larger than SSPBufferSize. The
  187. /// strong heuristic will add a guard variables to functions that call alloca
  188. /// regardless of size, functions with any buffer regardless of type and size,
  189. /// functions with aggregates that contain any buffer regardless of type and
  190. /// size, and functions that contain stack-based variables that have had their
  191. /// address taken.
  192. bool StackProtector::RequiresStackProtector() {
  193. bool Strong = false;
  194. bool NeedsProtector = false;
  195. for (const BasicBlock &BB : *F)
  196. for (const Instruction &I : BB)
  197. if (const CallInst *CI = dyn_cast<CallInst>(&I))
  198. if (CI->getCalledFunction() ==
  199. Intrinsic::getDeclaration(F->getParent(),
  200. Intrinsic::stackprotector))
  201. HasPrologue = true;
  202. if (F->hasFnAttribute(Attribute::SafeStack))
  203. return false;
  204. // We are constructing the OptimizationRemarkEmitter on the fly rather than
  205. // using the analysis pass to avoid building DominatorTree and LoopInfo which
  206. // are not available this late in the IR pipeline.
  207. OptimizationRemarkEmitter ORE(F);
  208. if (F->hasFnAttribute(Attribute::StackProtectReq)) {
  209. ORE.emit([&]() {
  210. return OptimizationRemark(DEBUG_TYPE, "StackProtectorRequested", F)
  211. << "Stack protection applied to function "
  212. << ore::NV("Function", F)
  213. << " due to a function attribute or command-line switch";
  214. });
  215. NeedsProtector = true;
  216. Strong = true; // Use the same heuristic as strong to determine SSPLayout
  217. } else if (F->hasFnAttribute(Attribute::StackProtectStrong))
  218. Strong = true;
  219. else if (HasPrologue)
  220. NeedsProtector = true;
  221. else if (!F->hasFnAttribute(Attribute::StackProtect))
  222. return false;
  223. for (const BasicBlock &BB : *F) {
  224. for (const Instruction &I : BB) {
  225. if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
  226. if (AI->isArrayAllocation()) {
  227. auto RemarkBuilder = [&]() {
  228. return OptimizationRemark(DEBUG_TYPE, "StackProtectorAllocaOrArray",
  229. &I)
  230. << "Stack protection applied to function "
  231. << ore::NV("Function", F)
  232. << " due to a call to alloca or use of a variable length "
  233. "array";
  234. };
  235. if (const auto *CI = dyn_cast<ConstantInt>(AI->getArraySize())) {
  236. if (CI->getLimitedValue(SSPBufferSize) >= SSPBufferSize) {
  237. // A call to alloca with size >= SSPBufferSize requires
  238. // stack protectors.
  239. Layout.insert(std::make_pair(AI,
  240. MachineFrameInfo::SSPLK_LargeArray));
  241. ORE.emit(RemarkBuilder);
  242. NeedsProtector = true;
  243. } else if (Strong) {
  244. // Require protectors for all alloca calls in strong mode.
  245. Layout.insert(std::make_pair(AI,
  246. MachineFrameInfo::SSPLK_SmallArray));
  247. ORE.emit(RemarkBuilder);
  248. NeedsProtector = true;
  249. }
  250. } else {
  251. // A call to alloca with a variable size requires protectors.
  252. Layout.insert(std::make_pair(AI,
  253. MachineFrameInfo::SSPLK_LargeArray));
  254. ORE.emit(RemarkBuilder);
  255. NeedsProtector = true;
  256. }
  257. continue;
  258. }
  259. bool IsLarge = false;
  260. if (ContainsProtectableArray(AI->getAllocatedType(), IsLarge, Strong)) {
  261. Layout.insert(std::make_pair(AI, IsLarge
  262. ? MachineFrameInfo::SSPLK_LargeArray
  263. : MachineFrameInfo::SSPLK_SmallArray));
  264. ORE.emit([&]() {
  265. return OptimizationRemark(DEBUG_TYPE, "StackProtectorBuffer", &I)
  266. << "Stack protection applied to function "
  267. << ore::NV("Function", F)
  268. << " due to a stack allocated buffer or struct containing a "
  269. "buffer";
  270. });
  271. NeedsProtector = true;
  272. continue;
  273. }
  274. if (Strong && HasAddressTaken(AI)) {
  275. ++NumAddrTaken;
  276. Layout.insert(std::make_pair(AI, MachineFrameInfo::SSPLK_AddrOf));
  277. ORE.emit([&]() {
  278. return OptimizationRemark(DEBUG_TYPE, "StackProtectorAddressTaken",
  279. &I)
  280. << "Stack protection applied to function "
  281. << ore::NV("Function", F)
  282. << " due to the address of a local variable being taken";
  283. });
  284. NeedsProtector = true;
  285. }
  286. }
  287. }
  288. }
  289. return NeedsProtector;
  290. }
  291. /// Create a stack guard loading and populate whether SelectionDAG SSP is
  292. /// supported.
  293. static Value *getStackGuard(const TargetLoweringBase *TLI, Module *M,
  294. IRBuilder<> &B,
  295. bool *SupportsSelectionDAGSP = nullptr) {
  296. if (Value *Guard = TLI->getIRStackGuard(B))
  297. return B.CreateLoad(Guard, true, "StackGuard");
  298. // Use SelectionDAG SSP handling, since there isn't an IR guard.
  299. //
  300. // This is more or less weird, since we optionally output whether we
  301. // should perform a SelectionDAG SP here. The reason is that it's strictly
  302. // defined as !TLI->getIRStackGuard(B), where getIRStackGuard is also
  303. // mutating. There is no way to get this bit without mutating the IR, so
  304. // getting this bit has to happen in this right time.
  305. //
  306. // We could have define a new function TLI::supportsSelectionDAGSP(), but that
  307. // will put more burden on the backends' overriding work, especially when it
  308. // actually conveys the same information getIRStackGuard() already gives.
  309. if (SupportsSelectionDAGSP)
  310. *SupportsSelectionDAGSP = true;
  311. TLI->insertSSPDeclarations(*M);
  312. return B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackguard));
  313. }
  314. /// Insert code into the entry block that stores the stack guard
  315. /// variable onto the stack:
  316. ///
  317. /// entry:
  318. /// StackGuardSlot = alloca i8*
  319. /// StackGuard = <stack guard>
  320. /// call void @llvm.stackprotector(StackGuard, StackGuardSlot)
  321. ///
  322. /// Returns true if the platform/triple supports the stackprotectorcreate pseudo
  323. /// node.
  324. static bool CreatePrologue(Function *F, Module *M, ReturnInst *RI,
  325. const TargetLoweringBase *TLI, AllocaInst *&AI) {
  326. bool SupportsSelectionDAGSP = false;
  327. IRBuilder<> B(&F->getEntryBlock().front());
  328. PointerType *PtrTy = Type::getInt8PtrTy(RI->getContext());
  329. AI = B.CreateAlloca(PtrTy, nullptr, "StackGuardSlot");
  330. Value *GuardSlot = getStackGuard(TLI, M, B, &SupportsSelectionDAGSP);
  331. B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackprotector),
  332. {GuardSlot, AI});
  333. return SupportsSelectionDAGSP;
  334. }
  335. /// InsertStackProtectors - Insert code into the prologue and epilogue of the
  336. /// function.
  337. ///
  338. /// - The prologue code loads and stores the stack guard onto the stack.
  339. /// - The epilogue checks the value stored in the prologue against the original
  340. /// value. It calls __stack_chk_fail if they differ.
  341. bool StackProtector::InsertStackProtectors() {
  342. // If the target wants to XOR the frame pointer into the guard value, it's
  343. // impossible to emit the check in IR, so the target *must* support stack
  344. // protection in SDAG.
  345. bool SupportsSelectionDAGSP =
  346. TLI->useStackGuardXorFP() ||
  347. (EnableSelectionDAGSP && !TM->Options.EnableFastISel);
  348. AllocaInst *AI = nullptr; // Place on stack that stores the stack guard.
  349. for (Function::iterator I = F->begin(), E = F->end(); I != E;) {
  350. BasicBlock *BB = &*I++;
  351. ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
  352. if (!RI)
  353. continue;
  354. // Generate prologue instrumentation if not already generated.
  355. if (!HasPrologue) {
  356. HasPrologue = true;
  357. SupportsSelectionDAGSP &= CreatePrologue(F, M, RI, TLI, AI);
  358. }
  359. // SelectionDAG based code generation. Nothing else needs to be done here.
  360. // The epilogue instrumentation is postponed to SelectionDAG.
  361. if (SupportsSelectionDAGSP)
  362. break;
  363. // Set HasIRCheck to true, so that SelectionDAG will not generate its own
  364. // version. SelectionDAG called 'shouldEmitSDCheck' to check whether
  365. // instrumentation has already been generated.
  366. HasIRCheck = true;
  367. // Generate epilogue instrumentation. The epilogue intrumentation can be
  368. // function-based or inlined depending on which mechanism the target is
  369. // providing.
  370. if (Value* GuardCheck = TLI->getSSPStackGuardCheck(*M)) {
  371. // Generate the function-based epilogue instrumentation.
  372. // The target provides a guard check function, generate a call to it.
  373. IRBuilder<> B(RI);
  374. LoadInst *Guard = B.CreateLoad(AI, true, "Guard");
  375. CallInst *Call = B.CreateCall(GuardCheck, {Guard});
  376. llvm::Function *Function = cast<llvm::Function>(GuardCheck);
  377. Call->setAttributes(Function->getAttributes());
  378. Call->setCallingConv(Function->getCallingConv());
  379. } else {
  380. // Generate the epilogue with inline instrumentation.
  381. // If we do not support SelectionDAG based tail calls, generate IR level
  382. // tail calls.
  383. //
  384. // For each block with a return instruction, convert this:
  385. //
  386. // return:
  387. // ...
  388. // ret ...
  389. //
  390. // into this:
  391. //
  392. // return:
  393. // ...
  394. // %1 = <stack guard>
  395. // %2 = load StackGuardSlot
  396. // %3 = cmp i1 %1, %2
  397. // br i1 %3, label %SP_return, label %CallStackCheckFailBlk
  398. //
  399. // SP_return:
  400. // ret ...
  401. //
  402. // CallStackCheckFailBlk:
  403. // call void @__stack_chk_fail()
  404. // unreachable
  405. // Create the FailBB. We duplicate the BB every time since the MI tail
  406. // merge pass will merge together all of the various BB into one including
  407. // fail BB generated by the stack protector pseudo instruction.
  408. BasicBlock *FailBB = CreateFailBB();
  409. // Split the basic block before the return instruction.
  410. BasicBlock *NewBB = BB->splitBasicBlock(RI->getIterator(), "SP_return");
  411. // Update the dominator tree if we need to.
  412. if (DT && DT->isReachableFromEntry(BB)) {
  413. DT->addNewBlock(NewBB, BB);
  414. DT->addNewBlock(FailBB, BB);
  415. }
  416. // Remove default branch instruction to the new BB.
  417. BB->getTerminator()->eraseFromParent();
  418. // Move the newly created basic block to the point right after the old
  419. // basic block so that it's in the "fall through" position.
  420. NewBB->moveAfter(BB);
  421. // Generate the stack protector instructions in the old basic block.
  422. IRBuilder<> B(BB);
  423. Value *Guard = getStackGuard(TLI, M, B);
  424. LoadInst *LI2 = B.CreateLoad(AI, true);
  425. Value *Cmp = B.CreateICmpEQ(Guard, LI2);
  426. auto SuccessProb =
  427. BranchProbabilityInfo::getBranchProbStackProtector(true);
  428. auto FailureProb =
  429. BranchProbabilityInfo::getBranchProbStackProtector(false);
  430. MDNode *Weights = MDBuilder(F->getContext())
  431. .createBranchWeights(SuccessProb.getNumerator(),
  432. FailureProb.getNumerator());
  433. B.CreateCondBr(Cmp, NewBB, FailBB, Weights);
  434. }
  435. }
  436. // Return if we didn't modify any basic blocks. i.e., there are no return
  437. // statements in the function.
  438. return HasPrologue;
  439. }
  440. /// CreateFailBB - Create a basic block to jump to when the stack protector
  441. /// check fails.
  442. BasicBlock *StackProtector::CreateFailBB() {
  443. LLVMContext &Context = F->getContext();
  444. BasicBlock *FailBB = BasicBlock::Create(Context, "CallStackCheckFailBlk", F);
  445. IRBuilder<> B(FailBB);
  446. B.SetCurrentDebugLocation(DebugLoc::get(0, 0, F->getSubprogram()));
  447. if (Trip.isOSOpenBSD()) {
  448. Constant *StackChkFail =
  449. M->getOrInsertFunction("__stack_smash_handler",
  450. Type::getVoidTy(Context),
  451. Type::getInt8PtrTy(Context));
  452. B.CreateCall(StackChkFail, B.CreateGlobalStringPtr(F->getName(), "SSH"));
  453. } else {
  454. Constant *StackChkFail =
  455. M->getOrInsertFunction("__stack_chk_fail", Type::getVoidTy(Context));
  456. B.CreateCall(StackChkFail, {});
  457. }
  458. B.CreateUnreachable();
  459. return FailBB;
  460. }
  461. bool StackProtector::shouldEmitSDCheck(const BasicBlock &BB) const {
  462. return HasPrologue && !HasIRCheck && dyn_cast<ReturnInst>(BB.getTerminator());
  463. }
  464. void StackProtector::copyToMachineFrameInfo(MachineFrameInfo &MFI) const {
  465. if (Layout.empty())
  466. return;
  467. for (int I = 0, E = MFI.getObjectIndexEnd(); I != E; ++I) {
  468. if (MFI.isDeadObjectIndex(I))
  469. continue;
  470. const AllocaInst *AI = MFI.getObjectAllocation(I);
  471. if (!AI)
  472. continue;
  473. SSPLayoutMap::const_iterator LI = Layout.find(AI);
  474. if (LI == Layout.end())
  475. continue;
  476. MFI.setObjectSSPLayout(I, LI->second);
  477. }
  478. }