blob: 2912f77810e1534e8b482ff6750b223d08c669b4 [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"
Etienne Bergeron22bfa832016-06-07 20:15:35 +000021#include "llvm/Analysis/EHPersonalities.h"
Michael Gottesman5e570682013-08-20 08:36:53 +000022#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000023#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))
Etienne Bergeron22bfa832016-06-07 20:15:35 +000098 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
Etienne Bergeron22bfa832016-06-07 20:15:35 +0000103 // TODO(etienneb): Functions with funclets are not correctly supported now.
104 // Do nothing if this is funclet-based personality.
105 if (Fn.hasPersonalityFn()) {
106 EHPersonality Personality = classifyEHPersonality(Fn.getPersonalityFn());
107 if (isFuncletEHPersonality(Personality))
108 return false;
109 }
110
Bill Wendling7c8f96a2013-01-23 06:43:53 +0000111 ++NumFunProtected;
Bill Wendling782e8342008-11-05 00:00:21 +0000112 return InsertStackProtectors();
Bill Wendling05d84172008-11-04 02:10:20 +0000113}
114
Josh Magee3f1c0e32013-10-29 21:16:16 +0000115/// \param [out] IsLarge is set to true if a protectable array is found and
116/// it is "large" ( >= ssp-buffer-size). In the case of a structure with
117/// multiple arrays, this gets set if any of them is large.
118bool StackProtector::ContainsProtectableArray(Type *Ty, bool &IsLarge,
Josh Magee7245f1d2013-10-30 02:25:14 +0000119 bool Strong,
120 bool InStruct) const {
121 if (!Ty)
122 return false;
Bill Wendlingbfb9b752012-08-17 20:59:56 +0000123 if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
124 if (!AT->getElementType()->isIntegerTy(8)) {
Bill Wendlingbfb9b752012-08-17 20:59:56 +0000125 // If we're on a non-Darwin platform or we're inside of a structure, don't
126 // add stack protectors unless the array is a character array.
Josh Magee3f1c0e32013-10-29 21:16:16 +0000127 // However, in strong mode any array, regardless of type and size,
128 // triggers a protector.
129 if (!Strong && (InStruct || !Trip.isOSDarwin()))
130 return false;
Bill Wendlingbfb9b752012-08-17 20:59:56 +0000131 }
132
133 // If an array has more than SSPBufferSize bytes of allocated space, then we
134 // emit stack protectors.
Mehdi Aminied6edbf2015-07-07 23:38:49 +0000135 if (SSPBufferSize <= M->getDataLayout().getTypeAllocSize(AT)) {
Josh Magee3f1c0e32013-10-29 21:16:16 +0000136 IsLarge = true;
137 return true;
Josh Magee7245f1d2013-10-30 02:25:14 +0000138 }
Josh Magee3f1c0e32013-10-29 21:16:16 +0000139
140 if (Strong)
141 // Require a protector for all arrays in strong mode
Bill Wendlingbfb9b752012-08-17 20:59:56 +0000142 return true;
143 }
144
145 const StructType *ST = dyn_cast<StructType>(Ty);
Josh Magee7245f1d2013-10-30 02:25:14 +0000146 if (!ST)
147 return false;
Bill Wendlingbfb9b752012-08-17 20:59:56 +0000148
Josh Magee3f1c0e32013-10-29 21:16:16 +0000149 bool NeedsProtector = false;
Bill Wendlingbfb9b752012-08-17 20:59:56 +0000150 for (StructType::element_iterator I = ST->element_begin(),
Josh Magee7245f1d2013-10-30 02:25:14 +0000151 E = ST->element_end();
152 I != E; ++I)
Josh Magee3f1c0e32013-10-29 21:16:16 +0000153 if (ContainsProtectableArray(*I, IsLarge, Strong, true)) {
154 // If the element is a protectable array and is large (>= SSPBufferSize)
155 // then we are done. If the protectable array is not large, then
156 // keep looking in case a subsequent element is a large array.
157 if (IsLarge)
158 return true;
159 NeedsProtector = true;
160 }
Bill Wendlingbfb9b752012-08-17 20:59:56 +0000161
Josh Magee3f1c0e32013-10-29 21:16:16 +0000162 return NeedsProtector;
Bill Wendlingbfb9b752012-08-17 20:59:56 +0000163}
164
Bill Wendling7c8f96a2013-01-23 06:43:53 +0000165bool StackProtector::HasAddressTaken(const Instruction *AI) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000166 for (const User *U : AI->users()) {
Bill Wendling7c8f96a2013-01-23 06:43:53 +0000167 if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
168 if (AI == SI->getValueOperand())
169 return true;
170 } else if (const PtrToIntInst *SI = dyn_cast<PtrToIntInst>(U)) {
171 if (AI == SI->getOperand(0))
172 return true;
173 } else if (isa<CallInst>(U)) {
174 return true;
175 } else if (isa<InvokeInst>(U)) {
176 return true;
177 } else if (const SelectInst *SI = dyn_cast<SelectInst>(U)) {
178 if (HasAddressTaken(SI))
179 return true;
180 } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
181 // Keep track of what PHI nodes we have already visited to ensure
182 // they are only visited once.
David Blaikie70573dc2014-11-19 07:49:26 +0000183 if (VisitedPHIs.insert(PN).second)
Bill Wendling7c8f96a2013-01-23 06:43:53 +0000184 if (HasAddressTaken(PN))
185 return true;
186 } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
187 if (HasAddressTaken(GEP))
188 return true;
189 } else if (const BitCastInst *BI = dyn_cast<BitCastInst>(U)) {
190 if (HasAddressTaken(BI))
191 return true;
192 }
193 }
194 return false;
195}
196
197/// \brief Check whether or not this function needs a stack protector based
198/// upon the stack protector level.
199///
200/// We use two heuristics: a standard (ssp) and strong (sspstrong).
201/// The standard heuristic which will add a guard variable to functions that
202/// call alloca with a either a variable size or a size >= SSPBufferSize,
203/// functions with character buffers larger than SSPBufferSize, and functions
204/// with aggregates containing character buffers larger than SSPBufferSize. The
205/// strong heuristic will add a guard variables to functions that call alloca
206/// regardless of size, functions with any buffer regardless of type and size,
207/// functions with aggregates that contain any buffer regardless of type and
208/// size, and functions that contain stack-based variables that have had their
209/// address taken.
210bool StackProtector::RequiresStackProtector() {
211 bool Strong = false;
Josh Magee3f1c0e32013-10-29 21:16:16 +0000212 bool NeedsProtector = false;
Tim Shen00127562016-04-08 21:26:31 +0000213 for (const BasicBlock &BB : *F)
214 for (const Instruction &I : BB)
215 if (const CallInst *CI = dyn_cast<CallInst>(&I))
216 if (CI->getCalledFunction() ==
217 Intrinsic::getDeclaration(F->getParent(),
218 Intrinsic::stackprotector))
219 HasPrologue = true;
220
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +0000221 if (F->hasFnAttribute(Attribute::SafeStack))
222 return false;
223
Duncan P. N. Exon Smith70eb9c52015-02-14 01:44:41 +0000224 if (F->hasFnAttribute(Attribute::StackProtectReq)) {
Josh Magee3f1c0e32013-10-29 21:16:16 +0000225 NeedsProtector = true;
226 Strong = true; // Use the same heuristic as strong to determine SSPLayout
Duncan P. N. Exon Smith70eb9c52015-02-14 01:44:41 +0000227 } else if (F->hasFnAttribute(Attribute::StackProtectStrong))
Bill Wendling7c8f96a2013-01-23 06:43:53 +0000228 Strong = true;
Tim Shen00127562016-04-08 21:26:31 +0000229 else if (HasPrologue)
230 NeedsProtector = true;
Duncan P. N. Exon Smith70eb9c52015-02-14 01:44:41 +0000231 else if (!F->hasFnAttribute(Attribute::StackProtect))
Bill Wendlingeeb04152008-11-18 05:32:11 +0000232 return false;
233
Saleem Abdulrasool57b5fe52014-12-20 21:37:51 +0000234 for (const BasicBlock &BB : *F) {
235 for (const Instruction &I : BB) {
236 if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
Bill Wendling7c8f96a2013-01-23 06:43:53 +0000237 if (AI->isArrayAllocation()) {
238 // SSP-Strong: Enable protectors for any call to alloca, regardless
239 // of size.
240 if (Strong)
241 return true;
Michael Gottesman62c5d712013-08-20 08:46:16 +0000242
Saleem Abdulrasool57b5fe52014-12-20 21:37:51 +0000243 if (const auto *CI = dyn_cast<ConstantInt>(AI->getArraySize())) {
Josh Magee3f1c0e32013-10-29 21:16:16 +0000244 if (CI->getLimitedValue(SSPBufferSize) >= SSPBufferSize) {
Bill Wendling7c8f96a2013-01-23 06:43:53 +0000245 // A call to alloca with size >= SSPBufferSize requires
246 // stack protectors.
Josh Magee3f1c0e32013-10-29 21:16:16 +0000247 Layout.insert(std::make_pair(AI, SSPLK_LargeArray));
248 NeedsProtector = true;
249 } else if (Strong) {
250 // Require protectors for all alloca calls in strong mode.
251 Layout.insert(std::make_pair(AI, SSPLK_SmallArray));
252 NeedsProtector = true;
253 }
Bill Wendlingc02a0aa2013-07-22 20:15:21 +0000254 } else {
255 // A call to alloca with a variable size requires protectors.
Josh Magee3f1c0e32013-10-29 21:16:16 +0000256 Layout.insert(std::make_pair(AI, SSPLK_LargeArray));
257 NeedsProtector = true;
Bill Wendlingc02a0aa2013-07-22 20:15:21 +0000258 }
Josh Magee3f1c0e32013-10-29 21:16:16 +0000259 continue;
Bill Wendling7c8f96a2013-01-23 06:43:53 +0000260 }
261
Josh Magee3f1c0e32013-10-29 21:16:16 +0000262 bool IsLarge = false;
263 if (ContainsProtectableArray(AI->getAllocatedType(), IsLarge, Strong)) {
264 Layout.insert(std::make_pair(AI, IsLarge ? SSPLK_LargeArray
265 : SSPLK_SmallArray));
266 NeedsProtector = true;
267 continue;
268 }
Bill Wendlingeeb04152008-11-18 05:32:11 +0000269
Bill Wendling7c8f96a2013-01-23 06:43:53 +0000270 if (Strong && HasAddressTaken(AI)) {
Michael Gottesman62c5d712013-08-20 08:46:16 +0000271 ++NumAddrTaken;
Josh Magee3f1c0e32013-10-29 21:16:16 +0000272 Layout.insert(std::make_pair(AI, SSPLK_AddrOf));
273 NeedsProtector = true;
Bill Wendling7c8f96a2013-01-23 06:43:53 +0000274 }
Bill Wendlingeeb04152008-11-18 05:32:11 +0000275 }
Bill Wendling7c8f96a2013-01-23 06:43:53 +0000276 }
Bill Wendlingeeb04152008-11-18 05:32:11 +0000277 }
278
Josh Magee3f1c0e32013-10-29 21:16:16 +0000279 return NeedsProtector;
Bill Wendlingeeb04152008-11-18 05:32:11 +0000280}
281
Tim Shene885d5e2016-04-19 19:40:37 +0000282/// Create a stack guard loading and populate whether SelectionDAG SSP is
283/// supported.
284static Value *getStackGuard(const TargetLoweringBase *TLI, Module *M,
285 IRBuilder<> &B,
286 bool *SupportsSelectionDAGSP = nullptr) {
287 if (Value *Guard = TLI->getIRStackGuard(B))
288 return B.CreateLoad(Guard, true, "StackGuard");
289
290 // Use SelectionDAG SSP handling, since there isn't an IR guard.
291 //
292 // This is more or less weird, since we optionally output whether we
293 // should perform a SelectionDAG SP here. The reason is that it's strictly
294 // defined as !TLI->getIRStackGuard(B), where getIRStackGuard is also
295 // mutating. There is no way to get this bit without mutating the IR, so
296 // getting this bit has to happen in this right time.
297 //
298 // We could have define a new function TLI::supportsSelectionDAGSP(), but that
299 // will put more burden on the backends' overriding work, especially when it
300 // actually conveys the same information getIRStackGuard() already gives.
301 if (SupportsSelectionDAGSP)
302 *SupportsSelectionDAGSP = true;
303 TLI->insertSSPDeclarations(*M);
304 return B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackguard));
305}
306
307/// Insert code into the entry block that stores the stack guard
Michael Gottesmana6188f92013-07-22 20:44:11 +0000308/// variable onto the stack:
309///
310/// entry:
311/// StackGuardSlot = alloca i8*
Tim Shene885d5e2016-04-19 19:40:37 +0000312/// StackGuard = <stack guard>
313/// call void @llvm.stackprotector(StackGuard, StackGuardSlot)
Michael Gottesmana6188f92013-07-22 20:44:11 +0000314///
Michael Gottesman5e570682013-08-20 08:36:53 +0000315/// Returns true if the platform/triple supports the stackprotectorcreate pseudo
316/// node.
317static bool CreatePrologue(Function *F, Module *M, ReturnInst *RI,
Tim Shene885d5e2016-04-19 19:40:37 +0000318 const TargetLoweringBase *TLI, AllocaInst *&AI) {
Michael Gottesman5e570682013-08-20 08:36:53 +0000319 bool SupportsSelectionDAGSP = false;
Evgeniy Stepanovdde29e22016-04-05 22:41:50 +0000320 IRBuilder<> B(&F->getEntryBlock().front());
Tim Shen00127562016-04-08 21:26:31 +0000321 PointerType *PtrTy = Type::getInt8PtrTy(RI->getContext());
Craig Topperc0196b12014-04-14 00:51:57 +0000322 AI = B.CreateAlloca(PtrTy, nullptr, "StackGuardSlot");
Tim Shene885d5e2016-04-19 19:40:37 +0000323
Etienne Bergeron22bfa832016-06-07 20:15:35 +0000324 Value *GuardSlot = getStackGuard(TLI, M, B, &SupportsSelectionDAGSP);
David Blaikieff6409d2015-05-18 22:13:54 +0000325 B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackprotector),
Etienne Bergeron22bfa832016-06-07 20:15:35 +0000326 {GuardSlot, AI});
Michael Gottesman5e570682013-08-20 08:36:53 +0000327 return SupportsSelectionDAGSP;
Michael Gottesmana6188f92013-07-22 20:44:11 +0000328}
329
Bill Wendling782e8342008-11-05 00:00:21 +0000330/// InsertStackProtectors - Insert code into the prologue and epilogue of the
331/// function.
332///
333/// - The prologue code loads and stores the stack guard onto the stack.
334/// - The epilogue checks the value stored in the prologue against the original
335/// value. It calls __stack_chk_fail if they differ.
336bool StackProtector::InsertStackProtectors() {
Michael Gottesman76c44be2013-08-20 08:56:26 +0000337 bool SupportsSelectionDAGSP =
Josh Magee7245f1d2013-10-30 02:25:14 +0000338 EnableSelectionDAGSP && !TM->Options.EnableFastISel;
Craig Topperc0196b12014-04-14 00:51:57 +0000339 AllocaInst *AI = nullptr; // Place on stack that stores the stack guard.
Bill Wendlingeb4268d2008-11-07 01:23:58 +0000340
Josh Magee7245f1d2013-10-30 02:25:14 +0000341 for (Function::iterator I = F->begin(), E = F->end(); I != E;) {
Duncan P. N. Exon Smithf1ff53e2015-10-09 22:56:24 +0000342 BasicBlock *BB = &*I++;
Bill Wendlingeeb04152008-11-18 05:32:11 +0000343 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
Michael Gottesmandc985ef2013-08-20 08:56:28 +0000344 if (!RI)
345 continue;
Bill Wendlingeb4268d2008-11-07 01:23:58 +0000346
Etienne Bergeron22bfa832016-06-07 20:15:35 +0000347 // Generate prologue instrumentation if not already generated.
Michael Gottesman8afcf3a2013-08-09 21:26:18 +0000348 if (!HasPrologue) {
349 HasPrologue = true;
Tim Shene885d5e2016-04-19 19:40:37 +0000350 SupportsSelectionDAGSP &= CreatePrologue(F, M, RI, TLI, AI);
Michael Gottesman62c5d712013-08-20 08:46:16 +0000351 }
Michael Gottesman5e570682013-08-20 08:36:53 +0000352
Etienne Bergeron22bfa832016-06-07 20:15:35 +0000353 // SelectionDAG based code generation. Nothing else needs to be done here.
354 // The epilogue instrumentation is postponed to SelectionDAG.
355 if (SupportsSelectionDAGSP)
356 break;
357
358 // Set HasIRCheck to true, so that SelectionDAG will not generate its own
359 // version. SelectionDAG called 'shouldEmitSDCheck' to check whether
360 // instrumentation has already been generated.
361 HasIRCheck = true;
362
363 // Generate epilogue instrumentation. The epilogue intrumentation can be
364 // function-based or inlined depending on which mechanism the target is
365 // providing.
366 if (Value* GuardCheck = TLI->getSSPStackGuardCheck(*M)) {
367 // Generate the function-based epilogue instrumentation.
368 // The target provides a guard check function, generate a call to it.
369 IRBuilder<> B(RI);
370 LoadInst *Guard = B.CreateLoad(AI, true, "Guard");
371 CallInst *Call = B.CreateCall(GuardCheck, {Guard});
372 llvm::Function *Function = cast<llvm::Function>(GuardCheck);
373 Call->setAttributes(Function->getAttributes());
374 Call->setCallingConv(Function->getCallingConv());
375 } else {
376 // Generate the epilogue with inline instrumentation.
Michael Gottesman56e246b2013-08-20 08:46:13 +0000377 // If we do not support SelectionDAG based tail calls, generate IR level
378 // tail calls.
379 //
Michael Gottesman5e570682013-08-20 08:36:53 +0000380 // For each block with a return instruction, convert this:
381 //
382 // return:
383 // ...
384 // ret ...
385 //
386 // into this:
387 //
388 // return:
389 // ...
Tim Shene885d5e2016-04-19 19:40:37 +0000390 // %1 = <stack guard>
Michael Gottesman5e570682013-08-20 08:36:53 +0000391 // %2 = load StackGuardSlot
392 // %3 = cmp i1 %1, %2
393 // br i1 %3, label %SP_return, label %CallStackCheckFailBlk
394 //
395 // SP_return:
396 // ret ...
397 //
398 // CallStackCheckFailBlk:
399 // call void @__stack_chk_fail()
400 // unreachable
401
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
Michael Gottesman62c5d712013-08-20 08:46:16 +0000404 // fail BB generated by the stack protector pseudo instruction.
Michael Gottesman5e570682013-08-20 08:36:53 +0000405 BasicBlock *FailBB = CreateFailBB();
Michael Gottesman62c5d712013-08-20 08:46:16 +0000406
Michael Gottesman5e570682013-08-20 08:36:53 +0000407 // Split the basic block before the return instruction.
Duncan P. N. Exon Smithf1ff53e2015-10-09 22:56:24 +0000408 BasicBlock *NewBB = BB->splitBasicBlock(RI->getIterator(), "SP_return");
Michael Gottesman62c5d712013-08-20 08:46:16 +0000409
Michael Gottesman5e570682013-08-20 08:36:53 +0000410 // Update the dominator tree if we need to.
411 if (DT && DT->isReachableFromEntry(BB)) {
412 DT->addNewBlock(NewBB, BB);
413 DT->addNewBlock(FailBB, BB);
414 }
Michael Gottesman62c5d712013-08-20 08:46:16 +0000415
Michael Gottesman5e570682013-08-20 08:36:53 +0000416 // Remove default branch instruction to the new BB.
417 BB->getTerminator()->eraseFromParent();
Michael Gottesman62c5d712013-08-20 08:46:16 +0000418
Michael Gottesman5e570682013-08-20 08:36:53 +0000419 // Move the newly created basic block to the point right after the old
420 // basic block so that it's in the "fall through" position.
421 NewBB->moveAfter(BB);
Michael Gottesman62c5d712013-08-20 08:46:16 +0000422
Michael Gottesman5e570682013-08-20 08:36:53 +0000423 // Generate the stack protector instructions in the old basic block.
Benjamin Kramerd93817f2013-09-09 17:38:01 +0000424 IRBuilder<> B(BB);
Tim Shene885d5e2016-04-19 19:40:37 +0000425 Value *Guard = getStackGuard(TLI, M, B);
426 LoadInst *LI2 = B.CreateLoad(AI, true);
427 Value *Cmp = B.CreateICmpEQ(Guard, LI2);
Cong Houe93b8e12015-12-22 18:56:14 +0000428 auto SuccessProb =
429 BranchProbabilityInfo::getBranchProbStackProtector(true);
430 auto FailureProb =
431 BranchProbabilityInfo::getBranchProbStackProtector(false);
Akira Hatanakab9991a22014-12-01 04:27:03 +0000432 MDNode *Weights = MDBuilder(F->getContext())
Cong Houe93b8e12015-12-22 18:56:14 +0000433 .createBranchWeights(SuccessProb.getNumerator(),
434 FailureProb.getNumerator());
Akira Hatanakab9991a22014-12-01 04:27:03 +0000435 B.CreateCondBr(Cmp, NewBB, FailBB, Weights);
Bill Wendlinga0826e182008-11-06 23:55:49 +0000436 }
Bill Wendling05d84172008-11-04 02:10:20 +0000437 }
Bill Wendling782e8342008-11-05 00:00:21 +0000438
Saleem Abdulrasool90c224a2014-12-21 21:52:38 +0000439 // Return if we didn't modify any basic blocks. i.e., there are no return
Bill Wendlinga0826e182008-11-06 23:55:49 +0000440 // statements in the function.
Rafael Espindola84921b92015-10-24 23:11:13 +0000441 return HasPrologue;
Bill Wendling05d84172008-11-04 02:10:20 +0000442}
443
444/// CreateFailBB - Create a basic block to jump to when the stack protector
445/// check fails.
Bill Wendling782e8342008-11-05 00:00:21 +0000446BasicBlock *StackProtector::CreateFailBB() {
Rafael Espindolaaad6c242013-06-07 16:35:57 +0000447 LLVMContext &Context = F->getContext();
448 BasicBlock *FailBB = BasicBlock::Create(Context, "CallStackCheckFailBlk", F);
Benjamin Kramerd93817f2013-09-09 17:38:01 +0000449 IRBuilder<> B(FailBB);
Simon Pilgrim2bfd9122014-11-29 19:18:21 +0000450 if (Trip.isOSOpenBSD()) {
Saleem Abdulrasool90c224a2014-12-21 21:52:38 +0000451 Constant *StackChkFail =
452 M->getOrInsertFunction("__stack_smash_handler",
453 Type::getVoidTy(Context),
454 Type::getInt8PtrTy(Context), nullptr);
Rafael Espindolaaad6c242013-06-07 16:35:57 +0000455
Benjamin Kramerd93817f2013-09-09 17:38:01 +0000456 B.CreateCall(StackChkFail, B.CreateGlobalStringPtr(F->getName(), "SSH"));
Rafael Espindolaaad6c242013-06-07 16:35:57 +0000457 } else {
Saleem Abdulrasool90c224a2014-12-21 21:52:38 +0000458 Constant *StackChkFail =
459 M->getOrInsertFunction("__stack_chk_fail", Type::getVoidTy(Context),
460 nullptr);
David Blaikieff6409d2015-05-18 22:13:54 +0000461 B.CreateCall(StackChkFail, {});
Rafael Espindolaaad6c242013-06-07 16:35:57 +0000462 }
Benjamin Kramerd93817f2013-09-09 17:38:01 +0000463 B.CreateUnreachable();
Bill Wendling782e8342008-11-05 00:00:21 +0000464 return FailBB;
Bill Wendling05d84172008-11-04 02:10:20 +0000465}
Tim Shen00127562016-04-08 21:26:31 +0000466
467bool StackProtector::shouldEmitSDCheck(const BasicBlock &BB) const {
468 return HasPrologue && !HasIRCheck && dyn_cast<ReturnInst>(BB.getTerminator());
469}