StackProtector.cpp revision d4f478899e6229648f94c4aa70256986cdc6ee18
15267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)//===-- StackProtector.cpp - Stack Protector Insertion --------------------===//
25267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)//
35267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)//                     The LLVM Compiler Infrastructure
45267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)//
55267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)// This file is distributed under the University of Illinois Open Source
65267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)// License. See LICENSE.TXT for details.
75267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)//
85267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)//===----------------------------------------------------------------------===//
95267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)//
105267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)// This pass inserts stack protectors into functions which need them. A variable
115267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)// with a random value in it is stored onto the stack before the local variables
125267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)// are allocated. Upon exiting the block, the stored value is checked. If it's
135267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)// changed, then there was some sort of violation and the program aborts.
145267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)//
155267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)//===----------------------------------------------------------------------===//
165267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)
175267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)#define DEBUG_TYPE "stack-protector"
185267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)#include "llvm/CodeGen/Analysis.h"
195267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)#include "llvm/CodeGen/Passes.h"
205267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)#include "llvm/ADT/SmallPtrSet.h"
215267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)#include "llvm/ADT/Statistic.h"
225267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)#include "llvm/ADT/Triple.h"
235267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)#include "llvm/Analysis/Dominators.h"
245267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)#include "llvm/Analysis/ValueTracking.h"
255267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)#include "llvm/IR/Attributes.h"
265267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)#include "llvm/IR/Constants.h"
275267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)#include "llvm/IR/DataLayout.h"
285267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)#include "llvm/IR/DerivedTypes.h"
295267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)#include "llvm/IR/Function.h"
305267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)#include "llvm/IR/GlobalValue.h"
315267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)#include "llvm/IR/GlobalVariable.h"
325d92fedcae5e801a8b224de090094f2d9df0b54aTorne (Richard Coles)#include "llvm/IR/Instructions.h"
335267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)#include "llvm/IR/IntrinsicInst.h"
3409380295ba73501a205346becac22c6978e4671dTorne (Richard Coles)#include "llvm/IR/Intrinsics.h"
355267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)#include "llvm/IR/Module.h"
36c1847b1379d12d0e05df27436bf19a9b1bf12deaTorne (Richard Coles)#include "llvm/Pass.h"
375267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)#include "llvm/Support/CommandLine.h"
38e69819bd8e388ea4ad1636a19aa6b2eed4952191Ben Murdoch#include "llvm/Target/TargetLowering.h"
395267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)#include <cstdlib>
405267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)using namespace llvm;
415267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)
425267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)STATISTIC(NumFunProtected, "Number of functions protected");
435267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)STATISTIC(NumAddrTaken, "Number of local variables that have their address"
445267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)                        " taken.");
455267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)
465267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)static cl::opt<bool>
475267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)EnableSelectionDAGSP("enable-selectiondag-sp", cl::init(true),
485267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)                     cl::Hidden);
495267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)
505267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)namespace {
515267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)  class StackProtector : public FunctionPass {
525267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)    const TargetMachine *TM;
535267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)
545267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)    /// TLI - Keep a pointer of a TargetLowering to consult for determining
555267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)    /// target type sizes.
565267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)    const TargetLoweringBase *TLI;
575267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)    const Triple Trip;
585267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)
595267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)    Function *F;
605267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)    Module *M;
615267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)
625267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)    DominatorTree *DT;
635267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)
645267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)    /// \brief The minimum size of buffers that will receive stack smashing
655267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)    /// protection when -fstack-protection is used.
665267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)    unsigned SSPBufferSize;
675267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)
685267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)    /// VisitedPHIs - The set of PHI nodes visited when determining
695267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)    /// if a variable's reference has been taken.  This set
705267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)    /// is maintained to ensure we don't visit the same PHI node multiple
715267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)    /// times.
725267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)    SmallPtrSet<const PHINode*, 16> VisitedPHIs;
735267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)
745267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)    /// InsertStackProtectors - Insert code into the prologue and epilogue of
755267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)    /// the function.
765267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)    ///
775267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)    ///  - The prologue code loads and stores the stack guard onto the stack.
785267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)    ///  - The epilogue checks the value stored in the prologue against the
795267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)    ///    original value. It calls __stack_chk_fail if they differ.
805267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)    bool InsertStackProtectors();
815267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)
825267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)    /// CreateFailBB - Create a basic block to jump to when the stack protector
835267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)    /// check fails.
845267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)    BasicBlock *CreateFailBB();
855267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)
865267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)    /// ContainsProtectableArray - Check whether the type either is an array or
875267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)    /// contains an array of sufficient size so that we need stack protectors
885267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)    /// for it.
895267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)    bool ContainsProtectableArray(Type *Ty, bool Strong = false,
905267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)                                  bool InStruct = false) const;
915267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)
925267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)    /// \brief Check whether a stack allocation has its address taken.
935267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)    bool HasAddressTaken(const Instruction *AI);
945267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)
955267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)    /// RequiresStackProtector - Check whether or not this function needs a
965267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)    /// stack protector based upon the stack protector level.
975267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)    bool RequiresStackProtector();
985267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)  public:
995267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)    static char ID;             // Pass identification, replacement for typeid.
1005267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)    StackProtector() : FunctionPass(ID), TM(0), TLI(0), SSPBufferSize(0) {
1015267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)      initializeStackProtectorPass(*PassRegistry::getPassRegistry());
1025267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)    }
1035267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)    StackProtector(const TargetMachine *TM)
1045267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)      : FunctionPass(ID), TM(TM), TLI(0), Trip(TM->getTargetTriple()),
1055267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)        SSPBufferSize(8) {
1065267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)      initializeStackProtectorPass(*PassRegistry::getPassRegistry());
1075267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)    }
1085267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)
1095267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1105267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)      AU.addPreserved<DominatorTree>();
1115267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)    }
1125267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)
1135267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)    virtual bool runOnFunction(Function &Fn);
1145267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)  };
1155267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)} // end anonymous namespace
1165267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)
1175267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)char StackProtector::ID = 0;
1185267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)INITIALIZE_PASS(StackProtector, "stack-protector",
1195267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)                "Insert stack protectors", false, false)
1205267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)
1215267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)FunctionPass *llvm::createStackProtectorPass(const TargetMachine *TM) {
1225267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)  return new StackProtector(TM);
123197021e6b966cfb06891637935ef33fff06433d1Ben Murdoch}
1245267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)
125197021e6b966cfb06891637935ef33fff06433d1Ben Murdochbool StackProtector::runOnFunction(Function &Fn) {
126197021e6b966cfb06891637935ef33fff06433d1Ben Murdoch  F = &Fn;
127197021e6b966cfb06891637935ef33fff06433d1Ben Murdoch  M = F->getParent();
128197021e6b966cfb06891637935ef33fff06433d1Ben Murdoch  DT = getAnalysisIfAvailable<DominatorTree>();
129197021e6b966cfb06891637935ef33fff06433d1Ben Murdoch  TLI = TM->getTargetLowering();
130197021e6b966cfb06891637935ef33fff06433d1Ben Murdoch
1317242dc3dbeb210b5e876a3c42d1ec1a667fc621aPrimiano Tucci  if (!RequiresStackProtector()) return false;
132197021e6b966cfb06891637935ef33fff06433d1Ben Murdoch
1337242dc3dbeb210b5e876a3c42d1ec1a667fc621aPrimiano Tucci  Attribute Attr =
134e69819bd8e388ea4ad1636a19aa6b2eed4952191Ben Murdoch    Fn.getAttributes().getAttribute(AttributeSet::FunctionIndex,
1355267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)                                    "stack-protector-buffer-size");
1365267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)  if (Attr.isStringAttribute())
1375267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)    SSPBufferSize = atoi(Attr.getValueAsString().data());
1385267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)
139197021e6b966cfb06891637935ef33fff06433d1Ben Murdoch  ++NumFunProtected;
140197021e6b966cfb06891637935ef33fff06433d1Ben Murdoch  return InsertStackProtectors();
141197021e6b966cfb06891637935ef33fff06433d1Ben Murdoch}
1427242dc3dbeb210b5e876a3c42d1ec1a667fc621aPrimiano Tucci
1435267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)/// ContainsProtectableArray - Check whether the type either is an array or
1445267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)/// contains a char array of sufficient size so that we need stack protectors
1455267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)/// for it.
1465267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)bool StackProtector::ContainsProtectableArray(Type *Ty, bool Strong,
1475267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)                                              bool InStruct) const {
1487242dc3dbeb210b5e876a3c42d1ec1a667fc621aPrimiano Tucci  if (!Ty) return false;
1495267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)  if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
1505267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)    // In strong mode any array, regardless of type and size, triggers a
1515267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)    // protector
1525267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)    if (Strong)
1535267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)      return true;
1545267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)    if (!AT->getElementType()->isIntegerTy(8)) {
1555267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)      // If we're on a non-Darwin platform or we're inside of a structure, don't
1565267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)      // add stack protectors unless the array is a character array.
1575267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)      if (InStruct || !Trip.isOSDarwin())
1585267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)          return false;
1595267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)    }
1605267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)
1615267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)    // If an array has more than SSPBufferSize bytes of allocated space, then we
1625267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)    // emit stack protectors.
1635267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)    if (SSPBufferSize <= TLI->getDataLayout()->getTypeAllocSize(AT))
164197021e6b966cfb06891637935ef33fff06433d1Ben Murdoch      return true;
1655267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)  }
166e69819bd8e388ea4ad1636a19aa6b2eed4952191Ben Murdoch
1675267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)  const StructType *ST = dyn_cast<StructType>(Ty);
1685267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)  if (!ST) return false;
1695267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)
1705267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)  for (StructType::element_iterator I = ST->element_begin(),
171197021e6b966cfb06891637935ef33fff06433d1Ben Murdoch         E = ST->element_end(); I != E; ++I)
172197021e6b966cfb06891637935ef33fff06433d1Ben Murdoch    if (ContainsProtectableArray(*I, Strong, true))
173197021e6b966cfb06891637935ef33fff06433d1Ben Murdoch      return true;
1745267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)
1755267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)  return false;
1765267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)}
1775267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)
1785267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)bool StackProtector::HasAddressTaken(const Instruction *AI) {
179c1847b1379d12d0e05df27436bf19a9b1bf12deaTorne (Richard Coles)  for (Value::const_use_iterator UI = AI->use_begin(), UE = AI->use_end();
180        UI != UE; ++UI) {
181    const User *U = *UI;
182    if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
183      if (AI == SI->getValueOperand())
184        return true;
185    } else if (const PtrToIntInst *SI = dyn_cast<PtrToIntInst>(U)) {
186      if (AI == SI->getOperand(0))
187        return true;
188    } else if (isa<CallInst>(U)) {
189      return true;
190    } else if (isa<InvokeInst>(U)) {
191      return true;
192    } else if (const SelectInst *SI = dyn_cast<SelectInst>(U)) {
193      if (HasAddressTaken(SI))
194        return true;
195    } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
196      // Keep track of what PHI nodes we have already visited to ensure
197      // they are only visited once.
198      if (VisitedPHIs.insert(PN))
199        if (HasAddressTaken(PN))
200          return true;
201    } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
202      if (HasAddressTaken(GEP))
203        return true;
204    } else if (const BitCastInst *BI = dyn_cast<BitCastInst>(U)) {
205      if (HasAddressTaken(BI))
206        return true;
207    }
208  }
209  return false;
210}
211
212/// \brief Check whether or not this function needs a stack protector based
213/// upon the stack protector level.
214///
215/// We use two heuristics: a standard (ssp) and strong (sspstrong).
216/// The standard heuristic which will add a guard variable to functions that
217/// call alloca with a either a variable size or a size >= SSPBufferSize,
218/// functions with character buffers larger than SSPBufferSize, and functions
219/// with aggregates containing character buffers larger than SSPBufferSize. The
220/// strong heuristic will add a guard variables to functions that call alloca
221/// regardless of size, functions with any buffer regardless of type and size,
222/// functions with aggregates that contain any buffer regardless of type and
223/// size, and functions that contain stack-based variables that have had their
224/// address taken.
225bool StackProtector::RequiresStackProtector() {
226  bool Strong = false;
227  if (F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
228                                      Attribute::StackProtectReq))
229    return true;
230  else if (F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
231                                           Attribute::StackProtectStrong))
232    Strong = true;
233  else if (!F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
234                                            Attribute::StackProtect))
235    return false;
236
237  for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
238    BasicBlock *BB = I;
239
240    for (BasicBlock::iterator
241           II = BB->begin(), IE = BB->end(); II != IE; ++II) {
242      if (AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
243        if (AI->isArrayAllocation()) {
244          // SSP-Strong: Enable protectors for any call to alloca, regardless
245          // of size.
246          if (Strong)
247            return true;
248
249          if (const ConstantInt *CI =
250               dyn_cast<ConstantInt>(AI->getArraySize())) {
251            if (CI->getLimitedValue(SSPBufferSize) >= SSPBufferSize)
252              // A call to alloca with size >= SSPBufferSize requires
253              // stack protectors.
254              return true;
255          } else {
256            // A call to alloca with a variable size requires protectors.
257            return true;
258          }
259        }
260
261        if (ContainsProtectableArray(AI->getAllocatedType(), Strong))
262          return true;
263
264        if (Strong && HasAddressTaken(AI)) {
265          ++NumAddrTaken;
266          return true;
267        }
268      }
269    }
270  }
271
272  return false;
273}
274
275static bool InstructionWillNotHaveChain(const Instruction *I) {
276  return !I->mayHaveSideEffects() && !I->mayReadFromMemory() &&
277    isSafeToSpeculativelyExecute(I);
278}
279
280/// Identify if RI has a previous instruction in the "Tail Position" and return
281/// it. Otherwise return 0.
282///
283/// This is based off of the code in llvm::isInTailCallPosition. The difference
284/// is that it inverts the first part of llvm::isInTailCallPosition since
285/// isInTailCallPosition is checking if a call is in a tail call position, and
286/// we are searching for an unknown tail call that might be in the tail call
287/// position. Once we find the call though, the code uses the same refactored
288/// code, returnTypeIsEligibleForTailCall.
289static CallInst *FindPotentialTailCall(BasicBlock *BB, ReturnInst *RI,
290                                       const TargetLoweringBase *TLI) {
291  // Establish a reasonable upper bound on the maximum amount of instructions we
292  // will look through to find a tail call.
293  unsigned SearchCounter = 0;
294  const unsigned MaxSearch = 4;
295  bool NoInterposingChain = true;
296
297  for (BasicBlock::reverse_iterator I = llvm::next(BB->rbegin()), E = BB->rend();
298       I != E && SearchCounter < MaxSearch; ++I) {
299    Instruction *Inst = &*I;
300
301    // Skip over debug intrinsics and do not allow them to affect our MaxSearch
302    // counter.
303    if (isa<DbgInfoIntrinsic>(Inst))
304      continue;
305
306    // If we find a call and the following conditions are satisifed, then we
307    // have found a tail call that satisfies at least the target independent
308    // requirements of a tail call:
309    //
310    // 1. The call site has the tail marker.
311    //
312    // 2. The call site either will not cause the creation of a chain or if a
313    // chain is necessary there are no instructions in between the callsite and
314    // the call which would create an interposing chain.
315    //
316    // 3. The return type of the function does not impede tail call
317    // optimization.
318    if (CallInst *CI = dyn_cast<CallInst>(Inst)) {
319      if (CI->isTailCall() &&
320          (InstructionWillNotHaveChain(CI) || NoInterposingChain) &&
321          returnTypeIsEligibleForTailCall(BB->getParent(), CI, RI, *TLI))
322        return CI;
323    }
324
325    // If we did not find a call see if we have an instruction that may create
326    // an interposing chain.
327    NoInterposingChain = NoInterposingChain && InstructionWillNotHaveChain(Inst);
328
329    // Increment max search.
330    SearchCounter++;
331  }
332
333  return 0;
334}
335
336/// Insert code into the entry block that stores the __stack_chk_guard
337/// variable onto the stack:
338///
339///   entry:
340///     StackGuardSlot = alloca i8*
341///     StackGuard = load __stack_chk_guard
342///     call void @llvm.stackprotect.create(StackGuard, StackGuardSlot)
343///
344/// Returns true if the platform/triple supports the stackprotectorcreate pseudo
345/// node.
346static bool CreatePrologue(Function *F, Module *M, ReturnInst *RI,
347                           const TargetLoweringBase *TLI, const Triple &Trip,
348                           AllocaInst *&AI, Value *&StackGuardVar) {
349  bool SupportsSelectionDAGSP = false;
350  PointerType *PtrTy = Type::getInt8PtrTy(RI->getContext());
351  unsigned AddressSpace, Offset;
352  if (TLI->getStackCookieLocation(AddressSpace, Offset)) {
353    Constant *OffsetVal =
354      ConstantInt::get(Type::getInt32Ty(RI->getContext()), Offset);
355
356    StackGuardVar = ConstantExpr::getIntToPtr(OffsetVal,
357                                              PointerType::get(PtrTy,
358                                                               AddressSpace));
359  } else if (Trip.getOS() == llvm::Triple::OpenBSD) {
360    StackGuardVar = M->getOrInsertGlobal("__guard_local", PtrTy);
361    cast<GlobalValue>(StackGuardVar)
362      ->setVisibility(GlobalValue::HiddenVisibility);
363  } else {
364    SupportsSelectionDAGSP = true;
365    StackGuardVar = M->getOrInsertGlobal("__stack_chk_guard", PtrTy);
366  }
367
368  BasicBlock &Entry = F->getEntryBlock();
369  Instruction *InsPt = &Entry.front();
370
371  AI = new AllocaInst(PtrTy, "StackGuardSlot", InsPt);
372  LoadInst *LI = new LoadInst(StackGuardVar, "StackGuard", false, InsPt);
373
374  Value *Args[] = { LI, AI };
375  CallInst::
376    Create(Intrinsic::getDeclaration(M, Intrinsic::stackprotector),
377           Args, "", InsPt);
378
379  return SupportsSelectionDAGSP;
380}
381
382/// InsertStackProtectors - Insert code into the prologue and epilogue of the
383/// function.
384///
385///  - The prologue code loads and stores the stack guard onto the stack.
386///  - The epilogue checks the value stored in the prologue against the original
387///    value. It calls __stack_chk_fail if they differ.
388bool StackProtector::InsertStackProtectors() {
389  bool HasPrologue = false;
390  bool SupportsSelectionDAGSP =
391    EnableSelectionDAGSP && !TM->Options.EnableFastISel;
392  AllocaInst *AI = 0;           // Place on stack that stores the stack guard.
393  Value *StackGuardVar = 0;     // The stack guard variable.
394
395  for (Function::iterator I = F->begin(), E = F->end(); I != E; ) {
396    BasicBlock *BB = I++;
397    ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
398    if (!RI) continue;
399
400    if (!HasPrologue) {
401      HasPrologue = true;
402      SupportsSelectionDAGSP &= CreatePrologue(F, M, RI, TLI, Trip, AI,
403                                               StackGuardVar);
404    }
405
406    if (SupportsSelectionDAGSP) {
407      // Since we have a potential tail call, insert the special stack check
408      // intrinsic.
409      Instruction *InsertionPt = 0;
410      if (CallInst *CI = FindPotentialTailCall(BB, RI, TLI)) {
411        InsertionPt = CI;
412      } else {
413        InsertionPt = RI;
414        // At this point we know that BB has a return statement so it *DOES*
415        // have a terminator.
416        assert(InsertionPt != 0 && "BB must have a terminator instruction at "
417               "this point.");
418      }
419
420      Function *Intrinsic =
421        Intrinsic::getDeclaration(M, Intrinsic::stackprotectorcheck);
422      Value *Args[] = { StackGuardVar };
423      CallInst::Create(Intrinsic, Args, "", InsertionPt);
424
425    } else {
426      // If we do not support SelectionDAG based tail calls, generate IR level
427      // tail calls.
428      //
429      // For each block with a return instruction, convert this:
430      //
431      //   return:
432      //     ...
433      //     ret ...
434      //
435      // into this:
436      //
437      //   return:
438      //     ...
439      //     %1 = load __stack_chk_guard
440      //     %2 = load StackGuardSlot
441      //     %3 = cmp i1 %1, %2
442      //     br i1 %3, label %SP_return, label %CallStackCheckFailBlk
443      //
444      //   SP_return:
445      //     ret ...
446      //
447      //   CallStackCheckFailBlk:
448      //     call void @__stack_chk_fail()
449      //     unreachable
450
451      // Create the FailBB. We duplicate the BB every time since the MI tail
452      // merge pass will merge together all of the various BB into one including
453      // fail BB generated by the stack protector pseudo instruction.
454      BasicBlock *FailBB = CreateFailBB();
455
456      // Split the basic block before the return instruction.
457      BasicBlock *NewBB = BB->splitBasicBlock(RI, "SP_return");
458
459      // Update the dominator tree if we need to.
460      if (DT && DT->isReachableFromEntry(BB)) {
461        DT->addNewBlock(NewBB, BB);
462        DT->addNewBlock(FailBB, BB);
463      }
464
465      // Remove default branch instruction to the new BB.
466      BB->getTerminator()->eraseFromParent();
467
468      // Move the newly created basic block to the point right after the old
469      // basic block so that it's in the "fall through" position.
470      NewBB->moveAfter(BB);
471
472      // Generate the stack protector instructions in the old basic block.
473      LoadInst *LI1 = new LoadInst(StackGuardVar, "", false, BB);
474      LoadInst *LI2 = new LoadInst(AI, "", true, BB);
475      ICmpInst *Cmp = new ICmpInst(*BB, CmpInst::ICMP_EQ, LI1, LI2, "");
476      BranchInst::Create(NewBB, FailBB, Cmp, BB);
477    }
478  }
479
480  // Return if we didn't modify any basic blocks. I.e., there are no return
481  // statements in the function.
482  if (!HasPrologue)
483    return false;
484
485  return true;
486}
487
488/// CreateFailBB - Create a basic block to jump to when the stack protector
489/// check fails.
490BasicBlock *StackProtector::CreateFailBB() {
491  LLVMContext &Context = F->getContext();
492  BasicBlock *FailBB = BasicBlock::Create(Context, "CallStackCheckFailBlk", F);
493  if (Trip.getOS() == llvm::Triple::OpenBSD) {
494    Constant *StackChkFail = M->getOrInsertFunction(
495        "__stack_smash_handler", Type::getVoidTy(Context),
496        Type::getInt8PtrTy(Context), NULL);
497
498    Constant *NameStr = ConstantDataArray::getString(Context, F->getName());
499    Constant *FuncName =
500        new GlobalVariable(*M, NameStr->getType(), true,
501                           GlobalVariable::PrivateLinkage, NameStr, "SSH");
502
503    SmallVector<Constant *, 2> IdxList;
504    IdxList.push_back(ConstantInt::get(Type::getInt8Ty(Context), 0));
505    IdxList.push_back(ConstantInt::get(Type::getInt8Ty(Context), 0));
506
507    SmallVector<Value *, 1> Args;
508    Args.push_back(ConstantExpr::getGetElementPtr(FuncName, IdxList));
509
510    CallInst::Create(StackChkFail, Args, "", FailBB);
511  } else {
512    Constant *StackChkFail = M->getOrInsertFunction(
513        "__stack_chk_fail", Type::getVoidTy(Context), NULL);
514    CallInst::Create(StackChkFail, "", FailBB);
515  }
516  new UnreachableInst(Context, FailBB);
517  return FailBB;
518}
519