LLVM  3.7.0
SafeStack.cpp
Go to the documentation of this file.
1 //===-- SafeStack.cpp - Safe Stack Insertion ------------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass splits the stack into the safe stack (kept as-is for LLVM backend)
11 // and the unsafe stack (explicitly allocated and managed through the runtime
12 // support library).
13 //
14 // http://clang.llvm.org/docs/SafeStack.html
15 //
16 //===----------------------------------------------------------------------===//
17 
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/ADT/Triple.h"
23 #include "llvm/IR/Constants.h"
24 #include "llvm/IR/DataLayout.h"
25 #include "llvm/IR/DerivedTypes.h"
26 #include "llvm/IR/DIBuilder.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/IR/InstIterator.h"
29 #include "llvm/IR/Instructions.h"
30 #include "llvm/IR/IntrinsicInst.h"
31 #include "llvm/IR/Intrinsics.h"
32 #include "llvm/IR/IRBuilder.h"
33 #include "llvm/IR/Module.h"
34 #include "llvm/Pass.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/Format.h"
42 
43 using namespace llvm;
44 
45 #define DEBUG_TYPE "safestack"
46 
47 namespace llvm {
48 
49 STATISTIC(NumFunctions, "Total number of functions");
50 STATISTIC(NumUnsafeStackFunctions, "Number of functions with unsafe stack");
51 STATISTIC(NumUnsafeStackRestorePointsFunctions,
52  "Number of functions that use setjmp or exceptions");
53 
54 STATISTIC(NumAllocas, "Total number of allocas");
55 STATISTIC(NumUnsafeStaticAllocas, "Number of unsafe static allocas");
56 STATISTIC(NumUnsafeDynamicAllocas, "Number of unsafe dynamic allocas");
57 STATISTIC(NumUnsafeStackRestorePoints, "Number of setjmps and landingpads");
58 
59 } // namespace llvm
60 
61 namespace {
62 
63 /// Check whether a given alloca instruction (AI) should be put on the safe
64 /// stack or not. The function analyzes all uses of AI and checks whether it is
65 /// only accessed in a memory safe way (as decided statically).
66 bool IsSafeStackAlloca(const AllocaInst *AI) {
67  // Go through all uses of this alloca and check whether all accesses to the
68  // allocated object are statically known to be memory safe and, hence, the
69  // object can be placed on the safe stack.
70 
73  WorkList.push_back(AI);
74 
75  // A DFS search through all uses of the alloca in bitcasts/PHI/GEPs/etc.
76  while (!WorkList.empty()) {
77  const Instruction *V = WorkList.pop_back_val();
78  for (const Use &UI : V->uses()) {
79  auto I = cast<const Instruction>(UI.getUser());
80  assert(V == UI.get());
81 
82  switch (I->getOpcode()) {
83  case Instruction::Load:
84  // Loading from a pointer is safe.
85  break;
86  case Instruction::VAArg:
87  // "va-arg" from a pointer is safe.
88  break;
89  case Instruction::Store:
90  if (V == I->getOperand(0))
91  // Stored the pointer - conservatively assume it may be unsafe.
92  return false;
93  // Storing to the pointee is safe.
94  break;
95 
96  case Instruction::GetElementPtr:
97  if (!cast<const GetElementPtrInst>(I)->hasAllConstantIndices())
98  // GEP with non-constant indices can lead to memory errors.
99  // This also applies to inbounds GEPs, as the inbounds attribute
100  // represents an assumption that the address is in bounds, rather than
101  // an assertion that it is.
102  return false;
103 
104  // We assume that GEP on static alloca with constant indices is safe,
105  // otherwise a compiler would detect it and warn during compilation.
106 
107  if (!isa<const ConstantInt>(AI->getArraySize()))
108  // However, if the array size itself is not constant, the access
109  // might still be unsafe at runtime.
110  return false;
111 
112  /* fallthrough */
113 
114  case Instruction::BitCast:
115  case Instruction::IntToPtr:
116  case Instruction::PHI:
117  case Instruction::PtrToInt:
118  case Instruction::Select:
119  // The object can be safe or not, depending on how the result of the
120  // instruction is used.
121  if (Visited.insert(I).second)
122  WorkList.push_back(cast<const Instruction>(I));
123  break;
124 
125  case Instruction::Call:
126  case Instruction::Invoke: {
127  // FIXME: add support for memset and memcpy intrinsics.
129 
130  // LLVM 'nocapture' attribute is only set for arguments whose address
131  // is not stored, passed around, or used in any other non-trivial way.
132  // We assume that passing a pointer to an object as a 'nocapture'
133  // argument is safe.
134  // FIXME: a more precise solution would require an interprocedural
135  // analysis here, which would look at all uses of an argument inside
136  // the function being called.
137  ImmutableCallSite::arg_iterator B = CS.arg_begin(), E = CS.arg_end();
138  for (ImmutableCallSite::arg_iterator A = B; A != E; ++A)
139  if (A->get() == V && !CS.doesNotCapture(A - B))
140  // The parameter is not marked 'nocapture' - unsafe.
141  return false;
142  continue;
143  }
144 
145  default:
146  // The object is unsafe if it is used in any other way.
147  return false;
148  }
149  }
150  }
151 
152  // All uses of the alloca are safe, we can place it on the safe stack.
153  return true;
154 }
155 
156 /// The SafeStack pass splits the stack of each function into the
157 /// safe stack, which is only accessed through memory safe dereferences
158 /// (as determined statically), and the unsafe stack, which contains all
159 /// local variables that are accessed in unsafe ways.
160 class SafeStack : public FunctionPass {
161  const DataLayout *DL;
162 
163  Type *StackPtrTy;
164  Type *IntPtrTy;
165  Type *Int32Ty;
166  Type *Int8Ty;
167 
168  Constant *UnsafeStackPtr = nullptr;
169 
170  /// Unsafe stack alignment. Each stack frame must ensure that the stack is
171  /// aligned to this value. We need to re-align the unsafe stack if the
172  /// alignment of any object on the stack exceeds this value.
173  ///
174  /// 16 seems like a reasonable upper bound on the alignment of objects that we
175  /// might expect to appear on the stack on most common targets.
176  enum { StackAlignment = 16 };
177 
178  /// \brief Build a constant representing a pointer to the unsafe stack
179  /// pointer.
180  Constant *getOrCreateUnsafeStackPtr(Module &M);
181 
182  /// \brief Find all static allocas, dynamic allocas, return instructions and
183  /// stack restore points (exception unwind blocks and setjmp calls) in the
184  /// given function and append them to the respective vectors.
185  void findInsts(Function &F, SmallVectorImpl<AllocaInst *> &StaticAllocas,
186  SmallVectorImpl<AllocaInst *> &DynamicAllocas,
188  SmallVectorImpl<Instruction *> &StackRestorePoints);
189 
190  /// \brief Allocate space for all static allocas in \p StaticAllocas,
191  /// replace allocas with pointers into the unsafe stack and generate code to
192  /// restore the stack pointer before all return instructions in \p Returns.
193  ///
194  /// \returns A pointer to the top of the unsafe stack after all unsafe static
195  /// allocas are allocated.
196  Value *moveStaticAllocasToUnsafeStack(Function &F,
197  ArrayRef<AllocaInst *> StaticAllocas,
198  ArrayRef<ReturnInst *> Returns);
199 
200  /// \brief Generate code to restore the stack after all stack restore points
201  /// in \p StackRestorePoints.
202  ///
203  /// \returns A local variable in which to maintain the dynamic top of the
204  /// unsafe stack if needed.
205  AllocaInst *
206  createStackRestorePoints(Function &F,
207  ArrayRef<Instruction *> StackRestorePoints,
208  Value *StaticTop, bool NeedDynamicTop);
209 
210  /// \brief Replace all allocas in \p DynamicAllocas with code to allocate
211  /// space dynamically on the unsafe stack and store the dynamic unsafe stack
212  /// top to \p DynamicTop if non-null.
213  void moveDynamicAllocasToUnsafeStack(Function &F, Value *UnsafeStackPtr,
214  AllocaInst *DynamicTop,
215  ArrayRef<AllocaInst *> DynamicAllocas);
216 
217 public:
218  static char ID; // Pass identification, replacement for typeid.
219  SafeStack() : FunctionPass(ID), DL(nullptr) {
221  }
222 
223  virtual void getAnalysisUsage(AnalysisUsage &AU) const {
225  }
226 
227  virtual bool doInitialization(Module &M) {
228  DL = &M.getDataLayout();
229 
230  StackPtrTy = Type::getInt8PtrTy(M.getContext());
231  IntPtrTy = DL->getIntPtrType(M.getContext());
232  Int32Ty = Type::getInt32Ty(M.getContext());
233  Int8Ty = Type::getInt8Ty(M.getContext());
234 
235  return false;
236  }
237 
238  bool runOnFunction(Function &F);
239 
240 }; // class SafeStack
241 
242 Constant *SafeStack::getOrCreateUnsafeStackPtr(Module &M) {
243  // The unsafe stack pointer is stored in a global variable with a magic name.
244  const char *kUnsafeStackPtrVar = "__safestack_unsafe_stack_ptr";
245 
246  auto UnsafeStackPtr =
247  dyn_cast_or_null<GlobalVariable>(M.getNamedValue(kUnsafeStackPtrVar));
248 
249  if (!UnsafeStackPtr) {
250  // The global variable is not defined yet, define it ourselves.
251  // We use the initial-exec TLS model because we do not support the variable
252  // living anywhere other than in the main executable.
253  UnsafeStackPtr = new GlobalVariable(
254  /*Module=*/M, /*Type=*/StackPtrTy,
255  /*isConstant=*/false, /*Linkage=*/GlobalValue::ExternalLinkage,
256  /*Initializer=*/0, /*Name=*/kUnsafeStackPtrVar,
257  /*InsertBefore=*/nullptr,
258  /*ThreadLocalMode=*/GlobalValue::InitialExecTLSModel);
259  } else {
260  // The variable exists, check its type and attributes.
261  if (UnsafeStackPtr->getValueType() != StackPtrTy) {
262  report_fatal_error(Twine(kUnsafeStackPtrVar) + " must have void* type");
263  }
264 
265  if (!UnsafeStackPtr->isThreadLocal()) {
266  report_fatal_error(Twine(kUnsafeStackPtrVar) + " must be thread-local");
267  }
268  }
269 
270  return UnsafeStackPtr;
271 }
272 
273 void SafeStack::findInsts(Function &F,
274  SmallVectorImpl<AllocaInst *> &StaticAllocas,
275  SmallVectorImpl<AllocaInst *> &DynamicAllocas,
277  SmallVectorImpl<Instruction *> &StackRestorePoints) {
278  for (Instruction &I : inst_range(&F)) {
279  if (auto AI = dyn_cast<AllocaInst>(&I)) {
280  ++NumAllocas;
281 
282  if (IsSafeStackAlloca(AI))
283  continue;
284 
285  if (AI->isStaticAlloca()) {
286  ++NumUnsafeStaticAllocas;
287  StaticAllocas.push_back(AI);
288  } else {
289  ++NumUnsafeDynamicAllocas;
290  DynamicAllocas.push_back(AI);
291  }
292  } else if (auto RI = dyn_cast<ReturnInst>(&I)) {
293  Returns.push_back(RI);
294  } else if (auto CI = dyn_cast<CallInst>(&I)) {
295  // setjmps require stack restore.
296  if (CI->getCalledFunction() && CI->canReturnTwice())
297  StackRestorePoints.push_back(CI);
298  } else if (auto LP = dyn_cast<LandingPadInst>(&I)) {
299  // Exception landing pads require stack restore.
300  StackRestorePoints.push_back(LP);
301  } else if (auto II = dyn_cast<IntrinsicInst>(&I)) {
302  if (II->getIntrinsicID() == Intrinsic::gcroot)
304  "gcroot intrinsic not compatible with safestack attribute");
305  }
306  }
307 }
308 
309 AllocaInst *
310 SafeStack::createStackRestorePoints(Function &F,
311  ArrayRef<Instruction *> StackRestorePoints,
312  Value *StaticTop, bool NeedDynamicTop) {
313  if (StackRestorePoints.empty())
314  return nullptr;
315 
316  IRBuilder<> IRB(StaticTop
317  ? cast<Instruction>(StaticTop)->getNextNode()
319 
320  // We need the current value of the shadow stack pointer to restore
321  // after longjmp or exception catching.
322 
323  // FIXME: On some platforms this could be handled by the longjmp/exception
324  // runtime itself.
325 
326  AllocaInst *DynamicTop = nullptr;
327  if (NeedDynamicTop)
328  // If we also have dynamic alloca's, the stack pointer value changes
329  // throughout the function. For now we store it in an alloca.
330  DynamicTop = IRB.CreateAlloca(StackPtrTy, /*ArraySize=*/nullptr,
331  "unsafe_stack_dynamic_ptr");
332 
333  if (!StaticTop)
334  // We need the original unsafe stack pointer value, even if there are
335  // no unsafe static allocas.
336  StaticTop = IRB.CreateLoad(UnsafeStackPtr, false, "unsafe_stack_ptr");
337 
338  if (NeedDynamicTop)
339  IRB.CreateStore(StaticTop, DynamicTop);
340 
341  // Restore current stack pointer after longjmp/exception catch.
342  for (Instruction *I : StackRestorePoints) {
343  ++NumUnsafeStackRestorePoints;
344 
345  IRB.SetInsertPoint(cast<Instruction>(I->getNextNode()));
346  Value *CurrentTop = DynamicTop ? IRB.CreateLoad(DynamicTop) : StaticTop;
347  IRB.CreateStore(CurrentTop, UnsafeStackPtr);
348  }
349 
350  return DynamicTop;
351 }
352 
353 Value *
354 SafeStack::moveStaticAllocasToUnsafeStack(Function &F,
355  ArrayRef<AllocaInst *> StaticAllocas,
356  ArrayRef<ReturnInst *> Returns) {
357  if (StaticAllocas.empty())
358  return nullptr;
359 
361  DIBuilder DIB(*F.getParent());
362 
363  // We explicitly compute and set the unsafe stack layout for all unsafe
364  // static alloca instructions. We save the unsafe "base pointer" in the
365  // prologue into a local variable and restore it in the epilogue.
366 
367  // Load the current stack pointer (we'll also use it as a base pointer).
368  // FIXME: use a dedicated register for it ?
369  Instruction *BasePointer =
370  IRB.CreateLoad(UnsafeStackPtr, false, "unsafe_stack_ptr");
371  assert(BasePointer->getType() == StackPtrTy);
372 
373  for (ReturnInst *RI : Returns) {
374  IRB.SetInsertPoint(RI);
375  IRB.CreateStore(BasePointer, UnsafeStackPtr);
376  }
377 
378  // Compute maximum alignment among static objects on the unsafe stack.
379  unsigned MaxAlignment = 0;
380  for (AllocaInst *AI : StaticAllocas) {
381  Type *Ty = AI->getAllocatedType();
382  unsigned Align =
383  std::max((unsigned)DL->getPrefTypeAlignment(Ty), AI->getAlignment());
384  if (Align > MaxAlignment)
385  MaxAlignment = Align;
386  }
387 
388  if (MaxAlignment > StackAlignment) {
389  // Re-align the base pointer according to the max requested alignment.
390  assert(isPowerOf2_32(MaxAlignment));
391  IRB.SetInsertPoint(cast<Instruction>(BasePointer->getNextNode()));
392  BasePointer = cast<Instruction>(IRB.CreateIntToPtr(
393  IRB.CreateAnd(IRB.CreatePtrToInt(BasePointer, IntPtrTy),
394  ConstantInt::get(IntPtrTy, ~uint64_t(MaxAlignment - 1))),
395  StackPtrTy));
396  }
397 
398  // Allocate space for every unsafe static AllocaInst on the unsafe stack.
399  int64_t StaticOffset = 0; // Current stack top.
400  for (AllocaInst *AI : StaticAllocas) {
401  IRB.SetInsertPoint(AI);
402 
403  auto CArraySize = cast<ConstantInt>(AI->getArraySize());
404  Type *Ty = AI->getAllocatedType();
405 
406  uint64_t Size = DL->getTypeAllocSize(Ty) * CArraySize->getZExtValue();
407  if (Size == 0)
408  Size = 1; // Don't create zero-sized stack objects.
409 
410  // Ensure the object is properly aligned.
411  unsigned Align =
412  std::max((unsigned)DL->getPrefTypeAlignment(Ty), AI->getAlignment());
413 
414  // Add alignment.
415  // NOTE: we ensure that BasePointer itself is aligned to >= Align.
416  StaticOffset += Size;
417  StaticOffset = RoundUpToAlignment(StaticOffset, Align);
418 
419  Value *Off = IRB.CreateGEP(BasePointer, // BasePointer is i8*
420  ConstantInt::get(Int32Ty, -StaticOffset));
421  Value *NewAI = IRB.CreateBitCast(Off, AI->getType(), AI->getName());
422  if (AI->hasName() && isa<Instruction>(NewAI))
423  cast<Instruction>(NewAI)->takeName(AI);
424 
425  // Replace alloc with the new location.
426  replaceDbgDeclareForAlloca(AI, NewAI, DIB, /*Deref=*/true);
427  AI->replaceAllUsesWith(NewAI);
428  AI->eraseFromParent();
429  }
430 
431  // Re-align BasePointer so that our callees would see it aligned as
432  // expected.
433  // FIXME: no need to update BasePointer in leaf functions.
434  StaticOffset = RoundUpToAlignment(StaticOffset, StackAlignment);
435 
436  // Update shadow stack pointer in the function epilogue.
437  IRB.SetInsertPoint(cast<Instruction>(BasePointer->getNextNode()));
438 
439  Value *StaticTop =
440  IRB.CreateGEP(BasePointer, ConstantInt::get(Int32Ty, -StaticOffset),
441  "unsafe_stack_static_top");
442  IRB.CreateStore(StaticTop, UnsafeStackPtr);
443  return StaticTop;
444 }
445 
446 void SafeStack::moveDynamicAllocasToUnsafeStack(
447  Function &F, Value *UnsafeStackPtr, AllocaInst *DynamicTop,
448  ArrayRef<AllocaInst *> DynamicAllocas) {
449  DIBuilder DIB(*F.getParent());
450 
451  for (AllocaInst *AI : DynamicAllocas) {
452  IRBuilder<> IRB(AI);
453 
454  // Compute the new SP value (after AI).
455  Value *ArraySize = AI->getArraySize();
456  if (ArraySize->getType() != IntPtrTy)
457  ArraySize = IRB.CreateIntCast(ArraySize, IntPtrTy, false);
458 
459  Type *Ty = AI->getAllocatedType();
460  uint64_t TySize = DL->getTypeAllocSize(Ty);
461  Value *Size = IRB.CreateMul(ArraySize, ConstantInt::get(IntPtrTy, TySize));
462 
463  Value *SP = IRB.CreatePtrToInt(IRB.CreateLoad(UnsafeStackPtr), IntPtrTy);
464  SP = IRB.CreateSub(SP, Size);
465 
466  // Align the SP value to satisfy the AllocaInst, type and stack alignments.
467  unsigned Align = std::max(
468  std::max((unsigned)DL->getPrefTypeAlignment(Ty), AI->getAlignment()),
469  (unsigned)StackAlignment);
470 
471  assert(isPowerOf2_32(Align));
472  Value *NewTop = IRB.CreateIntToPtr(
473  IRB.CreateAnd(SP, ConstantInt::get(IntPtrTy, ~uint64_t(Align - 1))),
474  StackPtrTy);
475 
476  // Save the stack pointer.
477  IRB.CreateStore(NewTop, UnsafeStackPtr);
478  if (DynamicTop)
479  IRB.CreateStore(NewTop, DynamicTop);
480 
481  Value *NewAI = IRB.CreateIntToPtr(SP, AI->getType());
482  if (AI->hasName() && isa<Instruction>(NewAI))
483  NewAI->takeName(AI);
484 
485  replaceDbgDeclareForAlloca(AI, NewAI, DIB, /*Deref=*/true);
486  AI->replaceAllUsesWith(NewAI);
487  AI->eraseFromParent();
488  }
489 
490  if (!DynamicAllocas.empty()) {
491  // Now go through the instructions again, replacing stacksave/stackrestore.
492  for (inst_iterator It = inst_begin(&F), Ie = inst_end(&F); It != Ie;) {
493  Instruction *I = &*(It++);
494  auto II = dyn_cast<IntrinsicInst>(I);
495  if (!II)
496  continue;
497 
498  if (II->getIntrinsicID() == Intrinsic::stacksave) {
499  IRBuilder<> IRB(II);
500  Instruction *LI = IRB.CreateLoad(UnsafeStackPtr);
501  LI->takeName(II);
502  II->replaceAllUsesWith(LI);
503  II->eraseFromParent();
504  } else if (II->getIntrinsicID() == Intrinsic::stackrestore) {
505  IRBuilder<> IRB(II);
506  Instruction *SI = IRB.CreateStore(II->getArgOperand(0), UnsafeStackPtr);
507  SI->takeName(II);
508  assert(II->use_empty());
509  II->eraseFromParent();
510  }
511  }
512  }
513 }
514 
515 bool SafeStack::runOnFunction(Function &F) {
516  auto AA = &getAnalysis<AliasAnalysis>();
517 
518  DEBUG(dbgs() << "[SafeStack] Function: " << F.getName() << "\n");
519 
521  DEBUG(dbgs() << "[SafeStack] safestack is not requested"
522  " for this function\n");
523  return false;
524  }
525 
526  if (F.isDeclaration()) {
527  DEBUG(dbgs() << "[SafeStack] function definition"
528  " is not available\n");
529  return false;
530  }
531 
532  {
533  // Make sure the regular stack protector won't run on this function
534  // (safestack attribute takes precedence).
535  AttrBuilder B;
541  AttributeSet::get(F.getContext(), AttributeSet::FunctionIndex, B));
542  }
543 
544  if (AA->onlyReadsMemory(&F)) {
545  // XXX: we don't protect against information leak attacks for now.
546  DEBUG(dbgs() << "[SafeStack] function only reads memory\n");
547  return false;
548  }
549 
550  ++NumFunctions;
551 
552  SmallVector<AllocaInst *, 16> StaticAllocas;
553  SmallVector<AllocaInst *, 4> DynamicAllocas;
555 
556  // Collect all points where stack gets unwound and needs to be restored
557  // This is only necessary because the runtime (setjmp and unwind code) is
558  // not aware of the unsafe stack and won't unwind/restore it prorerly.
559  // To work around this problem without changing the runtime, we insert
560  // instrumentation to restore the unsafe stack pointer when necessary.
561  SmallVector<Instruction *, 4> StackRestorePoints;
562 
563  // Find all static and dynamic alloca instructions that must be moved to the
564  // unsafe stack, all return instructions and stack restore points.
565  findInsts(F, StaticAllocas, DynamicAllocas, Returns, StackRestorePoints);
566 
567  if (StaticAllocas.empty() && DynamicAllocas.empty() &&
568  StackRestorePoints.empty())
569  return false; // Nothing to do in this function.
570 
571  if (!StaticAllocas.empty() || !DynamicAllocas.empty())
572  ++NumUnsafeStackFunctions; // This function has the unsafe stack.
573 
574  if (!StackRestorePoints.empty())
575  ++NumUnsafeStackRestorePointsFunctions;
576 
577  if (!UnsafeStackPtr)
578  UnsafeStackPtr = getOrCreateUnsafeStackPtr(*F.getParent());
579 
580  // The top of the unsafe stack after all unsafe static allocas are allocated.
581  Value *StaticTop = moveStaticAllocasToUnsafeStack(F, StaticAllocas, Returns);
582 
583  // Safe stack object that stores the current unsafe stack top. It is updated
584  // as unsafe dynamic (non-constant-sized) allocas are allocated and freed.
585  // This is only needed if we need to restore stack pointer after longjmp
586  // or exceptions, and we have dynamic allocations.
587  // FIXME: a better alternative might be to store the unsafe stack pointer
588  // before setjmp / invoke instructions.
589  AllocaInst *DynamicTop = createStackRestorePoints(
590  F, StackRestorePoints, StaticTop, !DynamicAllocas.empty());
591 
592  // Handle dynamic allocas.
593  moveDynamicAllocasToUnsafeStack(F, UnsafeStackPtr, DynamicTop,
594  DynamicAllocas);
595 
596  DEBUG(dbgs() << "[SafeStack] safestack applied\n");
597  return true;
598 }
599 
600 } // end anonymous namespace
601 
602 char SafeStack::ID = 0;
603 INITIALIZE_PASS_BEGIN(SafeStack, "safe-stack",
604  "Safe Stack instrumentation pass", false, false)
606 INITIALIZE_PASS_END(SafeStack, "safe-stack", "Safe Stack instrumentation pass",
607  false, false)
608 
609 FunctionPass *llvm::createSafeStackPass() { return new SafeStack(); }
ReturnInst - Return a value (possibly void), from a function.
iplist< Instruction >::iterator eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing basic block and deletes it...
Definition: Instruction.cpp:70
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:104
AllocaInst * CreateAlloca(Type *Ty, Value *ArraySize=nullptr, const Twine &Name="")
Definition: IRBuilder.h:967
iterator_range< use_iterator > uses()
Definition: Value.h:283
LoadInst * CreateLoad(Value *Ptr, const char *Name)
Definition: IRBuilder.h:973
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
Definition: Function.cpp:223
bool hasName() const
Definition: Value.h:228
STATISTIC(NumFunctions,"Total number of functions")
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:114
FunctionPass * createSafeStackPass()
This pass splits the stack into a safe stack and an unsafe stack to protect against stack-based overf...
Definition: SafeStack.cpp:609
Externally visible function.
Definition: GlobalValue.h:40
F(f)
FunctionType * getType(LLVMContext &Context, ID id, ArrayRef< Type * > Tys=None)
Return the function type for an intrinsic.
Definition: Function.cpp:822
AttrBuilder & addAttribute(Attribute::AttrKind Val)
Add an attribute to the builder.
User::const_op_iterator arg_iterator
arg_iterator - The type of iterator to use when looping over actual arguments at this call site...
Definition: CallSite.h:147
INITIALIZE_PASS_BEGIN(SafeStack,"safe-stack","Safe Stack instrumentation pass", false, false) INITIALIZE_PASS_END(SafeStack
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(const char *reason, bool gen_crash_diag=true)
Reports a serious error, calling any installed error handler.
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:188
safe Safe Stack instrumentation pass
Definition: SafeStack.cpp:606
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:70
inst_iterator inst_begin(Function *F)
Definition: InstIterator.h:127
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:79
T LLVM_ATTRIBUTE_UNUSED_RESULT pop_back_val()
Definition: SmallVector.h:406
A Use represents the edge between a Value definition and its users.
Definition: Use.h:69
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:75
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: APInt.h:33
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:517
Safe Stack protection.
Definition: Attributes.h:113
bool LLVM_ATTRIBUTE_UNUSED_RESULT empty() const
Definition: SmallVector.h:57
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: ArrayRef.h:31
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:351
void removeAttributes(unsigned i, AttributeSet attr)
removes the attributes from the list of attributes.
Definition: Function.cpp:353
void takeName(Value *V)
Transfer the name from V to this value.
Definition: Value.cpp:256
Stack protection.
Definition: Attributes.h:110
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block...
Definition: IRBuilder.h:85
#define true
Definition: ConvertUTF.c:66
Wrapper pass for TargetTransformInfo.
* if(!EatIfPresent(lltok::kw_thread_local)) return false
ParseOptionalThreadLocal := /*empty.
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:45
This is an important base class in LLVM.
Definition: Constant.h:41
PointerType * getType() const
getType - Overload to return most specific pointer type
Definition: Instructions.h:115
This file contains the declarations for the subclasses of Constant, which represent the different fla...
unsigned getAlignment() const
getAlignment - Return the alignment of the memory that is being allocated by the instruction.
Definition: Instructions.h:130
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:264
Represent the analysis usage information of a pass.
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:294
LLVM_ATTRIBUTE_UNUSED_RESULT bool isa(const Y &Val)
Definition: Casting.h:132
bool empty() const
empty - Check if the array is empty.
Definition: ArrayRef.h:129
static PointerType * getInt8PtrTy(LLVMContext &C, unsigned AS=0)
Definition: Type.cpp:283
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:299
This is the shared class of boolean and integer constants.
Definition: Constants.h:47
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:861
bool isStaticAlloca() const
isStaticAlloca - Return true if this alloca is in the entry block of the function and is a constant s...
Module.h This file contains the declarations for the Module class.
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:222
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
Definition: Constants.cpp:582
const BasicBlock & getEntryBlock() const
Definition: Function.h:442
static cl::opt< AlignMode > Align(cl::desc("Load/store alignment support"), cl::Hidden, cl::init(NoStrictAlign), cl::values(clEnumValN(StrictAlign,"aarch64-strict-align","Disallow all unaligned memory accesses"), clEnumValN(NoStrictAlign,"aarch64-no-strict-align","Allow unaligned memory accesses"), clEnumValEnd))
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:123
bool replaceDbgDeclareForAlloca(AllocaInst *AI, Value *NewAllocaAddress, DIBuilder &Builder, bool Deref)
Replaces llvm.dbg.declare instruction when an alloca is replaced with a new value.
Definition: Local.cpp:1080
safe Safe Stack instrumentation false
Definition: SafeStack.cpp:606
LLVM_ATTRIBUTE_UNUSED_RESULT std::enable_if< !is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:285
uint64_t RoundUpToAlignment(uint64_t Value, uint64_t Align)
Returns the next integer (mod 2**64) that is greater than or equal to Value and is a multiple of Alig...
Definition: MathExtras.h:609
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Definition: Module.cpp:372
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition: Function.h:217
static IntegerType * getInt32Ty(LLVMContext &C)
Definition: Type.cpp:239
void initializeSafeStackPass(PassRegistry &)
iterator_range< inst_iterator > inst_range(Function *F)
Definition: InstIterator.h:129
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition: Globals.cpp:128
ImmutableCallSite - establish a view to a call site for examination.
Definition: CallSite.h:418
#define I(x, y, z)
Definition: MD5.cpp:54
Strong Stack protection.
Definition: Attributes.h:112
safe stack
Definition: SafeStack.cpp:606
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:365
LLVM Value Representation.
Definition: Value.h:69
const Value * getArraySize() const
getArraySize - Get the number of elements allocated.
Definition: Instructions.h:110
#define DEBUG(X)
Definition: Debug.h:92
bool isPowerOf2_32(uint32_t Value)
isPowerOf2_32 - This function returns true if the argument is a power of two > 0. ...
Definition: MathExtras.h:354
inst_iterator inst_end(Function *F)
Definition: InstIterator.h:128
This pass exposes codegen information to IR-level passes.
iterator getFirstInsertionPt()
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
Definition: BasicBlock.cpp:194
Type * getAllocatedType() const
getAllocatedType - Return the type that is being allocated by the instruction.
Definition: Instructions.h:122
Stack protection required.
Definition: Attributes.h:111
static IntegerType * getInt8Ty(LLVMContext &C)
Definition: Type.cpp:237
GlobalValue * getNamedValue(StringRef Name) const
Return the global value in the module with the specified name, of arbitrary type. ...
Definition: Module.cpp:88
IntrinsicInst - A useful wrapper class for inspecting calls to intrinsic functions.
Definition: IntrinsicInst.h:37
LLVMContext & getContext() const
Get the global data context.
Definition: Module.h:265
AllocaInst - an instruction to allocate memory on the stack.
Definition: Instructions.h:76