blob: 3ea56d85fe59e429c8a8491535bde1f10336a231 [file] [log] [blame]
Bill Wendling05d84172008-11-04 02:10:20 +00001//===-- 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//
Bill Wendling64adc712008-11-04 21:53:09 +000010// 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
Bill Wendling05d84172008-11-04 02:10:20 +000013// changed, then there was some sort of violation and the program aborts.
14//
15//===----------------------------------------------------------------------===//
16
Josh Magee8ecfb522013-09-27 21:58:43 +000017#include "llvm/CodeGen/StackProtector.h"
Bill Wendling7c8f96a2013-01-23 06:43:53 +000018#include "llvm/ADT/SmallPtrSet.h"
19#include "llvm/ADT/Statistic.h"
Akira Hatanakab9991a22014-12-01 04:27:03 +000020#include "llvm/Analysis/BranchProbabilityInfo.h"
Michael Gottesman5e570682013-08-20 08:36:53 +000021#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000022#include "llvm/CodeGen/Analysis.h"
23#include "llvm/CodeGen/Passes.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/Attributes.h"
25#include "llvm/IR/Constants.h"
26#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/DerivedTypes.h"
28#include "llvm/IR/Function.h"
Rafael Espindolaaad6c242013-06-07 16:35:57 +000029#include "llvm/IR/GlobalValue.h"
30#include "llvm/IR/GlobalVariable.h"
Benjamin Kramerd93817f2013-09-09 17:38:01 +000031#include "llvm/IR/IRBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000032#include "llvm/IR/Instructions.h"
Michael Gottesman5e570682013-08-20 08:36:53 +000033#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000034#include "llvm/IR/Intrinsics.h"
Akira Hatanakab9991a22014-12-01 04:27:03 +000035#include "llvm/IR/MDBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000036#include "llvm/IR/Module.h"
Bill Wendling05d84172008-11-04 02:10:20 +000037#include "llvm/Support/CommandLine.h"
Eric Christopherd9134482014-08-04 21:25:23 +000038#include "llvm/Target/TargetSubtargetInfo.h"
Bill Wendlingc02a0aa2013-07-22 20:15:21 +000039#include <cstdlib>
Bill Wendling05d84172008-11-04 02:10:20 +000040using namespace llvm;
41
Chandler Carruth1b9dde02014-04-22 02:02:50 +000042#define DEBUG_TYPE "stack-protector"
43
Bill Wendling7c8f96a2013-01-23 06:43:53 +000044STATISTIC(NumFunProtected, "Number of functions protected");
45STATISTIC(NumAddrTaken, "Number of local variables that have their address"
46 " taken.");
47
Josh Magee7245f1d2013-10-30 02:25:14 +000048static cl::opt<bool> EnableSelectionDAGSP("enable-selectiondag-sp",
49 cl::init(true), cl::Hidden);
Michael Gottesman5e570682013-08-20 08:36:53 +000050
Bill Wendling05d84172008-11-04 02:10:20 +000051char StackProtector::ID = 0;
Josh Magee7245f1d2013-10-30 02:25:14 +000052INITIALIZE_PASS(StackProtector, "stack-protector", "Insert stack protectors",
53 false, true)
Bill Wendling05d84172008-11-04 02:10:20 +000054
Bill Wendlingafc10362013-06-19 20:51:24 +000055FunctionPass *llvm::createStackProtectorPass(const TargetMachine *TM) {
56 return new StackProtector(TM);
Bill Wendling05d84172008-11-04 02:10:20 +000057}
58
Josh Magee7245f1d2013-10-30 02:25:14 +000059StackProtector::SSPLayoutKind
60StackProtector::getSSPLayout(const AllocaInst *AI) const {
Josh Magee3f1c0e32013-10-29 21:16:16 +000061 return AI ? Layout.lookup(AI) : SSPLK_None;
62}
63
Hal Finkela69e5b82014-01-20 19:49:14 +000064void StackProtector::adjustForColoring(const AllocaInst *From,
65 const AllocaInst *To) {
66 // When coloring replaces one alloca with another, transfer the SSPLayoutKind
67 // tag from the remapped to the target alloca. The remapped alloca should
68 // have a size smaller than or equal to the replacement alloca.
69 SSPLayoutMap::iterator I = Layout.find(From);
70 if (I != Layout.end()) {
71 SSPLayoutKind Kind = I->second;
72 Layout.erase(I);
73
74 // Transfer the tag, but make sure that SSPLK_AddrOf does not overwrite
75 // SSPLK_SmallArray or SSPLK_LargeArray, and make sure that
76 // SSPLK_SmallArray does not overwrite SSPLK_LargeArray.
77 I = Layout.find(To);
78 if (I == Layout.end())
79 Layout.insert(std::make_pair(To, Kind));
80 else if (I->second != SSPLK_LargeArray && Kind != SSPLK_AddrOf)
81 I->second = Kind;
82 }
83}
84
Bill Wendling05d84172008-11-04 02:10:20 +000085bool StackProtector::runOnFunction(Function &Fn) {
86 F = &Fn;
87 M = F->getParent();
Chandler Carruth73523022014-01-13 13:07:17 +000088 DominatorTreeWrapperPass *DTWP =
89 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
Craig Topperc0196b12014-04-14 00:51:57 +000090 DT = DTWP ? &DTWP->getDomTree() : nullptr;
Eric Christopher33726202015-01-27 08:48:42 +000091 TLI = TM->getSubtargetImpl(Fn)->getTargetLowering();
Tim Shen00127562016-04-08 21:26:31 +000092 HasPrologue = false;
93 HasIRCheck = false;
Bill Wendling05d84172008-11-04 02:10:20 +000094
Duncan P. N. Exon Smith70eb9c52015-02-14 01:44:41 +000095 Attribute Attr = Fn.getFnAttribute("stack-protector-buffer-size");
Renato Goline195f9c2014-01-21 10:24:35 +000096 if (Attr.isStringAttribute() &&
97 Attr.getValueAsString().getAsInteger(10, SSPBufferSize))
98 return false; // Invalid integer string
Bill Wendlingc02a0aa2013-07-22 20:15:21 +000099
Josh Mageeadfde5f2014-04-17 19:08:36 +0000100 if (!RequiresStackProtector())
101 return false;
102
Bill Wendling7c8f96a2013-01-23 06:43:53 +0000103 ++NumFunProtected;
Bill Wendling782e8342008-11-05 00:00:21 +0000104 return InsertStackProtectors();
Bill Wendling05d84172008-11-04 02:10:20 +0000105}
106
Josh Magee3f1c0e32013-10-29 21:16:16 +0000107/// \param [out] IsLarge is set to true if a protectable array is found and
108/// it is "large" ( >= ssp-buffer-size). In the case of a structure with
109/// multiple arrays, this gets set if any of them is large.
110bool StackProtector::ContainsProtectableArray(Type *Ty, bool &IsLarge,
Josh Magee7245f1d2013-10-30 02:25:14 +0000111 bool Strong,
112 bool InStruct) const {
113 if (!Ty)
114 return false;
Bill Wendlingbfb9b752012-08-17 20:59:56 +0000115 if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
116 if (!AT->getElementType()->isIntegerTy(8)) {
Bill Wendlingbfb9b752012-08-17 20:59:56 +0000117 // If we're on a non-Darwin platform or we're inside of a structure, don't
118 // add stack protectors unless the array is a character array.
Josh Magee3f1c0e32013-10-29 21:16:16 +0000119 // However, in strong mode any array, regardless of type and size,
120 // triggers a protector.
121 if (!Strong && (InStruct || !Trip.isOSDarwin()))
122 return false;
Bill Wendlingbfb9b752012-08-17 20:59:56 +0000123 }
124
125 // If an array has more than SSPBufferSize bytes of allocated space, then we
126 // emit stack protectors.
Mehdi Aminied6edbf2015-07-07 23:38:49 +0000127 if (SSPBufferSize <= M->getDataLayout().getTypeAllocSize(AT)) {
Josh Magee3f1c0e32013-10-29 21:16:16 +0000128 IsLarge = true;
129 return true;
Josh Magee7245f1d2013-10-30 02:25:14 +0000130 }
Josh Magee3f1c0e32013-10-29 21:16:16 +0000131
132 if (Strong)
133 // Require a protector for all arrays in strong mode
Bill Wendlingbfb9b752012-08-17 20:59:56 +0000134 return true;
135 }
136
137 const StructType *ST = dyn_cast<StructType>(Ty);
Josh Magee7245f1d2013-10-30 02:25:14 +0000138 if (!ST)
139 return false;
Bill Wendlingbfb9b752012-08-17 20:59:56 +0000140
Josh Magee3f1c0e32013-10-29 21:16:16 +0000141 bool NeedsProtector = false;
Bill Wendlingbfb9b752012-08-17 20:59:56 +0000142 for (StructType::element_iterator I = ST->element_begin(),
Josh Magee7245f1d2013-10-30 02:25:14 +0000143 E = ST->element_end();
144 I != E; ++I)
Josh Magee3f1c0e32013-10-29 21:16:16 +0000145 if (ContainsProtectableArray(*I, IsLarge, Strong, true)) {
146 // If the element is a protectable array and is large (>= SSPBufferSize)
147 // then we are done. If the protectable array is not large, then
148 // keep looking in case a subsequent element is a large array.
149 if (IsLarge)
150 return true;
151 NeedsProtector = true;
152 }
Bill Wendlingbfb9b752012-08-17 20:59:56 +0000153
Josh Magee3f1c0e32013-10-29 21:16:16 +0000154 return NeedsProtector;
Bill Wendlingbfb9b752012-08-17 20:59:56 +0000155}
156
Bill Wendling7c8f96a2013-01-23 06:43:53 +0000157bool StackProtector::HasAddressTaken(const Instruction *AI) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000158 for (const User *U : AI->users()) {
Bill Wendling7c8f96a2013-01-23 06:43:53 +0000159 if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
160 if (AI == SI->getValueOperand())
161 return true;
162 } else if (const PtrToIntInst *SI = dyn_cast<PtrToIntInst>(U)) {
163 if (AI == SI->getOperand(0))
164 return true;
165 } else if (isa<CallInst>(U)) {
166 return true;
167 } else if (isa<InvokeInst>(U)) {
168 return true;
169 } else if (const SelectInst *SI = dyn_cast<SelectInst>(U)) {
170 if (HasAddressTaken(SI))
171 return true;
172 } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
173 // Keep track of what PHI nodes we have already visited to ensure
174 // they are only visited once.
David Blaikie70573dc2014-11-19 07:49:26 +0000175 if (VisitedPHIs.insert(PN).second)
Bill Wendling7c8f96a2013-01-23 06:43:53 +0000176 if (HasAddressTaken(PN))
177 return true;
178 } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
179 if (HasAddressTaken(GEP))
180 return true;
181 } else if (const BitCastInst *BI = dyn_cast<BitCastInst>(U)) {
182 if (HasAddressTaken(BI))
183 return true;
184 }
185 }
186 return false;
187}
188
189/// \brief Check whether or not this function needs a stack protector based
190/// upon the stack protector level.
191///
192/// We use two heuristics: a standard (ssp) and strong (sspstrong).
193/// The standard heuristic which will add a guard variable to functions that
194/// call alloca with a either a variable size or a size >= SSPBufferSize,
195/// functions with character buffers larger than SSPBufferSize, and functions
196/// with aggregates containing character buffers larger than SSPBufferSize. The
197/// strong heuristic will add a guard variables to functions that call alloca
198/// regardless of size, functions with any buffer regardless of type and size,
199/// functions with aggregates that contain any buffer regardless of type and
200/// size, and functions that contain stack-based variables that have had their
201/// address taken.
202bool StackProtector::RequiresStackProtector() {
203 bool Strong = false;
Josh Magee3f1c0e32013-10-29 21:16:16 +0000204 bool NeedsProtector = false;
Tim Shen00127562016-04-08 21:26:31 +0000205 for (const BasicBlock &BB : *F)
206 for (const Instruction &I : BB)
207 if (const CallInst *CI = dyn_cast<CallInst>(&I))
208 if (CI->getCalledFunction() ==
209 Intrinsic::getDeclaration(F->getParent(),
210 Intrinsic::stackprotector))
211 HasPrologue = true;
212
Duncan P. N. Exon Smith70eb9c52015-02-14 01:44:41 +0000213 if (F->hasFnAttribute(Attribute::StackProtectReq)) {
Josh Magee3f1c0e32013-10-29 21:16:16 +0000214 NeedsProtector = true;
215 Strong = true; // Use the same heuristic as strong to determine SSPLayout
Duncan P. N. Exon Smith70eb9c52015-02-14 01:44:41 +0000216 } else if (F->hasFnAttribute(Attribute::StackProtectStrong))
Bill Wendling7c8f96a2013-01-23 06:43:53 +0000217 Strong = true;
Tim Shen00127562016-04-08 21:26:31 +0000218 else if (HasPrologue)
219 NeedsProtector = true;
Duncan P. N. Exon Smith70eb9c52015-02-14 01:44:41 +0000220 else if (!F->hasFnAttribute(Attribute::StackProtect))
Bill Wendlingeeb04152008-11-18 05:32:11 +0000221 return false;
222
Saleem Abdulrasool57b5fe52014-12-20 21:37:51 +0000223 for (const BasicBlock &BB : *F) {
224 for (const Instruction &I : BB) {
225 if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
Bill Wendling7c8f96a2013-01-23 06:43:53 +0000226 if (AI->isArrayAllocation()) {
227 // SSP-Strong: Enable protectors for any call to alloca, regardless
228 // of size.
229 if (Strong)
230 return true;
Michael Gottesman62c5d712013-08-20 08:46:16 +0000231
Saleem Abdulrasool57b5fe52014-12-20 21:37:51 +0000232 if (const auto *CI = dyn_cast<ConstantInt>(AI->getArraySize())) {
Josh Magee3f1c0e32013-10-29 21:16:16 +0000233 if (CI->getLimitedValue(SSPBufferSize) >= SSPBufferSize) {
Bill Wendling7c8f96a2013-01-23 06:43:53 +0000234 // A call to alloca with size >= SSPBufferSize requires
235 // stack protectors.
Josh Magee3f1c0e32013-10-29 21:16:16 +0000236 Layout.insert(std::make_pair(AI, SSPLK_LargeArray));
237 NeedsProtector = true;
238 } else if (Strong) {
239 // Require protectors for all alloca calls in strong mode.
240 Layout.insert(std::make_pair(AI, SSPLK_SmallArray));
241 NeedsProtector = true;
242 }
Bill Wendlingc02a0aa2013-07-22 20:15:21 +0000243 } else {
244 // A call to alloca with a variable size requires protectors.
Josh Magee3f1c0e32013-10-29 21:16:16 +0000245 Layout.insert(std::make_pair(AI, SSPLK_LargeArray));
246 NeedsProtector = true;
Bill Wendlingc02a0aa2013-07-22 20:15:21 +0000247 }
Josh Magee3f1c0e32013-10-29 21:16:16 +0000248 continue;
Bill Wendling7c8f96a2013-01-23 06:43:53 +0000249 }
250
Josh Magee3f1c0e32013-10-29 21:16:16 +0000251 bool IsLarge = false;
252 if (ContainsProtectableArray(AI->getAllocatedType(), IsLarge, Strong)) {
253 Layout.insert(std::make_pair(AI, IsLarge ? SSPLK_LargeArray
254 : SSPLK_SmallArray));
255 NeedsProtector = true;
256 continue;
257 }
Bill Wendlingeeb04152008-11-18 05:32:11 +0000258
Bill Wendling7c8f96a2013-01-23 06:43:53 +0000259 if (Strong && HasAddressTaken(AI)) {
Michael Gottesman62c5d712013-08-20 08:46:16 +0000260 ++NumAddrTaken;
Josh Magee3f1c0e32013-10-29 21:16:16 +0000261 Layout.insert(std::make_pair(AI, SSPLK_AddrOf));
262 NeedsProtector = true;
Bill Wendling7c8f96a2013-01-23 06:43:53 +0000263 }
Bill Wendlingeeb04152008-11-18 05:32:11 +0000264 }
Bill Wendling7c8f96a2013-01-23 06:43:53 +0000265 }
Bill Wendlingeeb04152008-11-18 05:32:11 +0000266 }
267
Josh Magee3f1c0e32013-10-29 21:16:16 +0000268 return NeedsProtector;
Bill Wendlingeeb04152008-11-18 05:32:11 +0000269}
270
Michael Gottesmana6188f92013-07-22 20:44:11 +0000271/// Insert code into the entry block that stores the __stack_chk_guard
272/// variable onto the stack:
273///
274/// entry:
275/// StackGuardSlot = alloca i8*
276/// StackGuard = load __stack_chk_guard
277/// call void @llvm.stackprotect.create(StackGuard, StackGuardSlot)
278///
Michael Gottesman5e570682013-08-20 08:36:53 +0000279/// Returns true if the platform/triple supports the stackprotectorcreate pseudo
280/// node.
281static bool CreatePrologue(Function *F, Module *M, ReturnInst *RI,
Tim Shen00127562016-04-08 21:26:31 +0000282 const TargetLoweringBase *TLI, AllocaInst *&AI,
283 Value *&StackGuardVar) {
Michael Gottesman5e570682013-08-20 08:36:53 +0000284 bool SupportsSelectionDAGSP = false;
Evgeniy Stepanovdde29e22016-04-05 22:41:50 +0000285 IRBuilder<> B(&F->getEntryBlock().front());
Michael Gottesman62c5d712013-08-20 08:46:16 +0000286
Tim Shen00127562016-04-08 21:26:31 +0000287 StackGuardVar = TLI->getIRStackGuard(B);
Evgeniy Stepanovdde29e22016-04-05 22:41:50 +0000288 if (!StackGuardVar) {
Tim Shen00127562016-04-08 21:26:31 +0000289 /// Use SelectionDAG SSP handling, since there isn't an IR guard.
290 SupportsSelectionDAGSP = true;
291 TLI->insertSSPDeclarations(*M);
292 StackGuardVar = TLI->getSDStackGuard(*M);
Michael Gottesmana6188f92013-07-22 20:44:11 +0000293 }
Tim Shen00127562016-04-08 21:26:31 +0000294 assert(StackGuardVar && "Must have stack guard available");
Michael Gottesman62c5d712013-08-20 08:46:16 +0000295
Tim Shen00127562016-04-08 21:26:31 +0000296 PointerType *PtrTy = Type::getInt8PtrTy(RI->getContext());
Craig Topperc0196b12014-04-14 00:51:57 +0000297 AI = B.CreateAlloca(PtrTy, nullptr, "StackGuardSlot");
Benjamin Kramerd93817f2013-09-09 17:38:01 +0000298 LoadInst *LI = B.CreateLoad(StackGuardVar, "StackGuard");
David Blaikieff6409d2015-05-18 22:13:54 +0000299 B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackprotector),
300 {LI, AI});
Michael Gottesman5e570682013-08-20 08:36:53 +0000301 return SupportsSelectionDAGSP;
Michael Gottesmana6188f92013-07-22 20:44:11 +0000302}
303
Bill Wendling782e8342008-11-05 00:00:21 +0000304/// InsertStackProtectors - Insert code into the prologue and epilogue of the
305/// function.
306///
307/// - The prologue code loads and stores the stack guard onto the stack.
308/// - The epilogue checks the value stored in the prologue against the original
309/// value. It calls __stack_chk_fail if they differ.
310bool StackProtector::InsertStackProtectors() {
Michael Gottesman76c44be2013-08-20 08:56:26 +0000311 bool SupportsSelectionDAGSP =
Josh Magee7245f1d2013-10-30 02:25:14 +0000312 EnableSelectionDAGSP && !TM->Options.EnableFastISel;
Craig Topperc0196b12014-04-14 00:51:57 +0000313 AllocaInst *AI = nullptr; // Place on stack that stores the stack guard.
314 Value *StackGuardVar = nullptr; // The stack guard variable.
Bill Wendlingeb4268d2008-11-07 01:23:58 +0000315
Josh Magee7245f1d2013-10-30 02:25:14 +0000316 for (Function::iterator I = F->begin(), E = F->end(); I != E;) {
Duncan P. N. Exon Smithf1ff53e2015-10-09 22:56:24 +0000317 BasicBlock *BB = &*I++;
Bill Wendlingeeb04152008-11-18 05:32:11 +0000318 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
Michael Gottesmandc985ef2013-08-20 08:56:28 +0000319 if (!RI)
320 continue;
Bill Wendlingeb4268d2008-11-07 01:23:58 +0000321
Michael Gottesman8afcf3a2013-08-09 21:26:18 +0000322 if (!HasPrologue) {
323 HasPrologue = true;
Josh Magee7245f1d2013-10-30 02:25:14 +0000324 SupportsSelectionDAGSP &=
Tim Shen00127562016-04-08 21:26:31 +0000325 CreatePrologue(F, M, RI, TLI, AI, StackGuardVar);
Michael Gottesman62c5d712013-08-20 08:46:16 +0000326 }
Michael Gottesman5e570682013-08-20 08:36:53 +0000327
Tim Shen00127562016-04-08 21:26:31 +0000328 if (!SupportsSelectionDAGSP) {
Michael Gottesman56e246b2013-08-20 08:46:13 +0000329 // If we do not support SelectionDAG based tail calls, generate IR level
330 // tail calls.
331 //
Michael Gottesman5e570682013-08-20 08:36:53 +0000332 // For each block with a return instruction, convert this:
333 //
334 // return:
335 // ...
336 // ret ...
337 //
338 // into this:
339 //
340 // return:
341 // ...
342 // %1 = load __stack_chk_guard
343 // %2 = load StackGuardSlot
344 // %3 = cmp i1 %1, %2
345 // br i1 %3, label %SP_return, label %CallStackCheckFailBlk
346 //
347 // SP_return:
348 // ret ...
349 //
350 // CallStackCheckFailBlk:
351 // call void @__stack_chk_fail()
352 // unreachable
353
354 // Create the FailBB. We duplicate the BB every time since the MI tail
355 // merge pass will merge together all of the various BB into one including
Michael Gottesman62c5d712013-08-20 08:46:16 +0000356 // fail BB generated by the stack protector pseudo instruction.
Michael Gottesman5e570682013-08-20 08:36:53 +0000357 BasicBlock *FailBB = CreateFailBB();
Michael Gottesman62c5d712013-08-20 08:46:16 +0000358
Tim Shen00127562016-04-08 21:26:31 +0000359 // Set HasIRCheck to true, so that SelectionDAG will not generate its own
360 // version.
361 HasIRCheck = true;
362
Michael Gottesman5e570682013-08-20 08:36:53 +0000363 // Split the basic block before the return instruction.
Duncan P. N. Exon Smithf1ff53e2015-10-09 22:56:24 +0000364 BasicBlock *NewBB = BB->splitBasicBlock(RI->getIterator(), "SP_return");
Michael Gottesman62c5d712013-08-20 08:46:16 +0000365
Michael Gottesman5e570682013-08-20 08:36:53 +0000366 // Update the dominator tree if we need to.
367 if (DT && DT->isReachableFromEntry(BB)) {
368 DT->addNewBlock(NewBB, BB);
369 DT->addNewBlock(FailBB, BB);
370 }
Michael Gottesman62c5d712013-08-20 08:46:16 +0000371
Michael Gottesman5e570682013-08-20 08:36:53 +0000372 // Remove default branch instruction to the new BB.
373 BB->getTerminator()->eraseFromParent();
Michael Gottesman62c5d712013-08-20 08:46:16 +0000374
Michael Gottesman5e570682013-08-20 08:36:53 +0000375 // Move the newly created basic block to the point right after the old
376 // basic block so that it's in the "fall through" position.
377 NewBB->moveAfter(BB);
Michael Gottesman62c5d712013-08-20 08:46:16 +0000378
Michael Gottesman5e570682013-08-20 08:36:53 +0000379 // Generate the stack protector instructions in the old basic block.
Benjamin Kramerd93817f2013-09-09 17:38:01 +0000380 IRBuilder<> B(BB);
381 LoadInst *LI1 = B.CreateLoad(StackGuardVar);
382 LoadInst *LI2 = B.CreateLoad(AI);
383 Value *Cmp = B.CreateICmpEQ(LI1, LI2);
Cong Houe93b8e12015-12-22 18:56:14 +0000384 auto SuccessProb =
385 BranchProbabilityInfo::getBranchProbStackProtector(true);
386 auto FailureProb =
387 BranchProbabilityInfo::getBranchProbStackProtector(false);
Akira Hatanakab9991a22014-12-01 04:27:03 +0000388 MDNode *Weights = MDBuilder(F->getContext())
Cong Houe93b8e12015-12-22 18:56:14 +0000389 .createBranchWeights(SuccessProb.getNumerator(),
390 FailureProb.getNumerator());
Akira Hatanakab9991a22014-12-01 04:27:03 +0000391 B.CreateCondBr(Cmp, NewBB, FailBB, Weights);
Bill Wendlinga0826e182008-11-06 23:55:49 +0000392 }
Bill Wendling05d84172008-11-04 02:10:20 +0000393 }
Bill Wendling782e8342008-11-05 00:00:21 +0000394
Saleem Abdulrasool90c224a2014-12-21 21:52:38 +0000395 // Return if we didn't modify any basic blocks. i.e., there are no return
Bill Wendlinga0826e182008-11-06 23:55:49 +0000396 // statements in the function.
Rafael Espindola84921b92015-10-24 23:11:13 +0000397 return HasPrologue;
Bill Wendling05d84172008-11-04 02:10:20 +0000398}
399
400/// CreateFailBB - Create a basic block to jump to when the stack protector
401/// check fails.
Bill Wendling782e8342008-11-05 00:00:21 +0000402BasicBlock *StackProtector::CreateFailBB() {
Rafael Espindolaaad6c242013-06-07 16:35:57 +0000403 LLVMContext &Context = F->getContext();
404 BasicBlock *FailBB = BasicBlock::Create(Context, "CallStackCheckFailBlk", F);
Benjamin Kramerd93817f2013-09-09 17:38:01 +0000405 IRBuilder<> B(FailBB);
Simon Pilgrim2bfd9122014-11-29 19:18:21 +0000406 if (Trip.isOSOpenBSD()) {
Saleem Abdulrasool90c224a2014-12-21 21:52:38 +0000407 Constant *StackChkFail =
408 M->getOrInsertFunction("__stack_smash_handler",
409 Type::getVoidTy(Context),
410 Type::getInt8PtrTy(Context), nullptr);
Rafael Espindolaaad6c242013-06-07 16:35:57 +0000411
Benjamin Kramerd93817f2013-09-09 17:38:01 +0000412 B.CreateCall(StackChkFail, B.CreateGlobalStringPtr(F->getName(), "SSH"));
Rafael Espindolaaad6c242013-06-07 16:35:57 +0000413 } else {
Saleem Abdulrasool90c224a2014-12-21 21:52:38 +0000414 Constant *StackChkFail =
415 M->getOrInsertFunction("__stack_chk_fail", Type::getVoidTy(Context),
416 nullptr);
David Blaikieff6409d2015-05-18 22:13:54 +0000417 B.CreateCall(StackChkFail, {});
Rafael Espindolaaad6c242013-06-07 16:35:57 +0000418 }
Benjamin Kramerd93817f2013-09-09 17:38:01 +0000419 B.CreateUnreachable();
Bill Wendling782e8342008-11-05 00:00:21 +0000420 return FailBB;
Bill Wendling05d84172008-11-04 02:10:20 +0000421}
Tim Shen00127562016-04-08 21:26:31 +0000422
423bool StackProtector::shouldEmitSDCheck(const BasicBlock &BB) const {
424 return HasPrologue && !HasIRCheck && dyn_cast<ReturnInst>(BB.getTerminator());
425}