blob: ae3d49c5e23ac0f82a0fecec69229cf73c3657ce [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"
Adam Nemet0965da22017-10-09 23:19:02 +000021#include "llvm/Analysis/OptimizationRemarkEmitter.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000022#include "llvm/CodeGen/Passes.h"
Eugene Zelenko6ac7a342017-06-07 23:53:32 +000023#include "llvm/CodeGen/StackProtector.h"
Matthias Braune89461a2017-06-05 22:59:21 +000024#include "llvm/CodeGen/TargetPassConfig.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#include "llvm/IR/Attributes.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000026#include "llvm/IR/BasicBlock.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/Constants.h"
28#include "llvm/IR/DataLayout.h"
Yunzhong Gaob3869552016-06-30 18:49:04 +000029#include "llvm/IR/DebugInfo.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000030#include "llvm/IR/DebugLoc.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000031#include "llvm/IR/DerivedTypes.h"
Eugene Zelenko6ac7a342017-06-07 23:53:32 +000032#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000033#include "llvm/IR/Function.h"
Benjamin Kramerd93817f2013-09-09 17:38:01 +000034#include "llvm/IR/IRBuilder.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000035#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000036#include "llvm/IR/Instructions.h"
37#include "llvm/IR/Intrinsics.h"
Akira Hatanakab9991a22014-12-01 04:27:03 +000038#include "llvm/IR/MDBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000039#include "llvm/IR/Module.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000040#include "llvm/IR/Type.h"
41#include "llvm/IR/User.h"
42#include "llvm/Pass.h"
43#include "llvm/Support/Casting.h"
Bill Wendling05d84172008-11-04 02:10:20 +000044#include "llvm/Support/CommandLine.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000045#include "llvm/Target/TargetLowering.h"
46#include "llvm/Target/TargetMachine.h"
47#include "llvm/Target/TargetOptions.h"
Eric Christopherd9134482014-08-04 21:25:23 +000048#include "llvm/Target/TargetSubtargetInfo.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000049#include <utility>
50
Bill Wendling05d84172008-11-04 02:10:20 +000051using namespace llvm;
52
Chandler Carruth1b9dde02014-04-22 02:02:50 +000053#define DEBUG_TYPE "stack-protector"
54
Bill Wendling7c8f96a2013-01-23 06:43:53 +000055STATISTIC(NumFunProtected, "Number of functions protected");
56STATISTIC(NumAddrTaken, "Number of local variables that have their address"
57 " taken.");
58
Josh Magee7245f1d2013-10-30 02:25:14 +000059static cl::opt<bool> EnableSelectionDAGSP("enable-selectiondag-sp",
60 cl::init(true), cl::Hidden);
Michael Gottesman5e570682013-08-20 08:36:53 +000061
Bill Wendling05d84172008-11-04 02:10:20 +000062char StackProtector::ID = 0;
Eugene Zelenko6ac7a342017-06-07 23:53:32 +000063
Matthias Braun1527baa2017-05-25 21:26:32 +000064INITIALIZE_PASS_BEGIN(StackProtector, DEBUG_TYPE,
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +000065 "Insert stack protectors", false, true)
66INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
Matthias Braun1527baa2017-05-25 21:26:32 +000067INITIALIZE_PASS_END(StackProtector, DEBUG_TYPE,
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +000068 "Insert stack protectors", false, true)
Bill Wendling05d84172008-11-04 02:10:20 +000069
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +000070FunctionPass *llvm::createStackProtectorPass() { return new StackProtector(); }
Bill Wendling05d84172008-11-04 02:10:20 +000071
Josh Magee7245f1d2013-10-30 02:25:14 +000072StackProtector::SSPLayoutKind
73StackProtector::getSSPLayout(const AllocaInst *AI) const {
Josh Magee3f1c0e32013-10-29 21:16:16 +000074 return AI ? Layout.lookup(AI) : SSPLK_None;
75}
76
Hal Finkela69e5b82014-01-20 19:49:14 +000077void StackProtector::adjustForColoring(const AllocaInst *From,
78 const AllocaInst *To) {
79 // When coloring replaces one alloca with another, transfer the SSPLayoutKind
80 // tag from the remapped to the target alloca. The remapped alloca should
81 // have a size smaller than or equal to the replacement alloca.
82 SSPLayoutMap::iterator I = Layout.find(From);
83 if (I != Layout.end()) {
84 SSPLayoutKind Kind = I->second;
85 Layout.erase(I);
86
87 // Transfer the tag, but make sure that SSPLK_AddrOf does not overwrite
88 // SSPLK_SmallArray or SSPLK_LargeArray, and make sure that
89 // SSPLK_SmallArray does not overwrite SSPLK_LargeArray.
90 I = Layout.find(To);
91 if (I == Layout.end())
92 Layout.insert(std::make_pair(To, Kind));
93 else if (I->second != SSPLK_LargeArray && Kind != SSPLK_AddrOf)
94 I->second = Kind;
95 }
96}
97
Matthias Braune89461a2017-06-05 22:59:21 +000098void StackProtector::getAnalysisUsage(AnalysisUsage &AU) const {
99 AU.addRequired<TargetPassConfig>();
100 AU.addPreserved<DominatorTreeWrapperPass>();
101}
102
Bill Wendling05d84172008-11-04 02:10:20 +0000103bool StackProtector::runOnFunction(Function &Fn) {
104 F = &Fn;
105 M = F->getParent();
Chandler Carruth73523022014-01-13 13:07:17 +0000106 DominatorTreeWrapperPass *DTWP =
107 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
Craig Topperc0196b12014-04-14 00:51:57 +0000108 DT = DTWP ? &DTWP->getDomTree() : nullptr;
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000109 TM = &getAnalysis<TargetPassConfig>().getTM<TargetMachine>();
110 Trip = TM->getTargetTriple();
Eric Christopher33726202015-01-27 08:48:42 +0000111 TLI = TM->getSubtargetImpl(Fn)->getTargetLowering();
Tim Shen00127562016-04-08 21:26:31 +0000112 HasPrologue = false;
113 HasIRCheck = false;
Bill Wendling05d84172008-11-04 02:10:20 +0000114
Duncan P. N. Exon Smith70eb9c52015-02-14 01:44:41 +0000115 Attribute Attr = Fn.getFnAttribute("stack-protector-buffer-size");
Renato Goline195f9c2014-01-21 10:24:35 +0000116 if (Attr.isStringAttribute() &&
117 Attr.getValueAsString().getAsInteger(10, SSPBufferSize))
Etienne Bergeron22bfa832016-06-07 20:15:35 +0000118 return false; // Invalid integer string
Bill Wendlingc02a0aa2013-07-22 20:15:21 +0000119
Josh Mageeadfde5f2014-04-17 19:08:36 +0000120 if (!RequiresStackProtector())
121 return false;
122
Etienne Bergeron22bfa832016-06-07 20:15:35 +0000123 // TODO(etienneb): Functions with funclets are not correctly supported now.
124 // Do nothing if this is funclet-based personality.
125 if (Fn.hasPersonalityFn()) {
126 EHPersonality Personality = classifyEHPersonality(Fn.getPersonalityFn());
127 if (isFuncletEHPersonality(Personality))
128 return false;
129 }
130
Bill Wendling7c8f96a2013-01-23 06:43:53 +0000131 ++NumFunProtected;
Bill Wendling782e8342008-11-05 00:00:21 +0000132 return InsertStackProtectors();
Bill Wendling05d84172008-11-04 02:10:20 +0000133}
134
Josh Magee3f1c0e32013-10-29 21:16:16 +0000135/// \param [out] IsLarge is set to true if a protectable array is found and
136/// it is "large" ( >= ssp-buffer-size). In the case of a structure with
137/// multiple arrays, this gets set if any of them is large.
138bool StackProtector::ContainsProtectableArray(Type *Ty, bool &IsLarge,
Josh Magee7245f1d2013-10-30 02:25:14 +0000139 bool Strong,
140 bool InStruct) const {
141 if (!Ty)
142 return false;
Bill Wendlingbfb9b752012-08-17 20:59:56 +0000143 if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
144 if (!AT->getElementType()->isIntegerTy(8)) {
Bill Wendlingbfb9b752012-08-17 20:59:56 +0000145 // If we're on a non-Darwin platform or we're inside of a structure, don't
146 // add stack protectors unless the array is a character array.
Josh Magee3f1c0e32013-10-29 21:16:16 +0000147 // However, in strong mode any array, regardless of type and size,
148 // triggers a protector.
149 if (!Strong && (InStruct || !Trip.isOSDarwin()))
150 return false;
Bill Wendlingbfb9b752012-08-17 20:59:56 +0000151 }
152
153 // If an array has more than SSPBufferSize bytes of allocated space, then we
154 // emit stack protectors.
Mehdi Aminied6edbf2015-07-07 23:38:49 +0000155 if (SSPBufferSize <= M->getDataLayout().getTypeAllocSize(AT)) {
Josh Magee3f1c0e32013-10-29 21:16:16 +0000156 IsLarge = true;
157 return true;
Josh Magee7245f1d2013-10-30 02:25:14 +0000158 }
Josh Magee3f1c0e32013-10-29 21:16:16 +0000159
160 if (Strong)
161 // Require a protector for all arrays in strong mode
Bill Wendlingbfb9b752012-08-17 20:59:56 +0000162 return true;
163 }
164
165 const StructType *ST = dyn_cast<StructType>(Ty);
Josh Magee7245f1d2013-10-30 02:25:14 +0000166 if (!ST)
167 return false;
Bill Wendlingbfb9b752012-08-17 20:59:56 +0000168
Josh Magee3f1c0e32013-10-29 21:16:16 +0000169 bool NeedsProtector = false;
Bill Wendlingbfb9b752012-08-17 20:59:56 +0000170 for (StructType::element_iterator I = ST->element_begin(),
Josh Magee7245f1d2013-10-30 02:25:14 +0000171 E = ST->element_end();
172 I != E; ++I)
Josh Magee3f1c0e32013-10-29 21:16:16 +0000173 if (ContainsProtectableArray(*I, IsLarge, Strong, true)) {
174 // If the element is a protectable array and is large (>= SSPBufferSize)
175 // then we are done. If the protectable array is not large, then
176 // keep looking in case a subsequent element is a large array.
177 if (IsLarge)
178 return true;
179 NeedsProtector = true;
180 }
Bill Wendlingbfb9b752012-08-17 20:59:56 +0000181
Josh Magee3f1c0e32013-10-29 21:16:16 +0000182 return NeedsProtector;
Bill Wendlingbfb9b752012-08-17 20:59:56 +0000183}
184
Bill Wendling7c8f96a2013-01-23 06:43:53 +0000185bool StackProtector::HasAddressTaken(const Instruction *AI) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000186 for (const User *U : AI->users()) {
Bill Wendling7c8f96a2013-01-23 06:43:53 +0000187 if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
188 if (AI == SI->getValueOperand())
189 return true;
190 } else if (const PtrToIntInst *SI = dyn_cast<PtrToIntInst>(U)) {
191 if (AI == SI->getOperand(0))
192 return true;
193 } else if (isa<CallInst>(U)) {
194 return true;
195 } else if (isa<InvokeInst>(U)) {
196 return true;
197 } else if (const SelectInst *SI = dyn_cast<SelectInst>(U)) {
198 if (HasAddressTaken(SI))
199 return true;
200 } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
201 // Keep track of what PHI nodes we have already visited to ensure
202 // they are only visited once.
David Blaikie70573dc2014-11-19 07:49:26 +0000203 if (VisitedPHIs.insert(PN).second)
Bill Wendling7c8f96a2013-01-23 06:43:53 +0000204 if (HasAddressTaken(PN))
205 return true;
206 } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
207 if (HasAddressTaken(GEP))
208 return true;
209 } else if (const BitCastInst *BI = dyn_cast<BitCastInst>(U)) {
210 if (HasAddressTaken(BI))
211 return true;
212 }
213 }
214 return false;
215}
216
217/// \brief Check whether or not this function needs a stack protector based
218/// upon the stack protector level.
219///
220/// We use two heuristics: a standard (ssp) and strong (sspstrong).
221/// The standard heuristic which will add a guard variable to functions that
222/// call alloca with a either a variable size or a size >= SSPBufferSize,
223/// functions with character buffers larger than SSPBufferSize, and functions
224/// with aggregates containing character buffers larger than SSPBufferSize. The
225/// strong heuristic will add a guard variables to functions that call alloca
226/// regardless of size, functions with any buffer regardless of type and size,
227/// functions with aggregates that contain any buffer regardless of type and
228/// size, and functions that contain stack-based variables that have had their
229/// address taken.
230bool StackProtector::RequiresStackProtector() {
231 bool Strong = false;
Josh Magee3f1c0e32013-10-29 21:16:16 +0000232 bool NeedsProtector = false;
Tim Shen00127562016-04-08 21:26:31 +0000233 for (const BasicBlock &BB : *F)
234 for (const Instruction &I : BB)
235 if (const CallInst *CI = dyn_cast<CallInst>(&I))
236 if (CI->getCalledFunction() ==
237 Intrinsic::getDeclaration(F->getParent(),
238 Intrinsic::stackprotector))
239 HasPrologue = true;
240
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +0000241 if (F->hasFnAttribute(Attribute::SafeStack))
242 return false;
243
David Bozier51599682017-02-28 16:02:37 +0000244 // We are constructing the OptimizationRemarkEmitter on the fly rather than
245 // using the analysis pass to avoid building DominatorTree and LoopInfo which
246 // are not available this late in the IR pipeline.
247 OptimizationRemarkEmitter ORE(F);
David Bozier51599682017-02-28 16:02:37 +0000248
Duncan P. N. Exon Smith70eb9c52015-02-14 01:44:41 +0000249 if (F->hasFnAttribute(Attribute::StackProtectReq)) {
Vivek Pandya95906582017-10-11 17:12:59 +0000250 ORE.emit([&]() {
251 return OptimizationRemark(DEBUG_TYPE, "StackProtectorRequested", F)
Adam Nemet5361b822017-03-09 06:10:27 +0000252 << "Stack protection applied to function "
253 << ore::NV("Function", F)
Vivek Pandya95906582017-10-11 17:12:59 +0000254 << " due to a function attribute or command-line switch";
255 });
Josh Magee3f1c0e32013-10-29 21:16:16 +0000256 NeedsProtector = true;
257 Strong = true; // Use the same heuristic as strong to determine SSPLayout
Duncan P. N. Exon Smith70eb9c52015-02-14 01:44:41 +0000258 } else if (F->hasFnAttribute(Attribute::StackProtectStrong))
Bill Wendling7c8f96a2013-01-23 06:43:53 +0000259 Strong = true;
Tim Shen00127562016-04-08 21:26:31 +0000260 else if (HasPrologue)
261 NeedsProtector = true;
Duncan P. N. Exon Smith70eb9c52015-02-14 01:44:41 +0000262 else if (!F->hasFnAttribute(Attribute::StackProtect))
Bill Wendlingeeb04152008-11-18 05:32:11 +0000263 return false;
264
Saleem Abdulrasool57b5fe52014-12-20 21:37:51 +0000265 for (const BasicBlock &BB : *F) {
266 for (const Instruction &I : BB) {
267 if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
Bill Wendling7c8f96a2013-01-23 06:43:53 +0000268 if (AI->isArrayAllocation()) {
Vivek Pandya95906582017-10-11 17:12:59 +0000269 auto RemarkBuilder = [&]() {
270 return OptimizationRemark(DEBUG_TYPE, "StackProtectorAllocaOrArray",
271 &I)
272 << "Stack protection applied to function "
273 << ore::NV("Function", F)
274 << " due to a call to alloca or use of a variable length "
275 "array";
276 };
Saleem Abdulrasool57b5fe52014-12-20 21:37:51 +0000277 if (const auto *CI = dyn_cast<ConstantInt>(AI->getArraySize())) {
Josh Magee3f1c0e32013-10-29 21:16:16 +0000278 if (CI->getLimitedValue(SSPBufferSize) >= SSPBufferSize) {
Bill Wendling7c8f96a2013-01-23 06:43:53 +0000279 // A call to alloca with size >= SSPBufferSize requires
280 // stack protectors.
Josh Magee3f1c0e32013-10-29 21:16:16 +0000281 Layout.insert(std::make_pair(AI, SSPLK_LargeArray));
Vivek Pandya95906582017-10-11 17:12:59 +0000282 ORE.emit(RemarkBuilder);
Josh Magee3f1c0e32013-10-29 21:16:16 +0000283 NeedsProtector = true;
284 } else if (Strong) {
285 // Require protectors for all alloca calls in strong mode.
286 Layout.insert(std::make_pair(AI, SSPLK_SmallArray));
Vivek Pandya95906582017-10-11 17:12:59 +0000287 ORE.emit(RemarkBuilder);
Josh Magee3f1c0e32013-10-29 21:16:16 +0000288 NeedsProtector = true;
289 }
Bill Wendlingc02a0aa2013-07-22 20:15:21 +0000290 } else {
291 // A call to alloca with a variable size requires protectors.
Josh Magee3f1c0e32013-10-29 21:16:16 +0000292 Layout.insert(std::make_pair(AI, SSPLK_LargeArray));
Vivek Pandya95906582017-10-11 17:12:59 +0000293 ORE.emit(RemarkBuilder);
Josh Magee3f1c0e32013-10-29 21:16:16 +0000294 NeedsProtector = true;
Bill Wendlingc02a0aa2013-07-22 20:15:21 +0000295 }
Josh Magee3f1c0e32013-10-29 21:16:16 +0000296 continue;
Bill Wendling7c8f96a2013-01-23 06:43:53 +0000297 }
298
Josh Magee3f1c0e32013-10-29 21:16:16 +0000299 bool IsLarge = false;
300 if (ContainsProtectableArray(AI->getAllocatedType(), IsLarge, Strong)) {
301 Layout.insert(std::make_pair(AI, IsLarge ? SSPLK_LargeArray
302 : SSPLK_SmallArray));
Vivek Pandya95906582017-10-11 17:12:59 +0000303 ORE.emit([&]() {
304 return OptimizationRemark(DEBUG_TYPE, "StackProtectorBuffer", &I)
Adam Nemet5361b822017-03-09 06:10:27 +0000305 << "Stack protection applied to function "
306 << ore::NV("Function", F)
307 << " due to a stack allocated buffer or struct containing a "
Vivek Pandya95906582017-10-11 17:12:59 +0000308 "buffer";
309 });
Josh Magee3f1c0e32013-10-29 21:16:16 +0000310 NeedsProtector = true;
311 continue;
312 }
Bill Wendlingeeb04152008-11-18 05:32:11 +0000313
Bill Wendling7c8f96a2013-01-23 06:43:53 +0000314 if (Strong && HasAddressTaken(AI)) {
Michael Gottesman62c5d712013-08-20 08:46:16 +0000315 ++NumAddrTaken;
Josh Magee3f1c0e32013-10-29 21:16:16 +0000316 Layout.insert(std::make_pair(AI, SSPLK_AddrOf));
Vivek Pandya95906582017-10-11 17:12:59 +0000317 ORE.emit([&]() {
318 return OptimizationRemark(DEBUG_TYPE, "StackProtectorAddressTaken",
319 &I)
320 << "Stack protection applied to function "
321 << ore::NV("Function", F)
322 << " due to the address of a local variable being taken";
323 });
Josh Magee3f1c0e32013-10-29 21:16:16 +0000324 NeedsProtector = true;
Bill Wendling7c8f96a2013-01-23 06:43:53 +0000325 }
Bill Wendlingeeb04152008-11-18 05:32:11 +0000326 }
Bill Wendling7c8f96a2013-01-23 06:43:53 +0000327 }
Bill Wendlingeeb04152008-11-18 05:32:11 +0000328 }
329
Josh Magee3f1c0e32013-10-29 21:16:16 +0000330 return NeedsProtector;
Bill Wendlingeeb04152008-11-18 05:32:11 +0000331}
332
Tim Shene885d5e2016-04-19 19:40:37 +0000333/// Create a stack guard loading and populate whether SelectionDAG SSP is
334/// supported.
335static Value *getStackGuard(const TargetLoweringBase *TLI, Module *M,
336 IRBuilder<> &B,
337 bool *SupportsSelectionDAGSP = nullptr) {
338 if (Value *Guard = TLI->getIRStackGuard(B))
339 return B.CreateLoad(Guard, true, "StackGuard");
340
341 // Use SelectionDAG SSP handling, since there isn't an IR guard.
342 //
343 // This is more or less weird, since we optionally output whether we
344 // should perform a SelectionDAG SP here. The reason is that it's strictly
345 // defined as !TLI->getIRStackGuard(B), where getIRStackGuard is also
346 // mutating. There is no way to get this bit without mutating the IR, so
347 // getting this bit has to happen in this right time.
348 //
349 // We could have define a new function TLI::supportsSelectionDAGSP(), but that
350 // will put more burden on the backends' overriding work, especially when it
351 // actually conveys the same information getIRStackGuard() already gives.
352 if (SupportsSelectionDAGSP)
353 *SupportsSelectionDAGSP = true;
354 TLI->insertSSPDeclarations(*M);
355 return B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackguard));
356}
357
358/// Insert code into the entry block that stores the stack guard
Michael Gottesmana6188f92013-07-22 20:44:11 +0000359/// variable onto the stack:
360///
361/// entry:
362/// StackGuardSlot = alloca i8*
Tim Shene885d5e2016-04-19 19:40:37 +0000363/// StackGuard = <stack guard>
364/// call void @llvm.stackprotector(StackGuard, StackGuardSlot)
Michael Gottesmana6188f92013-07-22 20:44:11 +0000365///
Michael Gottesman5e570682013-08-20 08:36:53 +0000366/// Returns true if the platform/triple supports the stackprotectorcreate pseudo
367/// node.
368static bool CreatePrologue(Function *F, Module *M, ReturnInst *RI,
Tim Shene885d5e2016-04-19 19:40:37 +0000369 const TargetLoweringBase *TLI, AllocaInst *&AI) {
Michael Gottesman5e570682013-08-20 08:36:53 +0000370 bool SupportsSelectionDAGSP = false;
Evgeniy Stepanovdde29e22016-04-05 22:41:50 +0000371 IRBuilder<> B(&F->getEntryBlock().front());
Tim Shen00127562016-04-08 21:26:31 +0000372 PointerType *PtrTy = Type::getInt8PtrTy(RI->getContext());
Craig Topperc0196b12014-04-14 00:51:57 +0000373 AI = B.CreateAlloca(PtrTy, nullptr, "StackGuardSlot");
Tim Shene885d5e2016-04-19 19:40:37 +0000374
Etienne Bergeron22bfa832016-06-07 20:15:35 +0000375 Value *GuardSlot = getStackGuard(TLI, M, B, &SupportsSelectionDAGSP);
David Blaikieff6409d2015-05-18 22:13:54 +0000376 B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackprotector),
Etienne Bergeron22bfa832016-06-07 20:15:35 +0000377 {GuardSlot, AI});
Michael Gottesman5e570682013-08-20 08:36:53 +0000378 return SupportsSelectionDAGSP;
Michael Gottesmana6188f92013-07-22 20:44:11 +0000379}
380
Bill Wendling782e8342008-11-05 00:00:21 +0000381/// InsertStackProtectors - Insert code into the prologue and epilogue of the
382/// function.
383///
384/// - The prologue code loads and stores the stack guard onto the stack.
385/// - The epilogue checks the value stored in the prologue against the original
386/// value. It calls __stack_chk_fail if they differ.
387bool StackProtector::InsertStackProtectors() {
Michael Gottesman76c44be2013-08-20 08:56:26 +0000388 bool SupportsSelectionDAGSP =
Josh Magee7245f1d2013-10-30 02:25:14 +0000389 EnableSelectionDAGSP && !TM->Options.EnableFastISel;
Craig Topperc0196b12014-04-14 00:51:57 +0000390 AllocaInst *AI = nullptr; // Place on stack that stores the stack guard.
Bill Wendlingeb4268d2008-11-07 01:23:58 +0000391
Josh Magee7245f1d2013-10-30 02:25:14 +0000392 for (Function::iterator I = F->begin(), E = F->end(); I != E;) {
Duncan P. N. Exon Smithf1ff53e2015-10-09 22:56:24 +0000393 BasicBlock *BB = &*I++;
Bill Wendlingeeb04152008-11-18 05:32:11 +0000394 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
Michael Gottesmandc985ef2013-08-20 08:56:28 +0000395 if (!RI)
396 continue;
Bill Wendlingeb4268d2008-11-07 01:23:58 +0000397
Etienne Bergeron22bfa832016-06-07 20:15:35 +0000398 // Generate prologue instrumentation if not already generated.
Michael Gottesman8afcf3a2013-08-09 21:26:18 +0000399 if (!HasPrologue) {
400 HasPrologue = true;
Tim Shene885d5e2016-04-19 19:40:37 +0000401 SupportsSelectionDAGSP &= CreatePrologue(F, M, RI, TLI, AI);
Michael Gottesman62c5d712013-08-20 08:46:16 +0000402 }
Michael Gottesman5e570682013-08-20 08:36:53 +0000403
Etienne Bergeron22bfa832016-06-07 20:15:35 +0000404 // SelectionDAG based code generation. Nothing else needs to be done here.
405 // The epilogue instrumentation is postponed to SelectionDAG.
406 if (SupportsSelectionDAGSP)
407 break;
408
409 // Set HasIRCheck to true, so that SelectionDAG will not generate its own
410 // version. SelectionDAG called 'shouldEmitSDCheck' to check whether
411 // instrumentation has already been generated.
412 HasIRCheck = true;
413
414 // Generate epilogue instrumentation. The epilogue intrumentation can be
415 // function-based or inlined depending on which mechanism the target is
416 // providing.
417 if (Value* GuardCheck = TLI->getSSPStackGuardCheck(*M)) {
418 // Generate the function-based epilogue instrumentation.
419 // The target provides a guard check function, generate a call to it.
420 IRBuilder<> B(RI);
421 LoadInst *Guard = B.CreateLoad(AI, true, "Guard");
422 CallInst *Call = B.CreateCall(GuardCheck, {Guard});
423 llvm::Function *Function = cast<llvm::Function>(GuardCheck);
424 Call->setAttributes(Function->getAttributes());
425 Call->setCallingConv(Function->getCallingConv());
426 } else {
427 // Generate the epilogue with inline instrumentation.
Michael Gottesman56e246b2013-08-20 08:46:13 +0000428 // If we do not support SelectionDAG based tail calls, generate IR level
429 // tail calls.
430 //
Michael Gottesman5e570682013-08-20 08:36:53 +0000431 // For each block with a return instruction, convert this:
432 //
433 // return:
434 // ...
435 // ret ...
436 //
437 // into this:
438 //
439 // return:
440 // ...
Tim Shene885d5e2016-04-19 19:40:37 +0000441 // %1 = <stack guard>
Michael Gottesman5e570682013-08-20 08:36:53 +0000442 // %2 = load StackGuardSlot
443 // %3 = cmp i1 %1, %2
444 // br i1 %3, label %SP_return, label %CallStackCheckFailBlk
445 //
446 // SP_return:
447 // ret ...
448 //
449 // CallStackCheckFailBlk:
450 // call void @__stack_chk_fail()
451 // unreachable
452
453 // Create the FailBB. We duplicate the BB every time since the MI tail
454 // merge pass will merge together all of the various BB into one including
Michael Gottesman62c5d712013-08-20 08:46:16 +0000455 // fail BB generated by the stack protector pseudo instruction.
Michael Gottesman5e570682013-08-20 08:36:53 +0000456 BasicBlock *FailBB = CreateFailBB();
Michael Gottesman62c5d712013-08-20 08:46:16 +0000457
Michael Gottesman5e570682013-08-20 08:36:53 +0000458 // Split the basic block before the return instruction.
Duncan P. N. Exon Smithf1ff53e2015-10-09 22:56:24 +0000459 BasicBlock *NewBB = BB->splitBasicBlock(RI->getIterator(), "SP_return");
Michael Gottesman62c5d712013-08-20 08:46:16 +0000460
Michael Gottesman5e570682013-08-20 08:36:53 +0000461 // Update the dominator tree if we need to.
462 if (DT && DT->isReachableFromEntry(BB)) {
463 DT->addNewBlock(NewBB, BB);
464 DT->addNewBlock(FailBB, BB);
465 }
Michael Gottesman62c5d712013-08-20 08:46:16 +0000466
Michael Gottesman5e570682013-08-20 08:36:53 +0000467 // Remove default branch instruction to the new BB.
468 BB->getTerminator()->eraseFromParent();
Michael Gottesman62c5d712013-08-20 08:46:16 +0000469
Michael Gottesman5e570682013-08-20 08:36:53 +0000470 // Move the newly created basic block to the point right after the old
471 // basic block so that it's in the "fall through" position.
472 NewBB->moveAfter(BB);
Michael Gottesman62c5d712013-08-20 08:46:16 +0000473
Michael Gottesman5e570682013-08-20 08:36:53 +0000474 // Generate the stack protector instructions in the old basic block.
Benjamin Kramerd93817f2013-09-09 17:38:01 +0000475 IRBuilder<> B(BB);
Tim Shene885d5e2016-04-19 19:40:37 +0000476 Value *Guard = getStackGuard(TLI, M, B);
477 LoadInst *LI2 = B.CreateLoad(AI, true);
478 Value *Cmp = B.CreateICmpEQ(Guard, LI2);
Cong Houe93b8e12015-12-22 18:56:14 +0000479 auto SuccessProb =
480 BranchProbabilityInfo::getBranchProbStackProtector(true);
481 auto FailureProb =
482 BranchProbabilityInfo::getBranchProbStackProtector(false);
Akira Hatanakab9991a22014-12-01 04:27:03 +0000483 MDNode *Weights = MDBuilder(F->getContext())
Cong Houe93b8e12015-12-22 18:56:14 +0000484 .createBranchWeights(SuccessProb.getNumerator(),
485 FailureProb.getNumerator());
Akira Hatanakab9991a22014-12-01 04:27:03 +0000486 B.CreateCondBr(Cmp, NewBB, FailBB, Weights);
Bill Wendlinga0826e182008-11-06 23:55:49 +0000487 }
Bill Wendling05d84172008-11-04 02:10:20 +0000488 }
Bill Wendling782e8342008-11-05 00:00:21 +0000489
Saleem Abdulrasool90c224a2014-12-21 21:52:38 +0000490 // Return if we didn't modify any basic blocks. i.e., there are no return
Bill Wendlinga0826e182008-11-06 23:55:49 +0000491 // statements in the function.
Rafael Espindola84921b92015-10-24 23:11:13 +0000492 return HasPrologue;
Bill Wendling05d84172008-11-04 02:10:20 +0000493}
494
495/// CreateFailBB - Create a basic block to jump to when the stack protector
496/// check fails.
Bill Wendling782e8342008-11-05 00:00:21 +0000497BasicBlock *StackProtector::CreateFailBB() {
Rafael Espindolaaad6c242013-06-07 16:35:57 +0000498 LLVMContext &Context = F->getContext();
499 BasicBlock *FailBB = BasicBlock::Create(Context, "CallStackCheckFailBlk", F);
Benjamin Kramerd93817f2013-09-09 17:38:01 +0000500 IRBuilder<> B(FailBB);
Yunzhong Gaob3869552016-06-30 18:49:04 +0000501 B.SetCurrentDebugLocation(DebugLoc::get(0, 0, F->getSubprogram()));
Simon Pilgrim2bfd9122014-11-29 19:18:21 +0000502 if (Trip.isOSOpenBSD()) {
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000503 Constant *StackChkFail =
504 M->getOrInsertFunction("__stack_smash_handler",
505 Type::getVoidTy(Context),
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000506 Type::getInt8PtrTy(Context));
Rafael Espindolaaad6c242013-06-07 16:35:57 +0000507
Benjamin Kramerd93817f2013-09-09 17:38:01 +0000508 B.CreateCall(StackChkFail, B.CreateGlobalStringPtr(F->getName(), "SSH"));
Rafael Espindolaaad6c242013-06-07 16:35:57 +0000509 } else {
Saleem Abdulrasool90c224a2014-12-21 21:52:38 +0000510 Constant *StackChkFail =
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000511 M->getOrInsertFunction("__stack_chk_fail", Type::getVoidTy(Context));
512
David Blaikieff6409d2015-05-18 22:13:54 +0000513 B.CreateCall(StackChkFail, {});
Rafael Espindolaaad6c242013-06-07 16:35:57 +0000514 }
Benjamin Kramerd93817f2013-09-09 17:38:01 +0000515 B.CreateUnreachable();
Bill Wendling782e8342008-11-05 00:00:21 +0000516 return FailBB;
Bill Wendling05d84172008-11-04 02:10:20 +0000517}
Tim Shen00127562016-04-08 21:26:31 +0000518
519bool StackProtector::shouldEmitSDCheck(const BasicBlock &BB) const {
520 return HasPrologue && !HasIRCheck && dyn_cast<ReturnInst>(BB.getTerminator());
521}