blob: e3fdb96f62002ddbb2183dab246aca80d99804a2 [file] [log] [blame]
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001//===- StackProtector.cpp - Stack Protector Insertion ---------------------===//
Bill Wendling05d84172008-11-04 02:10:20 +00002//
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
Bill Wendling7c8f96a2013-01-23 06:43:53 +000017#include "llvm/ADT/SmallPtrSet.h"
18#include "llvm/ADT/Statistic.h"
Akira Hatanakab9991a22014-12-01 04:27:03 +000019#include "llvm/Analysis/BranchProbabilityInfo.h"
Etienne Bergeron22bfa832016-06-07 20:15:35 +000020#include "llvm/Analysis/EHPersonalities.h"
David Bozier51599682017-02-28 16:02:37 +000021#include "llvm/Analysis/OptimizationDiagnosticInfo.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000022#include "llvm/CodeGen/Passes.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000023#include "llvm/CodeGen/StackProtector.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/Attributes.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000025#include "llvm/IR/BasicBlock.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/Constants.h"
27#include "llvm/IR/DataLayout.h"
Yunzhong Gaob3869552016-06-30 18:49:04 +000028#include "llvm/IR/DebugInfo.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000029#include "llvm/IR/DebugLoc.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000030#include "llvm/IR/DerivedTypes.h"
31#include "llvm/IR/Function.h"
Benjamin Kramerd93817f2013-09-09 17:38:01 +000032#include "llvm/IR/IRBuilder.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000033#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000034#include "llvm/IR/Instructions.h"
35#include "llvm/IR/Intrinsics.h"
Akira Hatanakab9991a22014-12-01 04:27:03 +000036#include "llvm/IR/MDBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000037#include "llvm/IR/Module.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000038#include "llvm/IR/Type.h"
39#include "llvm/IR/User.h"
40#include "llvm/Pass.h"
41#include "llvm/Support/Casting.h"
Bill Wendling05d84172008-11-04 02:10:20 +000042#include "llvm/Support/CommandLine.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000043#include "llvm/Target/TargetLowering.h"
44#include "llvm/Target/TargetMachine.h"
45#include "llvm/Target/TargetOptions.h"
Eric Christopherd9134482014-08-04 21:25:23 +000046#include "llvm/Target/TargetSubtargetInfo.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000047#include <utility>
48
Bill Wendling05d84172008-11-04 02:10:20 +000049using namespace llvm;
50
Chandler Carruth1b9dde02014-04-22 02:02:50 +000051#define DEBUG_TYPE "stack-protector"
52
Bill Wendling7c8f96a2013-01-23 06:43:53 +000053STATISTIC(NumFunProtected, "Number of functions protected");
54STATISTIC(NumAddrTaken, "Number of local variables that have their address"
55 " taken.");
56
Josh Magee7245f1d2013-10-30 02:25:14 +000057static cl::opt<bool> EnableSelectionDAGSP("enable-selectiondag-sp",
58 cl::init(true), cl::Hidden);
Michael Gottesman5e570682013-08-20 08:36:53 +000059
Bill Wendling05d84172008-11-04 02:10:20 +000060char StackProtector::ID = 0;
Silviu Baranga0a020f02016-09-14 14:09:43 +000061INITIALIZE_TM_PASS(StackProtector, "stack-protector", "Insert stack protectors",
David Bozier51599682017-02-28 16:02:37 +000062 false, true)
Bill Wendling05d84172008-11-04 02:10:20 +000063
Bill Wendlingafc10362013-06-19 20:51:24 +000064FunctionPass *llvm::createStackProtectorPass(const TargetMachine *TM) {
65 return new StackProtector(TM);
Bill Wendling05d84172008-11-04 02:10:20 +000066}
67
Josh Magee7245f1d2013-10-30 02:25:14 +000068StackProtector::SSPLayoutKind
69StackProtector::getSSPLayout(const AllocaInst *AI) const {
Josh Magee3f1c0e32013-10-29 21:16:16 +000070 return AI ? Layout.lookup(AI) : SSPLK_None;
71}
72
Hal Finkela69e5b82014-01-20 19:49:14 +000073void StackProtector::adjustForColoring(const AllocaInst *From,
74 const AllocaInst *To) {
75 // When coloring replaces one alloca with another, transfer the SSPLayoutKind
76 // tag from the remapped to the target alloca. The remapped alloca should
77 // have a size smaller than or equal to the replacement alloca.
78 SSPLayoutMap::iterator I = Layout.find(From);
79 if (I != Layout.end()) {
80 SSPLayoutKind Kind = I->second;
81 Layout.erase(I);
82
83 // Transfer the tag, but make sure that SSPLK_AddrOf does not overwrite
84 // SSPLK_SmallArray or SSPLK_LargeArray, and make sure that
85 // SSPLK_SmallArray does not overwrite SSPLK_LargeArray.
86 I = Layout.find(To);
87 if (I == Layout.end())
88 Layout.insert(std::make_pair(To, Kind));
89 else if (I->second != SSPLK_LargeArray && Kind != SSPLK_AddrOf)
90 I->second = Kind;
91 }
92}
93
Bill Wendling05d84172008-11-04 02:10:20 +000094bool StackProtector::runOnFunction(Function &Fn) {
95 F = &Fn;
96 M = F->getParent();
Chandler Carruth73523022014-01-13 13:07:17 +000097 DominatorTreeWrapperPass *DTWP =
98 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
Craig Topperc0196b12014-04-14 00:51:57 +000099 DT = DTWP ? &DTWP->getDomTree() : nullptr;
Eric Christopher33726202015-01-27 08:48:42 +0000100 TLI = TM->getSubtargetImpl(Fn)->getTargetLowering();
Tim Shen00127562016-04-08 21:26:31 +0000101 HasPrologue = false;
102 HasIRCheck = false;
Bill Wendling05d84172008-11-04 02:10:20 +0000103
Duncan P. N. Exon Smith70eb9c52015-02-14 01:44:41 +0000104 Attribute Attr = Fn.getFnAttribute("stack-protector-buffer-size");
Renato Goline195f9c2014-01-21 10:24:35 +0000105 if (Attr.isStringAttribute() &&
106 Attr.getValueAsString().getAsInteger(10, SSPBufferSize))
Etienne Bergeron22bfa832016-06-07 20:15:35 +0000107 return false; // Invalid integer string
Bill Wendlingc02a0aa2013-07-22 20:15:21 +0000108
Josh Mageeadfde5f2014-04-17 19:08:36 +0000109 if (!RequiresStackProtector())
110 return false;
111
Etienne Bergeron22bfa832016-06-07 20:15:35 +0000112 // TODO(etienneb): Functions with funclets are not correctly supported now.
113 // Do nothing if this is funclet-based personality.
114 if (Fn.hasPersonalityFn()) {
115 EHPersonality Personality = classifyEHPersonality(Fn.getPersonalityFn());
116 if (isFuncletEHPersonality(Personality))
117 return false;
118 }
119
Bill Wendling7c8f96a2013-01-23 06:43:53 +0000120 ++NumFunProtected;
Bill Wendling782e8342008-11-05 00:00:21 +0000121 return InsertStackProtectors();
Bill Wendling05d84172008-11-04 02:10:20 +0000122}
123
Josh Magee3f1c0e32013-10-29 21:16:16 +0000124/// \param [out] IsLarge is set to true if a protectable array is found and
125/// it is "large" ( >= ssp-buffer-size). In the case of a structure with
126/// multiple arrays, this gets set if any of them is large.
127bool StackProtector::ContainsProtectableArray(Type *Ty, bool &IsLarge,
Josh Magee7245f1d2013-10-30 02:25:14 +0000128 bool Strong,
129 bool InStruct) const {
130 if (!Ty)
131 return false;
Bill Wendlingbfb9b752012-08-17 20:59:56 +0000132 if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
133 if (!AT->getElementType()->isIntegerTy(8)) {
Bill Wendlingbfb9b752012-08-17 20:59:56 +0000134 // If we're on a non-Darwin platform or we're inside of a structure, don't
135 // add stack protectors unless the array is a character array.
Josh Magee3f1c0e32013-10-29 21:16:16 +0000136 // However, in strong mode any array, regardless of type and size,
137 // triggers a protector.
138 if (!Strong && (InStruct || !Trip.isOSDarwin()))
139 return false;
Bill Wendlingbfb9b752012-08-17 20:59:56 +0000140 }
141
142 // If an array has more than SSPBufferSize bytes of allocated space, then we
143 // emit stack protectors.
Mehdi Aminied6edbf2015-07-07 23:38:49 +0000144 if (SSPBufferSize <= M->getDataLayout().getTypeAllocSize(AT)) {
Josh Magee3f1c0e32013-10-29 21:16:16 +0000145 IsLarge = true;
146 return true;
Josh Magee7245f1d2013-10-30 02:25:14 +0000147 }
Josh Magee3f1c0e32013-10-29 21:16:16 +0000148
149 if (Strong)
150 // Require a protector for all arrays in strong mode
Bill Wendlingbfb9b752012-08-17 20:59:56 +0000151 return true;
152 }
153
154 const StructType *ST = dyn_cast<StructType>(Ty);
Josh Magee7245f1d2013-10-30 02:25:14 +0000155 if (!ST)
156 return false;
Bill Wendlingbfb9b752012-08-17 20:59:56 +0000157
Josh Magee3f1c0e32013-10-29 21:16:16 +0000158 bool NeedsProtector = false;
Bill Wendlingbfb9b752012-08-17 20:59:56 +0000159 for (StructType::element_iterator I = ST->element_begin(),
Josh Magee7245f1d2013-10-30 02:25:14 +0000160 E = ST->element_end();
161 I != E; ++I)
Josh Magee3f1c0e32013-10-29 21:16:16 +0000162 if (ContainsProtectableArray(*I, IsLarge, Strong, true)) {
163 // If the element is a protectable array and is large (>= SSPBufferSize)
164 // then we are done. If the protectable array is not large, then
165 // keep looking in case a subsequent element is a large array.
166 if (IsLarge)
167 return true;
168 NeedsProtector = true;
169 }
Bill Wendlingbfb9b752012-08-17 20:59:56 +0000170
Josh Magee3f1c0e32013-10-29 21:16:16 +0000171 return NeedsProtector;
Bill Wendlingbfb9b752012-08-17 20:59:56 +0000172}
173
Bill Wendling7c8f96a2013-01-23 06:43:53 +0000174bool StackProtector::HasAddressTaken(const Instruction *AI) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000175 for (const User *U : AI->users()) {
Bill Wendling7c8f96a2013-01-23 06:43:53 +0000176 if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
177 if (AI == SI->getValueOperand())
178 return true;
179 } else if (const PtrToIntInst *SI = dyn_cast<PtrToIntInst>(U)) {
180 if (AI == SI->getOperand(0))
181 return true;
182 } else if (isa<CallInst>(U)) {
183 return true;
184 } else if (isa<InvokeInst>(U)) {
185 return true;
186 } else if (const SelectInst *SI = dyn_cast<SelectInst>(U)) {
187 if (HasAddressTaken(SI))
188 return true;
189 } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
190 // Keep track of what PHI nodes we have already visited to ensure
191 // they are only visited once.
David Blaikie70573dc2014-11-19 07:49:26 +0000192 if (VisitedPHIs.insert(PN).second)
Bill Wendling7c8f96a2013-01-23 06:43:53 +0000193 if (HasAddressTaken(PN))
194 return true;
195 } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
196 if (HasAddressTaken(GEP))
197 return true;
198 } else if (const BitCastInst *BI = dyn_cast<BitCastInst>(U)) {
199 if (HasAddressTaken(BI))
200 return true;
201 }
202 }
203 return false;
204}
205
206/// \brief Check whether or not this function needs a stack protector based
207/// upon the stack protector level.
208///
209/// We use two heuristics: a standard (ssp) and strong (sspstrong).
210/// The standard heuristic which will add a guard variable to functions that
211/// call alloca with a either a variable size or a size >= SSPBufferSize,
212/// functions with character buffers larger than SSPBufferSize, and functions
213/// with aggregates containing character buffers larger than SSPBufferSize. The
214/// strong heuristic will add a guard variables to functions that call alloca
215/// regardless of size, functions with any buffer regardless of type and size,
216/// functions with aggregates that contain any buffer regardless of type and
217/// size, and functions that contain stack-based variables that have had their
218/// address taken.
219bool StackProtector::RequiresStackProtector() {
220 bool Strong = false;
Josh Magee3f1c0e32013-10-29 21:16:16 +0000221 bool NeedsProtector = false;
Tim Shen00127562016-04-08 21:26:31 +0000222 for (const BasicBlock &BB : *F)
223 for (const Instruction &I : BB)
224 if (const CallInst *CI = dyn_cast<CallInst>(&I))
225 if (CI->getCalledFunction() ==
226 Intrinsic::getDeclaration(F->getParent(),
227 Intrinsic::stackprotector))
228 HasPrologue = true;
229
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +0000230 if (F->hasFnAttribute(Attribute::SafeStack))
231 return false;
232
David Bozier51599682017-02-28 16:02:37 +0000233 // We are constructing the OptimizationRemarkEmitter on the fly rather than
234 // using the analysis pass to avoid building DominatorTree and LoopInfo which
235 // are not available this late in the IR pipeline.
236 OptimizationRemarkEmitter ORE(F);
David Bozier51599682017-02-28 16:02:37 +0000237
Duncan P. N. Exon Smith70eb9c52015-02-14 01:44:41 +0000238 if (F->hasFnAttribute(Attribute::StackProtectReq)) {
David Bozier51599682017-02-28 16:02:37 +0000239 ORE.emit(OptimizationRemark(DEBUG_TYPE, "StackProtectorRequested", F)
Adam Nemet5361b822017-03-09 06:10:27 +0000240 << "Stack protection applied to function "
241 << ore::NV("Function", F)
242 << " due to a function attribute or command-line switch");
Josh Magee3f1c0e32013-10-29 21:16:16 +0000243 NeedsProtector = true;
244 Strong = true; // Use the same heuristic as strong to determine SSPLayout
Duncan P. N. Exon Smith70eb9c52015-02-14 01:44:41 +0000245 } else if (F->hasFnAttribute(Attribute::StackProtectStrong))
Bill Wendling7c8f96a2013-01-23 06:43:53 +0000246 Strong = true;
Tim Shen00127562016-04-08 21:26:31 +0000247 else if (HasPrologue)
248 NeedsProtector = true;
Duncan P. N. Exon Smith70eb9c52015-02-14 01:44:41 +0000249 else if (!F->hasFnAttribute(Attribute::StackProtect))
Bill Wendlingeeb04152008-11-18 05:32:11 +0000250 return false;
251
Saleem Abdulrasool57b5fe52014-12-20 21:37:51 +0000252 for (const BasicBlock &BB : *F) {
253 for (const Instruction &I : BB) {
254 if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
Bill Wendling7c8f96a2013-01-23 06:43:53 +0000255 if (AI->isArrayAllocation()) {
David Bozier51599682017-02-28 16:02:37 +0000256 OptimizationRemark Remark(DEBUG_TYPE, "StackProtectorAllocaOrArray",
257 &I);
Adam Nemet5361b822017-03-09 06:10:27 +0000258 Remark
259 << "Stack protection applied to function "
260 << ore::NV("Function", F)
261 << " due to a call to alloca or use of a variable length array";
Saleem Abdulrasool57b5fe52014-12-20 21:37:51 +0000262 if (const auto *CI = dyn_cast<ConstantInt>(AI->getArraySize())) {
Josh Magee3f1c0e32013-10-29 21:16:16 +0000263 if (CI->getLimitedValue(SSPBufferSize) >= SSPBufferSize) {
Bill Wendling7c8f96a2013-01-23 06:43:53 +0000264 // A call to alloca with size >= SSPBufferSize requires
265 // stack protectors.
Josh Magee3f1c0e32013-10-29 21:16:16 +0000266 Layout.insert(std::make_pair(AI, SSPLK_LargeArray));
David Bozier51599682017-02-28 16:02:37 +0000267 ORE.emit(Remark);
Josh Magee3f1c0e32013-10-29 21:16:16 +0000268 NeedsProtector = true;
269 } else if (Strong) {
270 // Require protectors for all alloca calls in strong mode.
271 Layout.insert(std::make_pair(AI, SSPLK_SmallArray));
David Bozier51599682017-02-28 16:02:37 +0000272 ORE.emit(Remark);
Josh Magee3f1c0e32013-10-29 21:16:16 +0000273 NeedsProtector = true;
274 }
Bill Wendlingc02a0aa2013-07-22 20:15:21 +0000275 } else {
276 // A call to alloca with a variable size requires protectors.
Josh Magee3f1c0e32013-10-29 21:16:16 +0000277 Layout.insert(std::make_pair(AI, SSPLK_LargeArray));
David Bozier51599682017-02-28 16:02:37 +0000278 ORE.emit(Remark);
Josh Magee3f1c0e32013-10-29 21:16:16 +0000279 NeedsProtector = true;
Bill Wendlingc02a0aa2013-07-22 20:15:21 +0000280 }
Josh Magee3f1c0e32013-10-29 21:16:16 +0000281 continue;
Bill Wendling7c8f96a2013-01-23 06:43:53 +0000282 }
283
Josh Magee3f1c0e32013-10-29 21:16:16 +0000284 bool IsLarge = false;
285 if (ContainsProtectableArray(AI->getAllocatedType(), IsLarge, Strong)) {
286 Layout.insert(std::make_pair(AI, IsLarge ? SSPLK_LargeArray
287 : SSPLK_SmallArray));
David Bozier51599682017-02-28 16:02:37 +0000288 ORE.emit(OptimizationRemark(DEBUG_TYPE, "StackProtectorBuffer", &I)
Adam Nemet5361b822017-03-09 06:10:27 +0000289 << "Stack protection applied to function "
290 << ore::NV("Function", F)
291 << " due to a stack allocated buffer or struct containing a "
292 "buffer");
Josh Magee3f1c0e32013-10-29 21:16:16 +0000293 NeedsProtector = true;
294 continue;
295 }
Bill Wendlingeeb04152008-11-18 05:32:11 +0000296
Bill Wendling7c8f96a2013-01-23 06:43:53 +0000297 if (Strong && HasAddressTaken(AI)) {
Michael Gottesman62c5d712013-08-20 08:46:16 +0000298 ++NumAddrTaken;
Josh Magee3f1c0e32013-10-29 21:16:16 +0000299 Layout.insert(std::make_pair(AI, SSPLK_AddrOf));
David Bozier51599682017-02-28 16:02:37 +0000300 ORE.emit(
301 OptimizationRemark(DEBUG_TYPE, "StackProtectorAddressTaken", &I)
Adam Nemet5361b822017-03-09 06:10:27 +0000302 << "Stack protection applied to function "
303 << ore::NV("Function", F)
304 << " due to the address of a local variable being taken");
Josh Magee3f1c0e32013-10-29 21:16:16 +0000305 NeedsProtector = true;
Bill Wendling7c8f96a2013-01-23 06:43:53 +0000306 }
Bill Wendlingeeb04152008-11-18 05:32:11 +0000307 }
Bill Wendling7c8f96a2013-01-23 06:43:53 +0000308 }
Bill Wendlingeeb04152008-11-18 05:32:11 +0000309 }
310
Josh Magee3f1c0e32013-10-29 21:16:16 +0000311 return NeedsProtector;
Bill Wendlingeeb04152008-11-18 05:32:11 +0000312}
313
Tim Shene885d5e2016-04-19 19:40:37 +0000314/// Create a stack guard loading and populate whether SelectionDAG SSP is
315/// supported.
316static Value *getStackGuard(const TargetLoweringBase *TLI, Module *M,
317 IRBuilder<> &B,
318 bool *SupportsSelectionDAGSP = nullptr) {
319 if (Value *Guard = TLI->getIRStackGuard(B))
320 return B.CreateLoad(Guard, true, "StackGuard");
321
322 // Use SelectionDAG SSP handling, since there isn't an IR guard.
323 //
324 // This is more or less weird, since we optionally output whether we
325 // should perform a SelectionDAG SP here. The reason is that it's strictly
326 // defined as !TLI->getIRStackGuard(B), where getIRStackGuard is also
327 // mutating. There is no way to get this bit without mutating the IR, so
328 // getting this bit has to happen in this right time.
329 //
330 // We could have define a new function TLI::supportsSelectionDAGSP(), but that
331 // will put more burden on the backends' overriding work, especially when it
332 // actually conveys the same information getIRStackGuard() already gives.
333 if (SupportsSelectionDAGSP)
334 *SupportsSelectionDAGSP = true;
335 TLI->insertSSPDeclarations(*M);
336 return B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackguard));
337}
338
339/// Insert code into the entry block that stores the stack guard
Michael Gottesmana6188f92013-07-22 20:44:11 +0000340/// variable onto the stack:
341///
342/// entry:
343/// StackGuardSlot = alloca i8*
Tim Shene885d5e2016-04-19 19:40:37 +0000344/// StackGuard = <stack guard>
345/// call void @llvm.stackprotector(StackGuard, StackGuardSlot)
Michael Gottesmana6188f92013-07-22 20:44:11 +0000346///
Michael Gottesman5e570682013-08-20 08:36:53 +0000347/// Returns true if the platform/triple supports the stackprotectorcreate pseudo
348/// node.
349static bool CreatePrologue(Function *F, Module *M, ReturnInst *RI,
Tim Shene885d5e2016-04-19 19:40:37 +0000350 const TargetLoweringBase *TLI, AllocaInst *&AI) {
Michael Gottesman5e570682013-08-20 08:36:53 +0000351 bool SupportsSelectionDAGSP = false;
Evgeniy Stepanovdde29e22016-04-05 22:41:50 +0000352 IRBuilder<> B(&F->getEntryBlock().front());
Tim Shen00127562016-04-08 21:26:31 +0000353 PointerType *PtrTy = Type::getInt8PtrTy(RI->getContext());
Craig Topperc0196b12014-04-14 00:51:57 +0000354 AI = B.CreateAlloca(PtrTy, nullptr, "StackGuardSlot");
Tim Shene885d5e2016-04-19 19:40:37 +0000355
Etienne Bergeron22bfa832016-06-07 20:15:35 +0000356 Value *GuardSlot = getStackGuard(TLI, M, B, &SupportsSelectionDAGSP);
David Blaikieff6409d2015-05-18 22:13:54 +0000357 B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackprotector),
Etienne Bergeron22bfa832016-06-07 20:15:35 +0000358 {GuardSlot, AI});
Michael Gottesman5e570682013-08-20 08:36:53 +0000359 return SupportsSelectionDAGSP;
Michael Gottesmana6188f92013-07-22 20:44:11 +0000360}
361
Bill Wendling782e8342008-11-05 00:00:21 +0000362/// InsertStackProtectors - Insert code into the prologue and epilogue of the
363/// function.
364///
365/// - The prologue code loads and stores the stack guard onto the stack.
366/// - The epilogue checks the value stored in the prologue against the original
367/// value. It calls __stack_chk_fail if they differ.
368bool StackProtector::InsertStackProtectors() {
Michael Gottesman76c44be2013-08-20 08:56:26 +0000369 bool SupportsSelectionDAGSP =
Josh Magee7245f1d2013-10-30 02:25:14 +0000370 EnableSelectionDAGSP && !TM->Options.EnableFastISel;
Craig Topperc0196b12014-04-14 00:51:57 +0000371 AllocaInst *AI = nullptr; // Place on stack that stores the stack guard.
Bill Wendlingeb4268d2008-11-07 01:23:58 +0000372
Josh Magee7245f1d2013-10-30 02:25:14 +0000373 for (Function::iterator I = F->begin(), E = F->end(); I != E;) {
Duncan P. N. Exon Smithf1ff53e2015-10-09 22:56:24 +0000374 BasicBlock *BB = &*I++;
Bill Wendlingeeb04152008-11-18 05:32:11 +0000375 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
Michael Gottesmandc985ef2013-08-20 08:56:28 +0000376 if (!RI)
377 continue;
Bill Wendlingeb4268d2008-11-07 01:23:58 +0000378
Etienne Bergeron22bfa832016-06-07 20:15:35 +0000379 // Generate prologue instrumentation if not already generated.
Michael Gottesman8afcf3a2013-08-09 21:26:18 +0000380 if (!HasPrologue) {
381 HasPrologue = true;
Tim Shene885d5e2016-04-19 19:40:37 +0000382 SupportsSelectionDAGSP &= CreatePrologue(F, M, RI, TLI, AI);
Michael Gottesman62c5d712013-08-20 08:46:16 +0000383 }
Michael Gottesman5e570682013-08-20 08:36:53 +0000384
Etienne Bergeron22bfa832016-06-07 20:15:35 +0000385 // SelectionDAG based code generation. Nothing else needs to be done here.
386 // The epilogue instrumentation is postponed to SelectionDAG.
387 if (SupportsSelectionDAGSP)
388 break;
389
390 // Set HasIRCheck to true, so that SelectionDAG will not generate its own
391 // version. SelectionDAG called 'shouldEmitSDCheck' to check whether
392 // instrumentation has already been generated.
393 HasIRCheck = true;
394
395 // Generate epilogue instrumentation. The epilogue intrumentation can be
396 // function-based or inlined depending on which mechanism the target is
397 // providing.
398 if (Value* GuardCheck = TLI->getSSPStackGuardCheck(*M)) {
399 // Generate the function-based epilogue instrumentation.
400 // The target provides a guard check function, generate a call to it.
401 IRBuilder<> B(RI);
402 LoadInst *Guard = B.CreateLoad(AI, true, "Guard");
403 CallInst *Call = B.CreateCall(GuardCheck, {Guard});
404 llvm::Function *Function = cast<llvm::Function>(GuardCheck);
405 Call->setAttributes(Function->getAttributes());
406 Call->setCallingConv(Function->getCallingConv());
407 } else {
408 // Generate the epilogue with inline instrumentation.
Michael Gottesman56e246b2013-08-20 08:46:13 +0000409 // If we do not support SelectionDAG based tail calls, generate IR level
410 // tail calls.
411 //
Michael Gottesman5e570682013-08-20 08:36:53 +0000412 // For each block with a return instruction, convert this:
413 //
414 // return:
415 // ...
416 // ret ...
417 //
418 // into this:
419 //
420 // return:
421 // ...
Tim Shene885d5e2016-04-19 19:40:37 +0000422 // %1 = <stack guard>
Michael Gottesman5e570682013-08-20 08:36:53 +0000423 // %2 = load StackGuardSlot
424 // %3 = cmp i1 %1, %2
425 // br i1 %3, label %SP_return, label %CallStackCheckFailBlk
426 //
427 // SP_return:
428 // ret ...
429 //
430 // CallStackCheckFailBlk:
431 // call void @__stack_chk_fail()
432 // unreachable
433
434 // Create the FailBB. We duplicate the BB every time since the MI tail
435 // merge pass will merge together all of the various BB into one including
Michael Gottesman62c5d712013-08-20 08:46:16 +0000436 // fail BB generated by the stack protector pseudo instruction.
Michael Gottesman5e570682013-08-20 08:36:53 +0000437 BasicBlock *FailBB = CreateFailBB();
Michael Gottesman62c5d712013-08-20 08:46:16 +0000438
Michael Gottesman5e570682013-08-20 08:36:53 +0000439 // Split the basic block before the return instruction.
Duncan P. N. Exon Smithf1ff53e2015-10-09 22:56:24 +0000440 BasicBlock *NewBB = BB->splitBasicBlock(RI->getIterator(), "SP_return");
Michael Gottesman62c5d712013-08-20 08:46:16 +0000441
Michael Gottesman5e570682013-08-20 08:36:53 +0000442 // Update the dominator tree if we need to.
443 if (DT && DT->isReachableFromEntry(BB)) {
444 DT->addNewBlock(NewBB, BB);
445 DT->addNewBlock(FailBB, BB);
446 }
Michael Gottesman62c5d712013-08-20 08:46:16 +0000447
Michael Gottesman5e570682013-08-20 08:36:53 +0000448 // Remove default branch instruction to the new BB.
449 BB->getTerminator()->eraseFromParent();
Michael Gottesman62c5d712013-08-20 08:46:16 +0000450
Michael Gottesman5e570682013-08-20 08:36:53 +0000451 // Move the newly created basic block to the point right after the old
452 // basic block so that it's in the "fall through" position.
453 NewBB->moveAfter(BB);
Michael Gottesman62c5d712013-08-20 08:46:16 +0000454
Michael Gottesman5e570682013-08-20 08:36:53 +0000455 // Generate the stack protector instructions in the old basic block.
Benjamin Kramerd93817f2013-09-09 17:38:01 +0000456 IRBuilder<> B(BB);
Tim Shene885d5e2016-04-19 19:40:37 +0000457 Value *Guard = getStackGuard(TLI, M, B);
458 LoadInst *LI2 = B.CreateLoad(AI, true);
459 Value *Cmp = B.CreateICmpEQ(Guard, LI2);
Cong Houe93b8e12015-12-22 18:56:14 +0000460 auto SuccessProb =
461 BranchProbabilityInfo::getBranchProbStackProtector(true);
462 auto FailureProb =
463 BranchProbabilityInfo::getBranchProbStackProtector(false);
Akira Hatanakab9991a22014-12-01 04:27:03 +0000464 MDNode *Weights = MDBuilder(F->getContext())
Cong Houe93b8e12015-12-22 18:56:14 +0000465 .createBranchWeights(SuccessProb.getNumerator(),
466 FailureProb.getNumerator());
Akira Hatanakab9991a22014-12-01 04:27:03 +0000467 B.CreateCondBr(Cmp, NewBB, FailBB, Weights);
Bill Wendlinga0826e182008-11-06 23:55:49 +0000468 }
Bill Wendling05d84172008-11-04 02:10:20 +0000469 }
Bill Wendling782e8342008-11-05 00:00:21 +0000470
Saleem Abdulrasool90c224a2014-12-21 21:52:38 +0000471 // Return if we didn't modify any basic blocks. i.e., there are no return
Bill Wendlinga0826e182008-11-06 23:55:49 +0000472 // statements in the function.
Rafael Espindola84921b92015-10-24 23:11:13 +0000473 return HasPrologue;
Bill Wendling05d84172008-11-04 02:10:20 +0000474}
475
476/// CreateFailBB - Create a basic block to jump to when the stack protector
477/// check fails.
Bill Wendling782e8342008-11-05 00:00:21 +0000478BasicBlock *StackProtector::CreateFailBB() {
Rafael Espindolaaad6c242013-06-07 16:35:57 +0000479 LLVMContext &Context = F->getContext();
480 BasicBlock *FailBB = BasicBlock::Create(Context, "CallStackCheckFailBlk", F);
Benjamin Kramerd93817f2013-09-09 17:38:01 +0000481 IRBuilder<> B(FailBB);
Yunzhong Gaob3869552016-06-30 18:49:04 +0000482 B.SetCurrentDebugLocation(DebugLoc::get(0, 0, F->getSubprogram()));
Simon Pilgrim2bfd9122014-11-29 19:18:21 +0000483 if (Trip.isOSOpenBSD()) {
Saleem Abdulrasool90c224a2014-12-21 21:52:38 +0000484 Constant *StackChkFail =
485 M->getOrInsertFunction("__stack_smash_handler",
486 Type::getVoidTy(Context),
487 Type::getInt8PtrTy(Context), nullptr);
Rafael Espindolaaad6c242013-06-07 16:35:57 +0000488
Benjamin Kramerd93817f2013-09-09 17:38:01 +0000489 B.CreateCall(StackChkFail, B.CreateGlobalStringPtr(F->getName(), "SSH"));
Rafael Espindolaaad6c242013-06-07 16:35:57 +0000490 } else {
Saleem Abdulrasool90c224a2014-12-21 21:52:38 +0000491 Constant *StackChkFail =
492 M->getOrInsertFunction("__stack_chk_fail", Type::getVoidTy(Context),
493 nullptr);
David Blaikieff6409d2015-05-18 22:13:54 +0000494 B.CreateCall(StackChkFail, {});
Rafael Espindolaaad6c242013-06-07 16:35:57 +0000495 }
Benjamin Kramerd93817f2013-09-09 17:38:01 +0000496 B.CreateUnreachable();
Bill Wendling782e8342008-11-05 00:00:21 +0000497 return FailBB;
Bill Wendling05d84172008-11-04 02:10:20 +0000498}
Tim Shen00127562016-04-08 21:26:31 +0000499
500bool StackProtector::shouldEmitSDCheck(const BasicBlock &BB) const {
501 return HasPrologue && !HasIRCheck && dyn_cast<ReturnInst>(BB.getTerminator());
502}