StackProtector.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619
  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/EHPersonalities.h"
  20. #include "llvm/Analysis/MemoryLocation.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/InitializePasses.h"
  45. #include "llvm/Pass.h"
  46. #include "llvm/Support/Casting.h"
  47. #include "llvm/Support/CommandLine.h"
  48. #include "llvm/Target/TargetMachine.h"
  49. #include "llvm/Target/TargetOptions.h"
  50. #include <utility>
  51. using namespace llvm;
  52. #define DEBUG_TYPE "stack-protector"
  53. STATISTIC(NumFunProtected, "Number of functions protected");
  54. STATISTIC(NumAddrTaken, "Number of local variables that have their address"
  55. " taken.");
  56. static cl::opt<bool> EnableSelectionDAGSP("enable-selectiondag-sp",
  57. cl::init(true), cl::Hidden);
  58. char StackProtector::ID = 0;
  59. StackProtector::StackProtector() : FunctionPass(ID), SSPBufferSize(8) {
  60. initializeStackProtectorPass(*PassRegistry::getPassRegistry());
  61. }
  62. INITIALIZE_PASS_BEGIN(StackProtector, DEBUG_TYPE,
  63. "Insert stack protectors", false, true)
  64. INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
  65. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  66. INITIALIZE_PASS_END(StackProtector, DEBUG_TYPE,
  67. "Insert stack protectors", false, true)
  68. FunctionPass *llvm::createStackProtectorPass() { return new StackProtector(); }
  69. void StackProtector::getAnalysisUsage(AnalysisUsage &AU) const {
  70. AU.addRequired<TargetPassConfig>();
  71. AU.addPreserved<DominatorTreeWrapperPass>();
  72. }
  73. bool StackProtector::runOnFunction(Function &Fn) {
  74. F = &Fn;
  75. M = F->getParent();
  76. DominatorTreeWrapperPass *DTWP =
  77. getAnalysisIfAvailable<DominatorTreeWrapperPass>();
  78. DT = DTWP ? &DTWP->getDomTree() : nullptr;
  79. TM = &getAnalysis<TargetPassConfig>().getTM<TargetMachine>();
  80. Trip = TM->getTargetTriple();
  81. TLI = TM->getSubtargetImpl(Fn)->getTargetLowering();
  82. HasPrologue = false;
  83. HasIRCheck = false;
  84. Attribute Attr = Fn.getFnAttribute("stack-protector-buffer-size");
  85. if (Attr.isStringAttribute() &&
  86. Attr.getValueAsString().getAsInteger(10, SSPBufferSize))
  87. return false; // Invalid integer string
  88. if (!RequiresStackProtector())
  89. return false;
  90. // TODO(etienneb): Functions with funclets are not correctly supported now.
  91. // Do nothing if this is funclet-based personality.
  92. if (Fn.hasPersonalityFn()) {
  93. EHPersonality Personality = classifyEHPersonality(Fn.getPersonalityFn());
  94. if (isFuncletEHPersonality(Personality))
  95. return false;
  96. }
  97. ++NumFunProtected;
  98. return InsertStackProtectors();
  99. }
  100. /// \param [out] IsLarge is set to true if a protectable array is found and
  101. /// it is "large" ( >= ssp-buffer-size). In the case of a structure with
  102. /// multiple arrays, this gets set if any of them is large.
  103. bool StackProtector::ContainsProtectableArray(Type *Ty, bool &IsLarge,
  104. bool Strong,
  105. bool InStruct) const {
  106. if (!Ty)
  107. return false;
  108. if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
  109. if (!AT->getElementType()->isIntegerTy(8)) {
  110. // If we're on a non-Darwin platform or we're inside of a structure, don't
  111. // add stack protectors unless the array is a character array.
  112. // However, in strong mode any array, regardless of type and size,
  113. // triggers a protector.
  114. if (!Strong && (InStruct || !Trip.isOSDarwin()))
  115. return false;
  116. }
  117. // If an array has more than SSPBufferSize bytes of allocated space, then we
  118. // emit stack protectors.
  119. if (SSPBufferSize <= M->getDataLayout().getTypeAllocSize(AT)) {
  120. IsLarge = true;
  121. return true;
  122. }
  123. if (Strong)
  124. // Require a protector for all arrays in strong mode
  125. return true;
  126. }
  127. const StructType *ST = dyn_cast<StructType>(Ty);
  128. if (!ST)
  129. return false;
  130. bool NeedsProtector = false;
  131. for (Type *ET : ST->elements())
  132. if (ContainsProtectableArray(ET, IsLarge, Strong, true)) {
  133. // If the element is a protectable array and is large (>= SSPBufferSize)
  134. // then we are done. If the protectable array is not large, then
  135. // keep looking in case a subsequent element is a large array.
  136. if (IsLarge)
  137. return true;
  138. NeedsProtector = true;
  139. }
  140. return NeedsProtector;
  141. }
  142. bool StackProtector::HasAddressTaken(const Instruction *AI,
  143. TypeSize AllocSize) {
  144. const DataLayout &DL = M->getDataLayout();
  145. for (const User *U : AI->users()) {
  146. const auto *I = cast<Instruction>(U);
  147. // If this instruction accesses memory make sure it doesn't access beyond
  148. // the bounds of the allocated object.
  149. Optional<MemoryLocation> MemLoc = MemoryLocation::getOrNone(I);
  150. if (MemLoc.hasValue() && MemLoc->Size.hasValue() &&
  151. !TypeSize::isKnownGE(AllocSize,
  152. TypeSize::getFixed(MemLoc->Size.getValue())))
  153. return true;
  154. switch (I->getOpcode()) {
  155. case Instruction::Store:
  156. if (AI == cast<StoreInst>(I)->getValueOperand())
  157. return true;
  158. break;
  159. case Instruction::AtomicCmpXchg:
  160. // cmpxchg conceptually includes both a load and store from the same
  161. // location. So, like store, the value being stored is what matters.
  162. if (AI == cast<AtomicCmpXchgInst>(I)->getNewValOperand())
  163. return true;
  164. break;
  165. case Instruction::PtrToInt:
  166. if (AI == cast<PtrToIntInst>(I)->getOperand(0))
  167. return true;
  168. break;
  169. case Instruction::Call: {
  170. // Ignore intrinsics that do not become real instructions.
  171. // TODO: Narrow this to intrinsics that have store-like effects.
  172. const auto *CI = cast<CallInst>(I);
  173. if (!CI->isDebugOrPseudoInst() && !CI->isLifetimeStartOrEnd())
  174. return true;
  175. break;
  176. }
  177. case Instruction::Invoke:
  178. return true;
  179. case Instruction::GetElementPtr: {
  180. // If the GEP offset is out-of-bounds, or is non-constant and so has to be
  181. // assumed to be potentially out-of-bounds, then any memory access that
  182. // would use it could also be out-of-bounds meaning stack protection is
  183. // required.
  184. const GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
  185. unsigned IndexSize = DL.getIndexTypeSizeInBits(I->getType());
  186. APInt Offset(IndexSize, 0);
  187. if (!GEP->accumulateConstantOffset(DL, Offset))
  188. return true;
  189. TypeSize OffsetSize = TypeSize::Fixed(Offset.getLimitedValue());
  190. if (!TypeSize::isKnownGT(AllocSize, OffsetSize))
  191. return true;
  192. // Adjust AllocSize to be the space remaining after this offset.
  193. // We can't subtract a fixed size from a scalable one, so in that case
  194. // assume the scalable value is of minimum size.
  195. TypeSize NewAllocSize =
  196. TypeSize::Fixed(AllocSize.getKnownMinValue()) - OffsetSize;
  197. if (HasAddressTaken(I, NewAllocSize))
  198. return true;
  199. break;
  200. }
  201. case Instruction::BitCast:
  202. case Instruction::Select:
  203. case Instruction::AddrSpaceCast:
  204. if (HasAddressTaken(I, AllocSize))
  205. return true;
  206. break;
  207. case Instruction::PHI: {
  208. // Keep track of what PHI nodes we have already visited to ensure
  209. // they are only visited once.
  210. const auto *PN = cast<PHINode>(I);
  211. if (VisitedPHIs.insert(PN).second)
  212. if (HasAddressTaken(PN, AllocSize))
  213. return true;
  214. break;
  215. }
  216. case Instruction::Load:
  217. case Instruction::AtomicRMW:
  218. case Instruction::Ret:
  219. // These instructions take an address operand, but have load-like or
  220. // other innocuous behavior that should not trigger a stack protector.
  221. // atomicrmw conceptually has both load and store semantics, but the
  222. // value being stored must be integer; so if a pointer is being stored,
  223. // we'll catch it in the PtrToInt case above.
  224. break;
  225. default:
  226. // Conservatively return true for any instruction that takes an address
  227. // operand, but is not handled above.
  228. return true;
  229. }
  230. }
  231. return false;
  232. }
  233. /// Search for the first call to the llvm.stackprotector intrinsic and return it
  234. /// if present.
  235. static const CallInst *findStackProtectorIntrinsic(Function &F) {
  236. for (const BasicBlock &BB : F)
  237. for (const Instruction &I : BB)
  238. if (const auto *II = dyn_cast<IntrinsicInst>(&I))
  239. if (II->getIntrinsicID() == Intrinsic::stackprotector)
  240. return II;
  241. return nullptr;
  242. }
  243. /// Check whether or not this function needs a stack protector based
  244. /// upon the stack protector level.
  245. ///
  246. /// We use two heuristics: a standard (ssp) and strong (sspstrong).
  247. /// The standard heuristic which will add a guard variable to functions that
  248. /// call alloca with a either a variable size or a size >= SSPBufferSize,
  249. /// functions with character buffers larger than SSPBufferSize, and functions
  250. /// with aggregates containing character buffers larger than SSPBufferSize. The
  251. /// strong heuristic will add a guard variables to functions that call alloca
  252. /// regardless of size, functions with any buffer regardless of type and size,
  253. /// functions with aggregates that contain any buffer regardless of type and
  254. /// size, and functions that contain stack-based variables that have had their
  255. /// address taken.
  256. bool StackProtector::RequiresStackProtector() {
  257. bool Strong = false;
  258. bool NeedsProtector = false;
  259. if (F->hasFnAttribute(Attribute::SafeStack))
  260. return false;
  261. // We are constructing the OptimizationRemarkEmitter on the fly rather than
  262. // using the analysis pass to avoid building DominatorTree and LoopInfo which
  263. // are not available this late in the IR pipeline.
  264. OptimizationRemarkEmitter ORE(F);
  265. if (F->hasFnAttribute(Attribute::StackProtectReq)) {
  266. ORE.emit([&]() {
  267. return OptimizationRemark(DEBUG_TYPE, "StackProtectorRequested", F)
  268. << "Stack protection applied to function "
  269. << ore::NV("Function", F)
  270. << " due to a function attribute or command-line switch";
  271. });
  272. NeedsProtector = true;
  273. Strong = true; // Use the same heuristic as strong to determine SSPLayout
  274. } else if (F->hasFnAttribute(Attribute::StackProtectStrong))
  275. Strong = true;
  276. else if (!F->hasFnAttribute(Attribute::StackProtect))
  277. return false;
  278. for (const BasicBlock &BB : *F) {
  279. for (const Instruction &I : BB) {
  280. if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
  281. if (AI->isArrayAllocation()) {
  282. auto RemarkBuilder = [&]() {
  283. return OptimizationRemark(DEBUG_TYPE, "StackProtectorAllocaOrArray",
  284. &I)
  285. << "Stack protection applied to function "
  286. << ore::NV("Function", F)
  287. << " due to a call to alloca or use of a variable length "
  288. "array";
  289. };
  290. if (const auto *CI = dyn_cast<ConstantInt>(AI->getArraySize())) {
  291. if (CI->getLimitedValue(SSPBufferSize) >= SSPBufferSize) {
  292. // A call to alloca with size >= SSPBufferSize requires
  293. // stack protectors.
  294. Layout.insert(std::make_pair(AI,
  295. MachineFrameInfo::SSPLK_LargeArray));
  296. ORE.emit(RemarkBuilder);
  297. NeedsProtector = true;
  298. } else if (Strong) {
  299. // Require protectors for all alloca calls in strong mode.
  300. Layout.insert(std::make_pair(AI,
  301. MachineFrameInfo::SSPLK_SmallArray));
  302. ORE.emit(RemarkBuilder);
  303. NeedsProtector = true;
  304. }
  305. } else {
  306. // A call to alloca with a variable size requires protectors.
  307. Layout.insert(std::make_pair(AI,
  308. MachineFrameInfo::SSPLK_LargeArray));
  309. ORE.emit(RemarkBuilder);
  310. NeedsProtector = true;
  311. }
  312. continue;
  313. }
  314. bool IsLarge = false;
  315. if (ContainsProtectableArray(AI->getAllocatedType(), IsLarge, Strong)) {
  316. Layout.insert(std::make_pair(AI, IsLarge
  317. ? MachineFrameInfo::SSPLK_LargeArray
  318. : MachineFrameInfo::SSPLK_SmallArray));
  319. ORE.emit([&]() {
  320. return OptimizationRemark(DEBUG_TYPE, "StackProtectorBuffer", &I)
  321. << "Stack protection applied to function "
  322. << ore::NV("Function", F)
  323. << " due to a stack allocated buffer or struct containing a "
  324. "buffer";
  325. });
  326. NeedsProtector = true;
  327. continue;
  328. }
  329. if (Strong && HasAddressTaken(AI, M->getDataLayout().getTypeAllocSize(
  330. AI->getAllocatedType()))) {
  331. ++NumAddrTaken;
  332. Layout.insert(std::make_pair(AI, MachineFrameInfo::SSPLK_AddrOf));
  333. ORE.emit([&]() {
  334. return OptimizationRemark(DEBUG_TYPE, "StackProtectorAddressTaken",
  335. &I)
  336. << "Stack protection applied to function "
  337. << ore::NV("Function", F)
  338. << " due to the address of a local variable being taken";
  339. });
  340. NeedsProtector = true;
  341. }
  342. // Clear any PHIs that we visited, to make sure we examine all uses of
  343. // any subsequent allocas that we look at.
  344. VisitedPHIs.clear();
  345. }
  346. }
  347. }
  348. return NeedsProtector;
  349. }
  350. /// Create a stack guard loading and populate whether SelectionDAG SSP is
  351. /// supported.
  352. static Value *getStackGuard(const TargetLoweringBase *TLI, Module *M,
  353. IRBuilder<> &B,
  354. bool *SupportsSelectionDAGSP = nullptr) {
  355. Value *Guard = TLI->getIRStackGuard(B);
  356. StringRef GuardMode = M->getStackProtectorGuard();
  357. if ((GuardMode == "tls" || GuardMode.empty()) && Guard)
  358. return B.CreateLoad(B.getInt8PtrTy(), Guard, true, "StackGuard");
  359. // Use SelectionDAG SSP handling, since there isn't an IR guard.
  360. //
  361. // This is more or less weird, since we optionally output whether we
  362. // should perform a SelectionDAG SP here. The reason is that it's strictly
  363. // defined as !TLI->getIRStackGuard(B), where getIRStackGuard is also
  364. // mutating. There is no way to get this bit without mutating the IR, so
  365. // getting this bit has to happen in this right time.
  366. //
  367. // We could have define a new function TLI::supportsSelectionDAGSP(), but that
  368. // will put more burden on the backends' overriding work, especially when it
  369. // actually conveys the same information getIRStackGuard() already gives.
  370. if (SupportsSelectionDAGSP)
  371. *SupportsSelectionDAGSP = true;
  372. TLI->insertSSPDeclarations(*M);
  373. return B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackguard));
  374. }
  375. /// Insert code into the entry block that stores the stack guard
  376. /// variable onto the stack:
  377. ///
  378. /// entry:
  379. /// StackGuardSlot = alloca i8*
  380. /// StackGuard = <stack guard>
  381. /// call void @llvm.stackprotector(StackGuard, StackGuardSlot)
  382. ///
  383. /// Returns true if the platform/triple supports the stackprotectorcreate pseudo
  384. /// node.
  385. static bool CreatePrologue(Function *F, Module *M, ReturnInst *RI,
  386. const TargetLoweringBase *TLI, AllocaInst *&AI) {
  387. bool SupportsSelectionDAGSP = false;
  388. IRBuilder<> B(&F->getEntryBlock().front());
  389. PointerType *PtrTy = Type::getInt8PtrTy(RI->getContext());
  390. AI = B.CreateAlloca(PtrTy, nullptr, "StackGuardSlot");
  391. Value *GuardSlot = getStackGuard(TLI, M, B, &SupportsSelectionDAGSP);
  392. B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackprotector),
  393. {GuardSlot, AI});
  394. return SupportsSelectionDAGSP;
  395. }
  396. /// InsertStackProtectors - Insert code into the prologue and epilogue of the
  397. /// function.
  398. ///
  399. /// - The prologue code loads and stores the stack guard onto the stack.
  400. /// - The epilogue checks the value stored in the prologue against the original
  401. /// value. It calls __stack_chk_fail if they differ.
  402. bool StackProtector::InsertStackProtectors() {
  403. // If the target wants to XOR the frame pointer into the guard value, it's
  404. // impossible to emit the check in IR, so the target *must* support stack
  405. // protection in SDAG.
  406. bool SupportsSelectionDAGSP =
  407. TLI->useStackGuardXorFP() ||
  408. (EnableSelectionDAGSP && !TM->Options.EnableFastISel);
  409. AllocaInst *AI = nullptr; // Place on stack that stores the stack guard.
  410. for (BasicBlock &BB : llvm::make_early_inc_range(*F)) {
  411. ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator());
  412. if (!RI)
  413. continue;
  414. // Generate prologue instrumentation if not already generated.
  415. if (!HasPrologue) {
  416. HasPrologue = true;
  417. SupportsSelectionDAGSP &= CreatePrologue(F, M, RI, TLI, AI);
  418. }
  419. // SelectionDAG based code generation. Nothing else needs to be done here.
  420. // The epilogue instrumentation is postponed to SelectionDAG.
  421. if (SupportsSelectionDAGSP)
  422. break;
  423. // Find the stack guard slot if the prologue was not created by this pass
  424. // itself via a previous call to CreatePrologue().
  425. if (!AI) {
  426. const CallInst *SPCall = findStackProtectorIntrinsic(*F);
  427. assert(SPCall && "Call to llvm.stackprotector is missing");
  428. AI = cast<AllocaInst>(SPCall->getArgOperand(1));
  429. }
  430. // Set HasIRCheck to true, so that SelectionDAG will not generate its own
  431. // version. SelectionDAG called 'shouldEmitSDCheck' to check whether
  432. // instrumentation has already been generated.
  433. HasIRCheck = true;
  434. // If we're instrumenting a block with a musttail call, the check has to be
  435. // inserted before the call rather than between it and the return. The
  436. // verifier guarantees that a musttail call is either directly before the
  437. // return or with a single correct bitcast of the return value in between so
  438. // we don't need to worry about many situations here.
  439. Instruction *CheckLoc = RI;
  440. Instruction *Prev = RI->getPrevNonDebugInstruction();
  441. if (Prev && isa<CallInst>(Prev) && cast<CallInst>(Prev)->isMustTailCall())
  442. CheckLoc = Prev;
  443. else if (Prev) {
  444. Prev = Prev->getPrevNonDebugInstruction();
  445. if (Prev && isa<CallInst>(Prev) && cast<CallInst>(Prev)->isMustTailCall())
  446. CheckLoc = Prev;
  447. }
  448. // Generate epilogue instrumentation. The epilogue intrumentation can be
  449. // function-based or inlined depending on which mechanism the target is
  450. // providing.
  451. if (Function *GuardCheck = TLI->getSSPStackGuardCheck(*M)) {
  452. // Generate the function-based epilogue instrumentation.
  453. // The target provides a guard check function, generate a call to it.
  454. IRBuilder<> B(CheckLoc);
  455. LoadInst *Guard = B.CreateLoad(B.getInt8PtrTy(), AI, true, "Guard");
  456. CallInst *Call = B.CreateCall(GuardCheck, {Guard});
  457. Call->setAttributes(GuardCheck->getAttributes());
  458. Call->setCallingConv(GuardCheck->getCallingConv());
  459. } else {
  460. // Generate the epilogue with inline instrumentation.
  461. // If we do not support SelectionDAG based calls, generate IR level
  462. // calls.
  463. //
  464. // For each block with a return instruction, convert this:
  465. //
  466. // return:
  467. // ...
  468. // ret ...
  469. //
  470. // into this:
  471. //
  472. // return:
  473. // ...
  474. // %1 = <stack guard>
  475. // %2 = load StackGuardSlot
  476. // %3 = cmp i1 %1, %2
  477. // br i1 %3, label %SP_return, label %CallStackCheckFailBlk
  478. //
  479. // SP_return:
  480. // ret ...
  481. //
  482. // CallStackCheckFailBlk:
  483. // call void @__stack_chk_fail()
  484. // unreachable
  485. // Create the FailBB. We duplicate the BB every time since the MI tail
  486. // merge pass will merge together all of the various BB into one including
  487. // fail BB generated by the stack protector pseudo instruction.
  488. BasicBlock *FailBB = CreateFailBB();
  489. // Split the basic block before the return instruction.
  490. BasicBlock *NewBB =
  491. BB.splitBasicBlock(CheckLoc->getIterator(), "SP_return");
  492. // Update the dominator tree if we need to.
  493. if (DT && DT->isReachableFromEntry(&BB)) {
  494. DT->addNewBlock(NewBB, &BB);
  495. DT->addNewBlock(FailBB, &BB);
  496. }
  497. // Remove default branch instruction to the new BB.
  498. BB.getTerminator()->eraseFromParent();
  499. // Move the newly created basic block to the point right after the old
  500. // basic block so that it's in the "fall through" position.
  501. NewBB->moveAfter(&BB);
  502. // Generate the stack protector instructions in the old basic block.
  503. IRBuilder<> B(&BB);
  504. Value *Guard = getStackGuard(TLI, M, B);
  505. LoadInst *LI2 = B.CreateLoad(B.getInt8PtrTy(), AI, true);
  506. Value *Cmp = B.CreateICmpEQ(Guard, LI2);
  507. auto SuccessProb =
  508. BranchProbabilityInfo::getBranchProbStackProtector(true);
  509. auto FailureProb =
  510. BranchProbabilityInfo::getBranchProbStackProtector(false);
  511. MDNode *Weights = MDBuilder(F->getContext())
  512. .createBranchWeights(SuccessProb.getNumerator(),
  513. FailureProb.getNumerator());
  514. B.CreateCondBr(Cmp, NewBB, FailBB, Weights);
  515. }
  516. }
  517. // Return if we didn't modify any basic blocks. i.e., there are no return
  518. // statements in the function.
  519. return HasPrologue;
  520. }
  521. /// CreateFailBB - Create a basic block to jump to when the stack protector
  522. /// check fails.
  523. BasicBlock *StackProtector::CreateFailBB() {
  524. LLVMContext &Context = F->getContext();
  525. BasicBlock *FailBB = BasicBlock::Create(Context, "CallStackCheckFailBlk", F);
  526. IRBuilder<> B(FailBB);
  527. if (F->getSubprogram())
  528. B.SetCurrentDebugLocation(
  529. DILocation::get(Context, 0, 0, F->getSubprogram()));
  530. if (Trip.isOSOpenBSD()) {
  531. FunctionCallee StackChkFail = M->getOrInsertFunction(
  532. "__stack_smash_handler", Type::getVoidTy(Context),
  533. Type::getInt8PtrTy(Context));
  534. B.CreateCall(StackChkFail, B.CreateGlobalStringPtr(F->getName(), "SSH"));
  535. } else {
  536. FunctionCallee StackChkFail =
  537. M->getOrInsertFunction("__stack_chk_fail", Type::getVoidTy(Context));
  538. B.CreateCall(StackChkFail, {});
  539. }
  540. B.CreateUnreachable();
  541. return FailBB;
  542. }
  543. bool StackProtector::shouldEmitSDCheck(const BasicBlock &BB) const {
  544. return HasPrologue && !HasIRCheck && isa<ReturnInst>(BB.getTerminator());
  545. }
  546. void StackProtector::copyToMachineFrameInfo(MachineFrameInfo &MFI) const {
  547. if (Layout.empty())
  548. return;
  549. for (int I = 0, E = MFI.getObjectIndexEnd(); I != E; ++I) {
  550. if (MFI.isDeadObjectIndex(I))
  551. continue;
  552. const AllocaInst *AI = MFI.getObjectAllocation(I);
  553. if (!AI)
  554. continue;
  555. SSPLayoutMap::const_iterator LI = Layout.find(AI);
  556. if (LI == Layout.end())
  557. continue;
  558. MFI.setObjectSSPLayout(I, LI->second);
  559. }
  560. }