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