StackProtector.cpp 20 KB

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