AddressSanitizer.cpp revision 8819c84aed10777ba91d4e862229882b8da0b272
1//===-- AddressSanitizer.cpp - memory error detector ------------*- C++ -*-===//
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 file is a part of AddressSanitizer, an address sanity checker.
11// Details of the algorithm:
12//  http://code.google.com/p/address-sanitizer/wiki/AddressSanitizerAlgorithm
13//
14//===----------------------------------------------------------------------===//
15
16#define DEBUG_TYPE "asan"
17
18#include "llvm/Transforms/Instrumentation.h"
19#include "llvm/ADT/ArrayRef.h"
20#include "llvm/ADT/DenseMap.h"
21#include "llvm/ADT/DepthFirstIterator.h"
22#include "llvm/ADT/OwningPtr.h"
23#include "llvm/ADT/SmallSet.h"
24#include "llvm/ADT/SmallString.h"
25#include "llvm/ADT/SmallVector.h"
26#include "llvm/ADT/StringExtras.h"
27#include "llvm/ADT/Triple.h"
28#include "llvm/DIBuilder.h"
29#include "llvm/IR/DataLayout.h"
30#include "llvm/IR/Function.h"
31#include "llvm/IR/IRBuilder.h"
32#include "llvm/IR/InlineAsm.h"
33#include "llvm/IR/IntrinsicInst.h"
34#include "llvm/IR/LLVMContext.h"
35#include "llvm/IR/Module.h"
36#include "llvm/IR/Type.h"
37#include "llvm/InstVisitor.h"
38#include "llvm/Support/CallSite.h"
39#include "llvm/Support/CommandLine.h"
40#include "llvm/Support/DataTypes.h"
41#include "llvm/Support/Debug.h"
42#include "llvm/Support/Endian.h"
43#include "llvm/Support/raw_ostream.h"
44#include "llvm/Support/system_error.h"
45#include "llvm/Transforms/Utils/BasicBlockUtils.h"
46#include "llvm/Transforms/Utils/Cloning.h"
47#include "llvm/Transforms/Utils/Local.h"
48#include "llvm/Transforms/Utils/ModuleUtils.h"
49#include "llvm/Transforms/Utils/SpecialCaseList.h"
50#include <algorithm>
51#include <string>
52
53using namespace llvm;
54
55static const uint64_t kDefaultShadowScale = 3;
56static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
57static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
58static const uint64_t kDefaultShort64bitShadowOffset = 0x7FFF8000;  // < 2G.
59static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 41;
60static const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa8000;
61
62static const size_t kMinStackMallocSize = 1 << 6;  // 64B
63static const size_t kMaxStackMallocSize = 1 << 16;  // 64K
64static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
65static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
66
67static const char *const kAsanModuleCtorName = "asan.module_ctor";
68static const char *const kAsanModuleDtorName = "asan.module_dtor";
69static const int         kAsanCtorAndCtorPriority = 1;
70static const char *const kAsanReportErrorTemplate = "__asan_report_";
71static const char *const kAsanReportLoadN = "__asan_report_load_n";
72static const char *const kAsanReportStoreN = "__asan_report_store_n";
73static const char *const kAsanRegisterGlobalsName = "__asan_register_globals";
74static const char *const kAsanUnregisterGlobalsName =
75    "__asan_unregister_globals";
76static const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
77static const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
78static const char *const kAsanInitName = "__asan_init_v3";
79static const char *const kAsanHandleNoReturnName = "__asan_handle_no_return";
80static const char *const kAsanMappingOffsetName = "__asan_mapping_offset";
81static const char *const kAsanMappingScaleName = "__asan_mapping_scale";
82static const int         kMaxAsanStackMallocSizeClass = 10;
83static const char *const kAsanStackMallocNameTemplate = "__asan_stack_malloc_";
84static const char *const kAsanStackFreeNameTemplate = "__asan_stack_free_";
85static const char *const kAsanGenPrefix = "__asan_gen_";
86static const char *const kAsanPoisonStackMemoryName =
87    "__asan_poison_stack_memory";
88static const char *const kAsanUnpoisonStackMemoryName =
89    "__asan_unpoison_stack_memory";
90
91static const char *const kAsanOptionDetectUAR =
92    "__asan_option_detect_stack_use_after_return";
93
94// These constants must match the definitions in the run-time library.
95static const int kAsanStackLeftRedzoneMagic = 0xf1;
96static const int kAsanStackMidRedzoneMagic = 0xf2;
97static const int kAsanStackRightRedzoneMagic = 0xf3;
98static const int kAsanStackPartialRedzoneMagic = 0xf4;
99#ifndef NDEBUG
100static const int kAsanStackAfterReturnMagic = 0xf5;
101#endif
102
103// Accesses sizes are powers of two: 1, 2, 4, 8, 16.
104static const size_t kNumberOfAccessSizes = 5;
105
106// Command-line flags.
107
108// This flag may need to be replaced with -f[no-]asan-reads.
109static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
110       cl::desc("instrument read instructions"), cl::Hidden, cl::init(true));
111static cl::opt<bool> ClInstrumentWrites("asan-instrument-writes",
112       cl::desc("instrument write instructions"), cl::Hidden, cl::init(true));
113static cl::opt<bool> ClInstrumentAtomics("asan-instrument-atomics",
114       cl::desc("instrument atomic instructions (rmw, cmpxchg)"),
115       cl::Hidden, cl::init(true));
116static cl::opt<bool> ClAlwaysSlowPath("asan-always-slow-path",
117       cl::desc("use instrumentation with slow path for all accesses"),
118       cl::Hidden, cl::init(false));
119// This flag limits the number of instructions to be instrumented
120// in any given BB. Normally, this should be set to unlimited (INT_MAX),
121// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
122// set it to 10000.
123static cl::opt<int> ClMaxInsnsToInstrumentPerBB("asan-max-ins-per-bb",
124       cl::init(10000),
125       cl::desc("maximal number of instructions to instrument in any given BB"),
126       cl::Hidden);
127// This flag may need to be replaced with -f[no]asan-stack.
128static cl::opt<bool> ClStack("asan-stack",
129       cl::desc("Handle stack memory"), cl::Hidden, cl::init(true));
130// This flag may need to be replaced with -f[no]asan-use-after-return.
131static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
132       cl::desc("Check return-after-free"), cl::Hidden, cl::init(false));
133// This flag may need to be replaced with -f[no]asan-globals.
134static cl::opt<bool> ClGlobals("asan-globals",
135       cl::desc("Handle global objects"), cl::Hidden, cl::init(true));
136static cl::opt<bool> ClInitializers("asan-initialization-order",
137       cl::desc("Handle C++ initializer order"), cl::Hidden, cl::init(false));
138static cl::opt<bool> ClMemIntrin("asan-memintrin",
139       cl::desc("Handle memset/memcpy/memmove"), cl::Hidden, cl::init(true));
140static cl::opt<bool> ClRealignStack("asan-realign-stack",
141       cl::desc("Realign stack to 32"), cl::Hidden, cl::init(true));
142static cl::opt<std::string> ClBlacklistFile("asan-blacklist",
143       cl::desc("File containing the list of objects to ignore "
144                "during instrumentation"), cl::Hidden);
145
146// This is an experimental feature that will allow to choose between
147// instrumented and non-instrumented code at link-time.
148// If this option is on, just before instrumenting a function we create its
149// clone; if the function is not changed by asan the clone is deleted.
150// If we end up with a clone, we put the instrumented function into a section
151// called "ASAN" and the uninstrumented function into a section called "NOASAN".
152//
153// This is still a prototype, we need to figure out a way to keep two copies of
154// a function so that the linker can easily choose one of them.
155static cl::opt<bool> ClKeepUninstrumented("asan-keep-uninstrumented-functions",
156       cl::desc("Keep uninstrumented copies of functions"),
157       cl::Hidden, cl::init(false));
158
159// These flags allow to change the shadow mapping.
160// The shadow mapping looks like
161//    Shadow = (Mem >> scale) + (1 << offset_log)
162static cl::opt<int> ClMappingScale("asan-mapping-scale",
163       cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
164static cl::opt<int> ClMappingOffsetLog("asan-mapping-offset-log",
165       cl::desc("offset of asan shadow mapping"), cl::Hidden, cl::init(-1));
166static cl::opt<bool> ClShort64BitOffset("asan-short-64bit-mapping-offset",
167       cl::desc("Use short immediate constant as the mapping offset for 64bit"),
168       cl::Hidden, cl::init(true));
169
170// Optimization flags. Not user visible, used mostly for testing
171// and benchmarking the tool.
172static cl::opt<bool> ClOpt("asan-opt",
173       cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
174static cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
175       cl::desc("Instrument the same temp just once"), cl::Hidden,
176       cl::init(true));
177static cl::opt<bool> ClOptGlobals("asan-opt-globals",
178       cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
179
180static cl::opt<bool> ClCheckLifetime("asan-check-lifetime",
181       cl::desc("Use llvm.lifetime intrinsics to insert extra checks"),
182       cl::Hidden, cl::init(false));
183
184// Debug flags.
185static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
186                            cl::init(0));
187static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
188                                 cl::Hidden, cl::init(0));
189static cl::opt<std::string> ClDebugFunc("asan-debug-func",
190                                        cl::Hidden, cl::desc("Debug func"));
191static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
192                               cl::Hidden, cl::init(-1));
193static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
194                               cl::Hidden, cl::init(-1));
195
196namespace {
197/// A set of dynamically initialized globals extracted from metadata.
198class SetOfDynamicallyInitializedGlobals {
199 public:
200  void Init(Module& M) {
201    // Clang generates metadata identifying all dynamically initialized globals.
202    NamedMDNode *DynamicGlobals =
203        M.getNamedMetadata("llvm.asan.dynamically_initialized_globals");
204    if (!DynamicGlobals)
205      return;
206    for (int i = 0, n = DynamicGlobals->getNumOperands(); i < n; ++i) {
207      MDNode *MDN = DynamicGlobals->getOperand(i);
208      assert(MDN->getNumOperands() == 1);
209      Value *VG = MDN->getOperand(0);
210      // The optimizer may optimize away a global entirely, in which case we
211      // cannot instrument access to it.
212      if (!VG)
213        continue;
214      DynInitGlobals.insert(cast<GlobalVariable>(VG));
215    }
216  }
217  bool Contains(GlobalVariable *G) { return DynInitGlobals.count(G) != 0; }
218 private:
219  SmallSet<GlobalValue*, 32> DynInitGlobals;
220};
221
222/// This struct defines the shadow mapping using the rule:
223///   shadow = (mem >> Scale) ADD-or-OR Offset.
224struct ShadowMapping {
225  int Scale;
226  uint64_t Offset;
227  bool OrShadowOffset;
228};
229
230static ShadowMapping getShadowMapping(const Module &M, int LongSize,
231                                      bool ZeroBaseShadow) {
232  llvm::Triple TargetTriple(M.getTargetTriple());
233  bool IsAndroid = TargetTriple.getEnvironment() == llvm::Triple::Android;
234  bool IsMacOSX = TargetTriple.getOS() == llvm::Triple::MacOSX;
235  bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
236                 TargetTriple.getArch() == llvm::Triple::ppc64le;
237  bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
238  bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
239                  TargetTriple.getArch() == llvm::Triple::mipsel;
240
241  ShadowMapping Mapping;
242
243  // OR-ing shadow offset if more efficient (at least on x86),
244  // but on ppc64 we have to use add since the shadow offset is not neccesary
245  // 1/8-th of the address space.
246  Mapping.OrShadowOffset = !IsPPC64 && !ClShort64BitOffset;
247
248  Mapping.Offset = (IsAndroid || ZeroBaseShadow) ? 0 :
249      (LongSize == 32 ?
250       (IsMIPS32 ? kMIPS32_ShadowOffset32 : kDefaultShadowOffset32) :
251       IsPPC64 ? kPPC64_ShadowOffset64 : kDefaultShadowOffset64);
252  if (!ZeroBaseShadow && ClShort64BitOffset && IsX86_64 && !IsMacOSX) {
253    assert(LongSize == 64);
254    Mapping.Offset = kDefaultShort64bitShadowOffset;
255  }
256  if (!ZeroBaseShadow && ClMappingOffsetLog >= 0) {
257    // Zero offset log is the special case.
258    Mapping.Offset = (ClMappingOffsetLog == 0) ? 0 : 1ULL << ClMappingOffsetLog;
259  }
260
261  Mapping.Scale = kDefaultShadowScale;
262  if (ClMappingScale) {
263    Mapping.Scale = ClMappingScale;
264  }
265
266  return Mapping;
267}
268
269static size_t RedzoneSizeForScale(int MappingScale) {
270  // Redzone used for stack and globals is at least 32 bytes.
271  // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
272  return std::max(32U, 1U << MappingScale);
273}
274
275/// AddressSanitizer: instrument the code in module to find memory bugs.
276struct AddressSanitizer : public FunctionPass {
277  AddressSanitizer(bool CheckInitOrder = true,
278                   bool CheckUseAfterReturn = false,
279                   bool CheckLifetime = false,
280                   StringRef BlacklistFile = StringRef(),
281                   bool ZeroBaseShadow = false)
282      : FunctionPass(ID),
283        CheckInitOrder(CheckInitOrder || ClInitializers),
284        CheckUseAfterReturn(CheckUseAfterReturn || ClUseAfterReturn),
285        CheckLifetime(CheckLifetime || ClCheckLifetime),
286        BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
287                                            : BlacklistFile),
288        ZeroBaseShadow(ZeroBaseShadow) {}
289  virtual const char *getPassName() const {
290    return "AddressSanitizerFunctionPass";
291  }
292  void instrumentMop(Instruction *I);
293  void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
294                         Value *Addr, uint32_t TypeSize, bool IsWrite,
295                         Value *SizeArgument);
296  Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
297                           Value *ShadowValue, uint32_t TypeSize);
298  Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
299                                 bool IsWrite, size_t AccessSizeIndex,
300                                 Value *SizeArgument);
301  bool instrumentMemIntrinsic(MemIntrinsic *MI);
302  void instrumentMemIntrinsicParam(Instruction *OrigIns, Value *Addr,
303                                   Value *Size,
304                                   Instruction *InsertBefore, bool IsWrite);
305  Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
306  bool runOnFunction(Function &F);
307  bool maybeInsertAsanInitAtFunctionEntry(Function &F);
308  void emitShadowMapping(Module &M, IRBuilder<> &IRB) const;
309  virtual bool doInitialization(Module &M);
310  static char ID;  // Pass identification, replacement for typeid
311
312 private:
313  void initializeCallbacks(Module &M);
314
315  bool ShouldInstrumentGlobal(GlobalVariable *G);
316  bool LooksLikeCodeInBug11395(Instruction *I);
317  void FindDynamicInitializers(Module &M);
318
319  bool CheckInitOrder;
320  bool CheckUseAfterReturn;
321  bool CheckLifetime;
322  SmallString<64> BlacklistFile;
323  bool ZeroBaseShadow;
324
325  LLVMContext *C;
326  DataLayout *TD;
327  int LongSize;
328  Type *IntptrTy;
329  ShadowMapping Mapping;
330  Function *AsanCtorFunction;
331  Function *AsanInitFunction;
332  Function *AsanHandleNoReturnFunc;
333  OwningPtr<SpecialCaseList> BL;
334  // This array is indexed by AccessIsWrite and log2(AccessSize).
335  Function *AsanErrorCallback[2][kNumberOfAccessSizes];
336  // This array is indexed by AccessIsWrite.
337  Function *AsanErrorCallbackSized[2];
338  InlineAsm *EmptyAsm;
339  SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
340
341  friend struct FunctionStackPoisoner;
342};
343
344class AddressSanitizerModule : public ModulePass {
345 public:
346  AddressSanitizerModule(bool CheckInitOrder = true,
347                         StringRef BlacklistFile = StringRef(),
348                         bool ZeroBaseShadow = false)
349      : ModulePass(ID),
350        CheckInitOrder(CheckInitOrder || ClInitializers),
351        BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
352                                            : BlacklistFile),
353        ZeroBaseShadow(ZeroBaseShadow) {}
354  bool runOnModule(Module &M);
355  static char ID;  // Pass identification, replacement for typeid
356  virtual const char *getPassName() const {
357    return "AddressSanitizerModule";
358  }
359
360 private:
361  void initializeCallbacks(Module &M);
362
363  bool ShouldInstrumentGlobal(GlobalVariable *G);
364  void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
365  size_t RedzoneSize() const {
366    return RedzoneSizeForScale(Mapping.Scale);
367  }
368
369  bool CheckInitOrder;
370  SmallString<64> BlacklistFile;
371  bool ZeroBaseShadow;
372
373  OwningPtr<SpecialCaseList> BL;
374  SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
375  Type *IntptrTy;
376  LLVMContext *C;
377  DataLayout *TD;
378  ShadowMapping Mapping;
379  Function *AsanPoisonGlobals;
380  Function *AsanUnpoisonGlobals;
381  Function *AsanRegisterGlobals;
382  Function *AsanUnregisterGlobals;
383};
384
385// Stack poisoning does not play well with exception handling.
386// When an exception is thrown, we essentially bypass the code
387// that unpoisones the stack. This is why the run-time library has
388// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
389// stack in the interceptor. This however does not work inside the
390// actual function which catches the exception. Most likely because the
391// compiler hoists the load of the shadow value somewhere too high.
392// This causes asan to report a non-existing bug on 453.povray.
393// It sounds like an LLVM bug.
394struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
395  Function &F;
396  AddressSanitizer &ASan;
397  DIBuilder DIB;
398  LLVMContext *C;
399  Type *IntptrTy;
400  Type *IntptrPtrTy;
401  ShadowMapping Mapping;
402
403  SmallVector<AllocaInst*, 16> AllocaVec;
404  SmallVector<Instruction*, 8> RetVec;
405  uint64_t TotalStackSize;
406  unsigned StackAlignment;
407
408  Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
409           *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
410  Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
411
412  // Stores a place and arguments of poisoning/unpoisoning call for alloca.
413  struct AllocaPoisonCall {
414    IntrinsicInst *InsBefore;
415    uint64_t Size;
416    bool DoPoison;
417  };
418  SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
419
420  // Maps Value to an AllocaInst from which the Value is originated.
421  typedef DenseMap<Value*, AllocaInst*> AllocaForValueMapTy;
422  AllocaForValueMapTy AllocaForValue;
423
424  FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
425      : F(F), ASan(ASan), DIB(*F.getParent()), C(ASan.C),
426        IntptrTy(ASan.IntptrTy), IntptrPtrTy(PointerType::get(IntptrTy, 0)),
427        Mapping(ASan.Mapping),
428        TotalStackSize(0), StackAlignment(1 << Mapping.Scale) {}
429
430  bool runOnFunction() {
431    if (!ClStack) return false;
432    // Collect alloca, ret, lifetime instructions etc.
433    for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
434         DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
435      BasicBlock *BB = *DI;
436      visit(*BB);
437    }
438    if (AllocaVec.empty()) return false;
439
440    initializeCallbacks(*F.getParent());
441
442    poisonStack();
443
444    if (ClDebugStack) {
445      DEBUG(dbgs() << F);
446    }
447    return true;
448  }
449
450  // Finds all static Alloca instructions and puts
451  // poisoned red zones around all of them.
452  // Then unpoison everything back before the function returns.
453  void poisonStack();
454
455  // ----------------------- Visitors.
456  /// \brief Collect all Ret instructions.
457  void visitReturnInst(ReturnInst &RI) {
458    RetVec.push_back(&RI);
459  }
460
461  /// \brief Collect Alloca instructions we want (and can) handle.
462  void visitAllocaInst(AllocaInst &AI) {
463    if (!isInterestingAlloca(AI)) return;
464
465    StackAlignment = std::max(StackAlignment, AI.getAlignment());
466    AllocaVec.push_back(&AI);
467    uint64_t AlignedSize = getAlignedAllocaSize(&AI);
468    TotalStackSize += AlignedSize;
469  }
470
471  /// \brief Collect lifetime intrinsic calls to check for use-after-scope
472  /// errors.
473  void visitIntrinsicInst(IntrinsicInst &II) {
474    if (!ASan.CheckLifetime) return;
475    Intrinsic::ID ID = II.getIntrinsicID();
476    if (ID != Intrinsic::lifetime_start &&
477        ID != Intrinsic::lifetime_end)
478      return;
479    // Found lifetime intrinsic, add ASan instrumentation if necessary.
480    ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
481    // If size argument is undefined, don't do anything.
482    if (Size->isMinusOne()) return;
483    // Check that size doesn't saturate uint64_t and can
484    // be stored in IntptrTy.
485    const uint64_t SizeValue = Size->getValue().getLimitedValue();
486    if (SizeValue == ~0ULL ||
487        !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
488      return;
489    // Find alloca instruction that corresponds to llvm.lifetime argument.
490    AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
491    if (!AI) return;
492    bool DoPoison = (ID == Intrinsic::lifetime_end);
493    AllocaPoisonCall APC = {&II, SizeValue, DoPoison};
494    AllocaPoisonCallVec.push_back(APC);
495  }
496
497  // ---------------------- Helpers.
498  void initializeCallbacks(Module &M);
499
500  // Check if we want (and can) handle this alloca.
501  bool isInterestingAlloca(AllocaInst &AI) const {
502    return (!AI.isArrayAllocation() &&
503            AI.isStaticAlloca() &&
504            AI.getAlignment() <= RedzoneSize() &&
505            AI.getAllocatedType()->isSized());
506  }
507
508  size_t RedzoneSize() const {
509    return RedzoneSizeForScale(Mapping.Scale);
510  }
511  uint64_t getAllocaSizeInBytes(AllocaInst *AI) const {
512    Type *Ty = AI->getAllocatedType();
513    uint64_t SizeInBytes = ASan.TD->getTypeAllocSize(Ty);
514    return SizeInBytes;
515  }
516  uint64_t getAlignedSize(uint64_t SizeInBytes) const {
517    size_t RZ = RedzoneSize();
518    return ((SizeInBytes + RZ - 1) / RZ) * RZ;
519  }
520  uint64_t getAlignedAllocaSize(AllocaInst *AI) const {
521    uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
522    return getAlignedSize(SizeInBytes);
523  }
524  /// Finds alloca where the value comes from.
525  AllocaInst *findAllocaForValue(Value *V);
526  void poisonRedZones(const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> &IRB,
527                      Value *ShadowBase, bool DoPoison);
528  void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
529
530  void SetShadowToStackAfterReturnInlined(IRBuilder<> &IRB, Value *ShadowBase,
531                                          int Size);
532};
533
534}  // namespace
535
536char AddressSanitizer::ID = 0;
537INITIALIZE_PASS(AddressSanitizer, "asan",
538    "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
539    false, false)
540FunctionPass *llvm::createAddressSanitizerFunctionPass(
541    bool CheckInitOrder, bool CheckUseAfterReturn, bool CheckLifetime,
542    StringRef BlacklistFile, bool ZeroBaseShadow) {
543  return new AddressSanitizer(CheckInitOrder, CheckUseAfterReturn,
544                              CheckLifetime, BlacklistFile, ZeroBaseShadow);
545}
546
547char AddressSanitizerModule::ID = 0;
548INITIALIZE_PASS(AddressSanitizerModule, "asan-module",
549    "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
550    "ModulePass", false, false)
551ModulePass *llvm::createAddressSanitizerModulePass(
552    bool CheckInitOrder, StringRef BlacklistFile, bool ZeroBaseShadow) {
553  return new AddressSanitizerModule(CheckInitOrder, BlacklistFile,
554                                    ZeroBaseShadow);
555}
556
557static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
558  size_t Res = countTrailingZeros(TypeSize / 8);
559  assert(Res < kNumberOfAccessSizes);
560  return Res;
561}
562
563// \brief Create a constant for Str so that we can pass it to the run-time lib.
564static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str) {
565  Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
566  GlobalVariable *GV = new GlobalVariable(M, StrConst->getType(), true,
567                            GlobalValue::InternalLinkage, StrConst,
568                            kAsanGenPrefix);
569  GV->setUnnamedAddr(true);  // Ok to merge these.
570  GV->setAlignment(1);  // Strings may not be merged w/o setting align 1.
571  return GV;
572}
573
574static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
575  return G->getName().find(kAsanGenPrefix) == 0;
576}
577
578Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
579  // Shadow >> scale
580  Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
581  if (Mapping.Offset == 0)
582    return Shadow;
583  // (Shadow >> scale) | offset
584  if (Mapping.OrShadowOffset)
585    return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
586  else
587    return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
588}
589
590void AddressSanitizer::instrumentMemIntrinsicParam(
591    Instruction *OrigIns,
592    Value *Addr, Value *Size, Instruction *InsertBefore, bool IsWrite) {
593  IRBuilder<> IRB(InsertBefore);
594  if (Size->getType() != IntptrTy)
595    Size = IRB.CreateIntCast(Size, IntptrTy, false);
596  // Check the first byte.
597  instrumentAddress(OrigIns, InsertBefore, Addr, 8, IsWrite, Size);
598  // Check the last byte.
599  IRB.SetInsertPoint(InsertBefore);
600  Value *SizeMinusOne = IRB.CreateSub(Size, ConstantInt::get(IntptrTy, 1));
601  Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
602  Value *AddrLast = IRB.CreateAdd(AddrLong, SizeMinusOne);
603  instrumentAddress(OrigIns, InsertBefore, AddrLast, 8, IsWrite, Size);
604}
605
606// Instrument memset/memmove/memcpy
607bool AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
608  Value *Dst = MI->getDest();
609  MemTransferInst *MemTran = dyn_cast<MemTransferInst>(MI);
610  Value *Src = MemTran ? MemTran->getSource() : 0;
611  Value *Length = MI->getLength();
612
613  Constant *ConstLength = dyn_cast<Constant>(Length);
614  Instruction *InsertBefore = MI;
615  if (ConstLength) {
616    if (ConstLength->isNullValue()) return false;
617  } else {
618    // The size is not a constant so it could be zero -- check at run-time.
619    IRBuilder<> IRB(InsertBefore);
620
621    Value *Cmp = IRB.CreateICmpNE(Length,
622                                  Constant::getNullValue(Length->getType()));
623    InsertBefore = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
624  }
625
626  instrumentMemIntrinsicParam(MI, Dst, Length, InsertBefore, true);
627  if (Src)
628    instrumentMemIntrinsicParam(MI, Src, Length, InsertBefore, false);
629  return true;
630}
631
632// If I is an interesting memory access, return the PointerOperand
633// and set IsWrite. Otherwise return NULL.
634static Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite) {
635  if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
636    if (!ClInstrumentReads) return NULL;
637    *IsWrite = false;
638    return LI->getPointerOperand();
639  }
640  if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
641    if (!ClInstrumentWrites) return NULL;
642    *IsWrite = true;
643    return SI->getPointerOperand();
644  }
645  if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
646    if (!ClInstrumentAtomics) return NULL;
647    *IsWrite = true;
648    return RMW->getPointerOperand();
649  }
650  if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
651    if (!ClInstrumentAtomics) return NULL;
652    *IsWrite = true;
653    return XCHG->getPointerOperand();
654  }
655  return NULL;
656}
657
658void AddressSanitizer::instrumentMop(Instruction *I) {
659  bool IsWrite = false;
660  Value *Addr = isInterestingMemoryAccess(I, &IsWrite);
661  assert(Addr);
662  if (ClOpt && ClOptGlobals) {
663    if (GlobalVariable *G = dyn_cast<GlobalVariable>(Addr)) {
664      // If initialization order checking is disabled, a simple access to a
665      // dynamically initialized global is always valid.
666      if (!CheckInitOrder)
667        return;
668      // If a global variable does not have dynamic initialization we don't
669      // have to instrument it.  However, if a global does not have initailizer
670      // at all, we assume it has dynamic initializer (in other TU).
671      if (G->hasInitializer() && !DynamicallyInitializedGlobals.Contains(G))
672        return;
673    }
674  }
675
676  Type *OrigPtrTy = Addr->getType();
677  Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
678
679  assert(OrigTy->isSized());
680  uint32_t TypeSize = TD->getTypeStoreSizeInBits(OrigTy);
681
682  assert((TypeSize % 8) == 0);
683
684  // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check.
685  if (TypeSize == 8  || TypeSize == 16 ||
686      TypeSize == 32 || TypeSize == 64 || TypeSize == 128)
687    return instrumentAddress(I, I, Addr, TypeSize, IsWrite, 0);
688  // Instrument unusual size (but still multiple of 8).
689  // We can not do it with a single check, so we do 1-byte check for the first
690  // and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
691  // to report the actual access size.
692  IRBuilder<> IRB(I);
693  Value *LastByte =  IRB.CreateIntToPtr(
694      IRB.CreateAdd(IRB.CreatePointerCast(Addr, IntptrTy),
695                    ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
696      OrigPtrTy);
697  Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
698  instrumentAddress(I, I, Addr, 8, IsWrite, Size);
699  instrumentAddress(I, I, LastByte, 8, IsWrite, Size);
700}
701
702// Validate the result of Module::getOrInsertFunction called for an interface
703// function of AddressSanitizer. If the instrumented module defines a function
704// with the same name, their prototypes must match, otherwise
705// getOrInsertFunction returns a bitcast.
706static Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
707  if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
708  FuncOrBitcast->dump();
709  report_fatal_error("trying to redefine an AddressSanitizer "
710                     "interface function");
711}
712
713Instruction *AddressSanitizer::generateCrashCode(
714    Instruction *InsertBefore, Value *Addr,
715    bool IsWrite, size_t AccessSizeIndex, Value *SizeArgument) {
716  IRBuilder<> IRB(InsertBefore);
717  CallInst *Call = SizeArgument
718    ? IRB.CreateCall2(AsanErrorCallbackSized[IsWrite], Addr, SizeArgument)
719    : IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex], Addr);
720
721  // We don't do Call->setDoesNotReturn() because the BB already has
722  // UnreachableInst at the end.
723  // This EmptyAsm is required to avoid callback merge.
724  IRB.CreateCall(EmptyAsm);
725  return Call;
726}
727
728Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
729                                            Value *ShadowValue,
730                                            uint32_t TypeSize) {
731  size_t Granularity = 1 << Mapping.Scale;
732  // Addr & (Granularity - 1)
733  Value *LastAccessedByte = IRB.CreateAnd(
734      AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
735  // (Addr & (Granularity - 1)) + size - 1
736  if (TypeSize / 8 > 1)
737    LastAccessedByte = IRB.CreateAdd(
738        LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
739  // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
740  LastAccessedByte = IRB.CreateIntCast(
741      LastAccessedByte, ShadowValue->getType(), false);
742  // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
743  return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
744}
745
746void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
747                                         Instruction *InsertBefore,
748                                         Value *Addr, uint32_t TypeSize,
749                                         bool IsWrite, Value *SizeArgument) {
750  IRBuilder<> IRB(InsertBefore);
751  Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
752
753  Type *ShadowTy  = IntegerType::get(
754      *C, std::max(8U, TypeSize >> Mapping.Scale));
755  Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
756  Value *ShadowPtr = memToShadow(AddrLong, IRB);
757  Value *CmpVal = Constant::getNullValue(ShadowTy);
758  Value *ShadowValue = IRB.CreateLoad(
759      IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
760
761  Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
762  size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
763  size_t Granularity = 1 << Mapping.Scale;
764  TerminatorInst *CrashTerm = 0;
765
766  if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
767    TerminatorInst *CheckTerm =
768        SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
769    assert(dyn_cast<BranchInst>(CheckTerm)->isUnconditional());
770    BasicBlock *NextBB = CheckTerm->getSuccessor(0);
771    IRB.SetInsertPoint(CheckTerm);
772    Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
773    BasicBlock *CrashBlock =
774        BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
775    CrashTerm = new UnreachableInst(*C, CrashBlock);
776    BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
777    ReplaceInstWithInst(CheckTerm, NewTerm);
778  } else {
779    CrashTerm = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), true);
780  }
781
782  Instruction *Crash = generateCrashCode(
783      CrashTerm, AddrLong, IsWrite, AccessSizeIndex, SizeArgument);
784  Crash->setDebugLoc(OrigIns->getDebugLoc());
785}
786
787void AddressSanitizerModule::createInitializerPoisonCalls(
788    Module &M, GlobalValue *ModuleName) {
789  // We do all of our poisoning and unpoisoning within _GLOBAL__I_a.
790  Function *GlobalInit = M.getFunction("_GLOBAL__I_a");
791  // If that function is not present, this TU contains no globals, or they have
792  // all been optimized away
793  if (!GlobalInit)
794    return;
795
796  // Set up the arguments to our poison/unpoison functions.
797  IRBuilder<> IRB(GlobalInit->begin()->getFirstInsertionPt());
798
799  // Add a call to poison all external globals before the given function starts.
800  Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
801  IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
802
803  // Add calls to unpoison all globals before each return instruction.
804  for (Function::iterator I = GlobalInit->begin(), E = GlobalInit->end();
805      I != E; ++I) {
806    if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator())) {
807      CallInst::Create(AsanUnpoisonGlobals, "", RI);
808    }
809  }
810}
811
812bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
813  Type *Ty = cast<PointerType>(G->getType())->getElementType();
814  DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
815
816  if (BL->isIn(*G)) return false;
817  if (!Ty->isSized()) return false;
818  if (!G->hasInitializer()) return false;
819  if (GlobalWasGeneratedByAsan(G)) return false;  // Our own global.
820  // Touch only those globals that will not be defined in other modules.
821  // Don't handle ODR type linkages since other modules may be built w/o asan.
822  if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
823      G->getLinkage() != GlobalVariable::PrivateLinkage &&
824      G->getLinkage() != GlobalVariable::InternalLinkage)
825    return false;
826  // Two problems with thread-locals:
827  //   - The address of the main thread's copy can't be computed at link-time.
828  //   - Need to poison all copies, not just the main thread's one.
829  if (G->isThreadLocal())
830    return false;
831  // For now, just ignore this Alloca if the alignment is large.
832  if (G->getAlignment() > RedzoneSize()) return false;
833
834  // Ignore all the globals with the names starting with "\01L_OBJC_".
835  // Many of those are put into the .cstring section. The linker compresses
836  // that section by removing the spare \0s after the string terminator, so
837  // our redzones get broken.
838  if ((G->getName().find("\01L_OBJC_") == 0) ||
839      (G->getName().find("\01l_OBJC_") == 0)) {
840    DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G);
841    return false;
842  }
843
844  if (G->hasSection()) {
845    StringRef Section(G->getSection());
846    // Ignore the globals from the __OBJC section. The ObjC runtime assumes
847    // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
848    // them.
849    if ((Section.find("__OBJC,") == 0) ||
850        (Section.find("__DATA, __objc_") == 0)) {
851      DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G);
852      return false;
853    }
854    // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
855    // Constant CFString instances are compiled in the following way:
856    //  -- the string buffer is emitted into
857    //     __TEXT,__cstring,cstring_literals
858    //  -- the constant NSConstantString structure referencing that buffer
859    //     is placed into __DATA,__cfstring
860    // Therefore there's no point in placing redzones into __DATA,__cfstring.
861    // Moreover, it causes the linker to crash on OS X 10.7
862    if (Section.find("__DATA,__cfstring") == 0) {
863      DEBUG(dbgs() << "Ignoring CFString: " << *G);
864      return false;
865    }
866  }
867
868  return true;
869}
870
871void AddressSanitizerModule::initializeCallbacks(Module &M) {
872  IRBuilder<> IRB(*C);
873  // Declare our poisoning and unpoisoning functions.
874  AsanPoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
875      kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, NULL));
876  AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
877  AsanUnpoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
878      kAsanUnpoisonGlobalsName, IRB.getVoidTy(), NULL));
879  AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
880  // Declare functions that register/unregister globals.
881  AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
882      kAsanRegisterGlobalsName, IRB.getVoidTy(),
883      IntptrTy, IntptrTy, NULL));
884  AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
885  AsanUnregisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
886      kAsanUnregisterGlobalsName,
887      IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
888  AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
889}
890
891// This function replaces all global variables with new variables that have
892// trailing redzones. It also creates a function that poisons
893// redzones and inserts this function into llvm.global_ctors.
894bool AddressSanitizerModule::runOnModule(Module &M) {
895  if (!ClGlobals) return false;
896  TD = getAnalysisIfAvailable<DataLayout>();
897  if (!TD)
898    return false;
899  BL.reset(SpecialCaseList::createOrDie(BlacklistFile));
900  if (BL->isIn(M)) return false;
901  C = &(M.getContext());
902  int LongSize = TD->getPointerSizeInBits();
903  IntptrTy = Type::getIntNTy(*C, LongSize);
904  Mapping = getShadowMapping(M, LongSize, ZeroBaseShadow);
905  initializeCallbacks(M);
906  DynamicallyInitializedGlobals.Init(M);
907
908  SmallVector<GlobalVariable *, 16> GlobalsToChange;
909
910  for (Module::GlobalListType::iterator G = M.global_begin(),
911       E = M.global_end(); G != E; ++G) {
912    if (ShouldInstrumentGlobal(G))
913      GlobalsToChange.push_back(G);
914  }
915
916  size_t n = GlobalsToChange.size();
917  if (n == 0) return false;
918
919  // A global is described by a structure
920  //   size_t beg;
921  //   size_t size;
922  //   size_t size_with_redzone;
923  //   const char *name;
924  //   const char *module_name;
925  //   size_t has_dynamic_init;
926  // We initialize an array of such structures and pass it to a run-time call.
927  StructType *GlobalStructTy = StructType::get(IntptrTy, IntptrTy,
928                                               IntptrTy, IntptrTy,
929                                               IntptrTy, IntptrTy, NULL);
930  SmallVector<Constant *, 16> Initializers(n);
931
932  Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
933  assert(CtorFunc);
934  IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
935
936  bool HasDynamicallyInitializedGlobals = false;
937
938  GlobalVariable *ModuleName = createPrivateGlobalForString(
939      M, M.getModuleIdentifier());
940  // We shouldn't merge same module names, as this string serves as unique
941  // module ID in runtime.
942  ModuleName->setUnnamedAddr(false);
943
944  for (size_t i = 0; i < n; i++) {
945    static const uint64_t kMaxGlobalRedzone = 1 << 18;
946    GlobalVariable *G = GlobalsToChange[i];
947    PointerType *PtrTy = cast<PointerType>(G->getType());
948    Type *Ty = PtrTy->getElementType();
949    uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
950    uint64_t MinRZ = RedzoneSize();
951    // MinRZ <= RZ <= kMaxGlobalRedzone
952    // and trying to make RZ to be ~ 1/4 of SizeInBytes.
953    uint64_t RZ = std::max(MinRZ,
954                         std::min(kMaxGlobalRedzone,
955                                  (SizeInBytes / MinRZ / 4) * MinRZ));
956    uint64_t RightRedzoneSize = RZ;
957    // Round up to MinRZ
958    if (SizeInBytes % MinRZ)
959      RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
960    assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
961    Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
962    // Determine whether this global should be poisoned in initialization.
963    bool GlobalHasDynamicInitializer =
964        DynamicallyInitializedGlobals.Contains(G);
965    // Don't check initialization order if this global is blacklisted.
966    GlobalHasDynamicInitializer &= !BL->isIn(*G, "init");
967
968    StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
969    Constant *NewInitializer = ConstantStruct::get(
970        NewTy, G->getInitializer(),
971        Constant::getNullValue(RightRedZoneTy), NULL);
972
973    GlobalVariable *Name = createPrivateGlobalForString(M, G->getName());
974
975    // Create a new global variable with enough space for a redzone.
976    GlobalValue::LinkageTypes Linkage = G->getLinkage();
977    if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
978      Linkage = GlobalValue::InternalLinkage;
979    GlobalVariable *NewGlobal = new GlobalVariable(
980        M, NewTy, G->isConstant(), Linkage,
981        NewInitializer, "", G, G->getThreadLocalMode());
982    NewGlobal->copyAttributesFrom(G);
983    NewGlobal->setAlignment(MinRZ);
984
985    Value *Indices2[2];
986    Indices2[0] = IRB.getInt32(0);
987    Indices2[1] = IRB.getInt32(0);
988
989    G->replaceAllUsesWith(
990        ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
991    NewGlobal->takeName(G);
992    G->eraseFromParent();
993
994    Initializers[i] = ConstantStruct::get(
995        GlobalStructTy,
996        ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
997        ConstantInt::get(IntptrTy, SizeInBytes),
998        ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
999        ConstantExpr::getPointerCast(Name, IntptrTy),
1000        ConstantExpr::getPointerCast(ModuleName, IntptrTy),
1001        ConstantInt::get(IntptrTy, GlobalHasDynamicInitializer),
1002        NULL);
1003
1004    // Populate the first and last globals declared in this TU.
1005    if (CheckInitOrder && GlobalHasDynamicInitializer)
1006      HasDynamicallyInitializedGlobals = true;
1007
1008    DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
1009  }
1010
1011  ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
1012  GlobalVariable *AllGlobals = new GlobalVariable(
1013      M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
1014      ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
1015
1016  // Create calls for poisoning before initializers run and unpoisoning after.
1017  if (CheckInitOrder && HasDynamicallyInitializedGlobals)
1018    createInitializerPoisonCalls(M, ModuleName);
1019  IRB.CreateCall2(AsanRegisterGlobals,
1020                  IRB.CreatePointerCast(AllGlobals, IntptrTy),
1021                  ConstantInt::get(IntptrTy, n));
1022
1023  // We also need to unregister globals at the end, e.g. when a shared library
1024  // gets closed.
1025  Function *AsanDtorFunction = Function::Create(
1026      FunctionType::get(Type::getVoidTy(*C), false),
1027      GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
1028  BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
1029  IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
1030  IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
1031                       IRB.CreatePointerCast(AllGlobals, IntptrTy),
1032                       ConstantInt::get(IntptrTy, n));
1033  appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndCtorPriority);
1034
1035  DEBUG(dbgs() << M);
1036  return true;
1037}
1038
1039void AddressSanitizer::initializeCallbacks(Module &M) {
1040  IRBuilder<> IRB(*C);
1041  // Create __asan_report* callbacks.
1042  for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
1043    for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
1044         AccessSizeIndex++) {
1045      // IsWrite and TypeSize are encoded in the function name.
1046      std::string FunctionName = std::string(kAsanReportErrorTemplate) +
1047          (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
1048      // If we are merging crash callbacks, they have two parameters.
1049      AsanErrorCallback[AccessIsWrite][AccessSizeIndex] =
1050          checkInterfaceFunction(M.getOrInsertFunction(
1051              FunctionName, IRB.getVoidTy(), IntptrTy, NULL));
1052    }
1053  }
1054  AsanErrorCallbackSized[0] = checkInterfaceFunction(M.getOrInsertFunction(
1055              kAsanReportLoadN, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1056  AsanErrorCallbackSized[1] = checkInterfaceFunction(M.getOrInsertFunction(
1057              kAsanReportStoreN, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1058
1059  AsanHandleNoReturnFunc = checkInterfaceFunction(M.getOrInsertFunction(
1060      kAsanHandleNoReturnName, IRB.getVoidTy(), NULL));
1061  // We insert an empty inline asm after __asan_report* to avoid callback merge.
1062  EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
1063                            StringRef(""), StringRef(""),
1064                            /*hasSideEffects=*/true);
1065}
1066
1067void AddressSanitizer::emitShadowMapping(Module &M, IRBuilder<> &IRB) const {
1068  // Tell the values of mapping offset and scale to the run-time.
1069  GlobalValue *asan_mapping_offset =
1070      new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
1071                     ConstantInt::get(IntptrTy, Mapping.Offset),
1072                     kAsanMappingOffsetName);
1073  // Read the global, otherwise it may be optimized away.
1074  IRB.CreateLoad(asan_mapping_offset, true);
1075
1076  GlobalValue *asan_mapping_scale =
1077      new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
1078                         ConstantInt::get(IntptrTy, Mapping.Scale),
1079                         kAsanMappingScaleName);
1080  // Read the global, otherwise it may be optimized away.
1081  IRB.CreateLoad(asan_mapping_scale, true);
1082}
1083
1084// virtual
1085bool AddressSanitizer::doInitialization(Module &M) {
1086  // Initialize the private fields. No one has accessed them before.
1087  TD = getAnalysisIfAvailable<DataLayout>();
1088
1089  if (!TD)
1090    return false;
1091  BL.reset(SpecialCaseList::createOrDie(BlacklistFile));
1092  DynamicallyInitializedGlobals.Init(M);
1093
1094  C = &(M.getContext());
1095  LongSize = TD->getPointerSizeInBits();
1096  IntptrTy = Type::getIntNTy(*C, LongSize);
1097
1098  AsanCtorFunction = Function::Create(
1099      FunctionType::get(Type::getVoidTy(*C), false),
1100      GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
1101  BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
1102  // call __asan_init in the module ctor.
1103  IRBuilder<> IRB(ReturnInst::Create(*C, AsanCtorBB));
1104  AsanInitFunction = checkInterfaceFunction(
1105      M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
1106  AsanInitFunction->setLinkage(Function::ExternalLinkage);
1107  IRB.CreateCall(AsanInitFunction);
1108
1109  Mapping = getShadowMapping(M, LongSize, ZeroBaseShadow);
1110  emitShadowMapping(M, IRB);
1111
1112  appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndCtorPriority);
1113  return true;
1114}
1115
1116bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1117  // For each NSObject descendant having a +load method, this method is invoked
1118  // by the ObjC runtime before any of the static constructors is called.
1119  // Therefore we need to instrument such methods with a call to __asan_init
1120  // at the beginning in order to initialize our runtime before any access to
1121  // the shadow memory.
1122  // We cannot just ignore these methods, because they may call other
1123  // instrumented functions.
1124  if (F.getName().find(" load]") != std::string::npos) {
1125    IRBuilder<> IRB(F.begin()->begin());
1126    IRB.CreateCall(AsanInitFunction);
1127    return true;
1128  }
1129  return false;
1130}
1131
1132bool AddressSanitizer::runOnFunction(Function &F) {
1133  if (BL->isIn(F)) return false;
1134  if (&F == AsanCtorFunction) return false;
1135  if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
1136  DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
1137  initializeCallbacks(*F.getParent());
1138
1139  // If needed, insert __asan_init before checking for SanitizeAddress attr.
1140  maybeInsertAsanInitAtFunctionEntry(F);
1141
1142  if (!F.hasFnAttribute(Attribute::SanitizeAddress))
1143    return false;
1144
1145  if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
1146    return false;
1147
1148  // We want to instrument every address only once per basic block (unless there
1149  // are calls between uses).
1150  SmallSet<Value*, 16> TempsToInstrument;
1151  SmallVector<Instruction*, 16> ToInstrument;
1152  SmallVector<Instruction*, 8> NoReturnCalls;
1153  int NumAllocas = 0;
1154  bool IsWrite;
1155
1156  // Fill the set of memory operations to instrument.
1157  for (Function::iterator FI = F.begin(), FE = F.end();
1158       FI != FE; ++FI) {
1159    TempsToInstrument.clear();
1160    int NumInsnsPerBB = 0;
1161    for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
1162         BI != BE; ++BI) {
1163      if (LooksLikeCodeInBug11395(BI)) return false;
1164      if (Value *Addr = isInterestingMemoryAccess(BI, &IsWrite)) {
1165        if (ClOpt && ClOptSameTemp) {
1166          if (!TempsToInstrument.insert(Addr))
1167            continue;  // We've seen this temp in the current BB.
1168        }
1169      } else if (isa<MemIntrinsic>(BI) && ClMemIntrin) {
1170        // ok, take it.
1171      } else {
1172        if (isa<AllocaInst>(BI))
1173          NumAllocas++;
1174        CallSite CS(BI);
1175        if (CS) {
1176          // A call inside BB.
1177          TempsToInstrument.clear();
1178          if (CS.doesNotReturn())
1179            NoReturnCalls.push_back(CS.getInstruction());
1180        }
1181        continue;
1182      }
1183      ToInstrument.push_back(BI);
1184      NumInsnsPerBB++;
1185      if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
1186        break;
1187    }
1188  }
1189
1190  Function *UninstrumentedDuplicate = 0;
1191  bool LikelyToInstrument =
1192      !NoReturnCalls.empty() || !ToInstrument.empty() || (NumAllocas > 0);
1193  if (ClKeepUninstrumented && LikelyToInstrument) {
1194    ValueToValueMapTy VMap;
1195    UninstrumentedDuplicate = CloneFunction(&F, VMap, false);
1196    UninstrumentedDuplicate->removeFnAttr(Attribute::SanitizeAddress);
1197    UninstrumentedDuplicate->setName("NOASAN_" + F.getName());
1198    F.getParent()->getFunctionList().push_back(UninstrumentedDuplicate);
1199  }
1200
1201  // Instrument.
1202  int NumInstrumented = 0;
1203  for (size_t i = 0, n = ToInstrument.size(); i != n; i++) {
1204    Instruction *Inst = ToInstrument[i];
1205    if (ClDebugMin < 0 || ClDebugMax < 0 ||
1206        (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
1207      if (isInterestingMemoryAccess(Inst, &IsWrite))
1208        instrumentMop(Inst);
1209      else
1210        instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
1211    }
1212    NumInstrumented++;
1213  }
1214
1215  FunctionStackPoisoner FSP(F, *this);
1216  bool ChangedStack = FSP.runOnFunction();
1217
1218  // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1219  // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
1220  for (size_t i = 0, n = NoReturnCalls.size(); i != n; i++) {
1221    Instruction *CI = NoReturnCalls[i];
1222    IRBuilder<> IRB(CI);
1223    IRB.CreateCall(AsanHandleNoReturnFunc);
1224  }
1225
1226  bool res = NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
1227  DEBUG(dbgs() << "ASAN done instrumenting: " << res << " " << F << "\n");
1228
1229  if (ClKeepUninstrumented) {
1230    if (!res) {
1231      // No instrumentation is done, no need for the duplicate.
1232      if (UninstrumentedDuplicate)
1233        UninstrumentedDuplicate->eraseFromParent();
1234    } else {
1235      // The function was instrumented. We must have the duplicate.
1236      assert(UninstrumentedDuplicate);
1237      UninstrumentedDuplicate->setSection("NOASAN");
1238      assert(!F.hasSection());
1239      F.setSection("ASAN");
1240    }
1241  }
1242
1243  return res;
1244}
1245
1246static uint64_t ValueForPoison(uint64_t PoisonByte, size_t ShadowRedzoneSize) {
1247  if (ShadowRedzoneSize == 1) return PoisonByte;
1248  if (ShadowRedzoneSize == 2) return (PoisonByte << 8) + PoisonByte;
1249  if (ShadowRedzoneSize == 4)
1250    return (PoisonByte << 24) + (PoisonByte << 16) +
1251        (PoisonByte << 8) + (PoisonByte);
1252  llvm_unreachable("ShadowRedzoneSize is either 1, 2 or 4");
1253}
1254
1255static void PoisonShadowPartialRightRedzone(uint8_t *Shadow,
1256                                            size_t Size,
1257                                            size_t RZSize,
1258                                            size_t ShadowGranularity,
1259                                            uint8_t Magic) {
1260  for (size_t i = 0; i < RZSize;
1261       i+= ShadowGranularity, Shadow++) {
1262    if (i + ShadowGranularity <= Size) {
1263      *Shadow = 0;  // fully addressable
1264    } else if (i >= Size) {
1265      *Shadow = Magic;  // unaddressable
1266    } else {
1267      *Shadow = Size - i;  // first Size-i bytes are addressable
1268    }
1269  }
1270}
1271
1272// Workaround for bug 11395: we don't want to instrument stack in functions
1273// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1274// FIXME: remove once the bug 11395 is fixed.
1275bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1276  if (LongSize != 32) return false;
1277  CallInst *CI = dyn_cast<CallInst>(I);
1278  if (!CI || !CI->isInlineAsm()) return false;
1279  if (CI->getNumArgOperands() <= 5) return false;
1280  // We have inline assembly with quite a few arguments.
1281  return true;
1282}
1283
1284void FunctionStackPoisoner::initializeCallbacks(Module &M) {
1285  IRBuilder<> IRB(*C);
1286  for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
1287    std::string Suffix = itostr(i);
1288    AsanStackMallocFunc[i] = checkInterfaceFunction(
1289        M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
1290                              IntptrTy, IntptrTy, NULL));
1291    AsanStackFreeFunc[i] = checkInterfaceFunction(M.getOrInsertFunction(
1292        kAsanStackFreeNameTemplate + Suffix, IRB.getVoidTy(), IntptrTy,
1293        IntptrTy, IntptrTy, NULL));
1294  }
1295  AsanPoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1296      kAsanPoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1297  AsanUnpoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1298      kAsanUnpoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1299}
1300
1301void FunctionStackPoisoner::poisonRedZones(
1302  const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> &IRB, Value *ShadowBase,
1303  bool DoPoison) {
1304  size_t ShadowRZSize = RedzoneSize() >> Mapping.Scale;
1305  assert(ShadowRZSize >= 1 && ShadowRZSize <= 4);
1306  Type *RZTy = Type::getIntNTy(*C, ShadowRZSize * 8);
1307  Type *RZPtrTy = PointerType::get(RZTy, 0);
1308
1309  Value *PoisonLeft  = ConstantInt::get(RZTy,
1310    ValueForPoison(DoPoison ? kAsanStackLeftRedzoneMagic : 0LL, ShadowRZSize));
1311  Value *PoisonMid   = ConstantInt::get(RZTy,
1312    ValueForPoison(DoPoison ? kAsanStackMidRedzoneMagic : 0LL, ShadowRZSize));
1313  Value *PoisonRight = ConstantInt::get(RZTy,
1314    ValueForPoison(DoPoison ? kAsanStackRightRedzoneMagic : 0LL, ShadowRZSize));
1315
1316  // poison the first red zone.
1317  IRB.CreateStore(PoisonLeft, IRB.CreateIntToPtr(ShadowBase, RZPtrTy));
1318
1319  // poison all other red zones.
1320  uint64_t Pos = RedzoneSize();
1321  for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1322    AllocaInst *AI = AllocaVec[i];
1323    uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1324    uint64_t AlignedSize = getAlignedAllocaSize(AI);
1325    assert(AlignedSize - SizeInBytes < RedzoneSize());
1326    Value *Ptr = NULL;
1327
1328    Pos += AlignedSize;
1329
1330    assert(ShadowBase->getType() == IntptrTy);
1331    if (SizeInBytes < AlignedSize) {
1332      // Poison the partial redzone at right
1333      Ptr = IRB.CreateAdd(
1334          ShadowBase, ConstantInt::get(IntptrTy,
1335                                       (Pos >> Mapping.Scale) - ShadowRZSize));
1336      size_t AddressableBytes = RedzoneSize() - (AlignedSize - SizeInBytes);
1337      uint32_t Poison = 0;
1338      if (DoPoison) {
1339        PoisonShadowPartialRightRedzone((uint8_t*)&Poison, AddressableBytes,
1340                                        RedzoneSize(),
1341                                        1ULL << Mapping.Scale,
1342                                        kAsanStackPartialRedzoneMagic);
1343        Poison =
1344            ASan.TD->isLittleEndian()
1345                ? support::endian::byte_swap<uint32_t, support::little>(Poison)
1346                : support::endian::byte_swap<uint32_t, support::big>(Poison);
1347      }
1348      Value *PartialPoison = ConstantInt::get(RZTy, Poison);
1349      IRB.CreateStore(PartialPoison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
1350    }
1351
1352    // Poison the full redzone at right.
1353    Ptr = IRB.CreateAdd(ShadowBase,
1354                        ConstantInt::get(IntptrTy, Pos >> Mapping.Scale));
1355    bool LastAlloca = (i == AllocaVec.size() - 1);
1356    Value *Poison = LastAlloca ? PoisonRight : PoisonMid;
1357    IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
1358
1359    Pos += RedzoneSize();
1360  }
1361}
1362
1363// Fake stack allocator (asan_fake_stack.h) has 11 size classes
1364// for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
1365static int StackMallocSizeClass(uint64_t LocalStackSize) {
1366  assert(LocalStackSize <= kMaxStackMallocSize);
1367  uint64_t MaxSize = kMinStackMallocSize;
1368  for (int i = 0; ; i++, MaxSize *= 2)
1369    if (LocalStackSize <= MaxSize)
1370      return i;
1371  llvm_unreachable("impossible LocalStackSize");
1372}
1373
1374// Set Size bytes starting from ShadowBase to kAsanStackAfterReturnMagic.
1375// We can not use MemSet intrinsic because it may end up calling the actual
1376// memset. Size is a multiple of 8.
1377// Currently this generates 8-byte stores on x86_64; it may be better to
1378// generate wider stores.
1379void FunctionStackPoisoner::SetShadowToStackAfterReturnInlined(
1380    IRBuilder<> &IRB, Value *ShadowBase, int Size) {
1381  assert(!(Size % 8));
1382  assert(kAsanStackAfterReturnMagic == 0xf5);
1383  for (int i = 0; i < Size; i += 8) {
1384    Value *p = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1385    IRB.CreateStore(ConstantInt::get(IRB.getInt64Ty(), 0xf5f5f5f5f5f5f5f5ULL),
1386                    IRB.CreateIntToPtr(p, IRB.getInt64Ty()->getPointerTo()));
1387  }
1388}
1389
1390void FunctionStackPoisoner::poisonStack() {
1391  uint64_t LocalStackSize = TotalStackSize +
1392                            (AllocaVec.size() + 1) * RedzoneSize();
1393
1394  bool DoStackMalloc = ASan.CheckUseAfterReturn
1395      && LocalStackSize <= kMaxStackMallocSize;
1396  int StackMallocIdx = -1;
1397
1398  assert(AllocaVec.size() > 0);
1399  Instruction *InsBefore = AllocaVec[0];
1400  IRBuilder<> IRB(InsBefore);
1401
1402
1403  Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
1404  AllocaInst *MyAlloca =
1405      new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
1406  if (ClRealignStack && StackAlignment < RedzoneSize())
1407    StackAlignment = RedzoneSize();
1408  MyAlloca->setAlignment(StackAlignment);
1409  assert(MyAlloca->isStaticAlloca());
1410  Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
1411  Value *LocalStackBase = OrigStackBase;
1412
1413  if (DoStackMalloc) {
1414    // LocalStackBase = OrigStackBase
1415    // if (__asan_option_detect_stack_use_after_return)
1416    //   LocalStackBase = __asan_stack_malloc_N(LocalStackBase, OrigStackBase);
1417    StackMallocIdx = StackMallocSizeClass(LocalStackSize);
1418    assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
1419    Constant *OptionDetectUAR = F.getParent()->getOrInsertGlobal(
1420        kAsanOptionDetectUAR, IRB.getInt32Ty());
1421    Value *Cmp = IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUAR),
1422                                  Constant::getNullValue(IRB.getInt32Ty()));
1423    Instruction *Term =
1424        SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
1425    BasicBlock *CmpBlock = cast<Instruction>(Cmp)->getParent();
1426    IRBuilder<> IRBIf(Term);
1427    LocalStackBase = IRBIf.CreateCall2(
1428        AsanStackMallocFunc[StackMallocIdx],
1429        ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
1430    BasicBlock *SetBlock = cast<Instruction>(LocalStackBase)->getParent();
1431    IRB.SetInsertPoint(InsBefore);
1432    PHINode *Phi = IRB.CreatePHI(IntptrTy, 2);
1433    Phi->addIncoming(OrigStackBase, CmpBlock);
1434    Phi->addIncoming(LocalStackBase, SetBlock);
1435    LocalStackBase = Phi;
1436  }
1437
1438  // This string will be parsed by the run-time (DescribeAddressIfStack).
1439  SmallString<2048> StackDescriptionStorage;
1440  raw_svector_ostream StackDescription(StackDescriptionStorage);
1441  StackDescription << AllocaVec.size() << " ";
1442
1443  // Insert poison calls for lifetime intrinsics for alloca.
1444  bool HavePoisonedAllocas = false;
1445  for (size_t i = 0, n = AllocaPoisonCallVec.size(); i < n; i++) {
1446    const AllocaPoisonCall &APC = AllocaPoisonCallVec[i];
1447    IntrinsicInst *II = APC.InsBefore;
1448    AllocaInst *AI = findAllocaForValue(II->getArgOperand(1));
1449    assert(AI);
1450    IRBuilder<> IRB(II);
1451    poisonAlloca(AI, APC.Size, IRB, APC.DoPoison);
1452    HavePoisonedAllocas |= APC.DoPoison;
1453  }
1454
1455  uint64_t Pos = RedzoneSize();
1456  // Replace Alloca instructions with base+offset.
1457  for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1458    AllocaInst *AI = AllocaVec[i];
1459    uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1460    StringRef Name = AI->getName();
1461    StackDescription << Pos << " " << SizeInBytes << " "
1462                     << Name.size() << " " << Name << " ";
1463    uint64_t AlignedSize = getAlignedAllocaSize(AI);
1464    assert((AlignedSize % RedzoneSize()) == 0);
1465    Value *NewAllocaPtr = IRB.CreateIntToPtr(
1466            IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Pos)),
1467            AI->getType());
1468    replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB);
1469    AI->replaceAllUsesWith(NewAllocaPtr);
1470    Pos += AlignedSize + RedzoneSize();
1471  }
1472  assert(Pos == LocalStackSize);
1473
1474  // The left-most redzone has enough space for at least 4 pointers.
1475  // Write the Magic value to redzone[0].
1476  Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1477  IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1478                  BasePlus0);
1479  // Write the frame description constant to redzone[1].
1480  Value *BasePlus1 = IRB.CreateIntToPtr(
1481    IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, ASan.LongSize/8)),
1482    IntptrPtrTy);
1483  GlobalVariable *StackDescriptionGlobal =
1484      createPrivateGlobalForString(*F.getParent(), StackDescription.str());
1485  Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal,
1486                                             IntptrTy);
1487  IRB.CreateStore(Description, BasePlus1);
1488  // Write the PC to redzone[2].
1489  Value *BasePlus2 = IRB.CreateIntToPtr(
1490    IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy,
1491                                                   2 * ASan.LongSize/8)),
1492    IntptrPtrTy);
1493  IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
1494
1495  // Poison the stack redzones at the entry.
1496  Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
1497  poisonRedZones(AllocaVec, IRB, ShadowBase, true);
1498
1499  // Unpoison the stack before all ret instructions.
1500  for (size_t i = 0, n = RetVec.size(); i < n; i++) {
1501    Instruction *Ret = RetVec[i];
1502    IRBuilder<> IRBRet(Ret);
1503    // Mark the current frame as retired.
1504    IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1505                       BasePlus0);
1506    // Unpoison the stack.
1507    poisonRedZones(AllocaVec, IRBRet, ShadowBase, false);
1508    if (DoStackMalloc) {
1509      assert(StackMallocIdx >= 0);
1510      // In use-after-return mode, mark the whole stack frame unaddressable.
1511      if (StackMallocIdx <= 4) {
1512        // For small sizes inline the whole thing:
1513        // if LocalStackBase != OrigStackBase:
1514        //     memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
1515        //     **SavedFlagPtr(LocalStackBase) = 0
1516        // FIXME: if LocalStackBase != OrigStackBase don't call poisonRedZones.
1517        Value *Cmp = IRBRet.CreateICmpNE(LocalStackBase, OrigStackBase);
1518        TerminatorInst *PoisonTerm =
1519            SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
1520        IRBuilder<> IRBPoison(PoisonTerm);
1521        int ClassSize = kMinStackMallocSize << StackMallocIdx;
1522        SetShadowToStackAfterReturnInlined(IRBPoison, ShadowBase,
1523                                           ClassSize >> Mapping.Scale);
1524        Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
1525            LocalStackBase,
1526            ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
1527        Value *SavedFlagPtr = IRBPoison.CreateLoad(
1528            IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
1529        IRBPoison.CreateStore(
1530            Constant::getNullValue(IRBPoison.getInt8Ty()),
1531            IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
1532      } else {
1533        // For larger frames call __asan_stack_free_*.
1534        IRBRet.CreateCall3(AsanStackFreeFunc[StackMallocIdx], LocalStackBase,
1535                           ConstantInt::get(IntptrTy, LocalStackSize),
1536                           OrigStackBase);
1537      }
1538    } else if (HavePoisonedAllocas) {
1539      // If we poisoned some allocas in llvm.lifetime analysis,
1540      // unpoison whole stack frame now.
1541      assert(LocalStackBase == OrigStackBase);
1542      poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
1543    }
1544  }
1545
1546  // We are done. Remove the old unused alloca instructions.
1547  for (size_t i = 0, n = AllocaVec.size(); i < n; i++)
1548    AllocaVec[i]->eraseFromParent();
1549}
1550
1551void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
1552                                         IRBuilder<> &IRB, bool DoPoison) {
1553  // For now just insert the call to ASan runtime.
1554  Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
1555  Value *SizeArg = ConstantInt::get(IntptrTy, Size);
1556  IRB.CreateCall2(DoPoison ? AsanPoisonStackMemoryFunc
1557                           : AsanUnpoisonStackMemoryFunc,
1558                  AddrArg, SizeArg);
1559}
1560
1561// Handling llvm.lifetime intrinsics for a given %alloca:
1562// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
1563// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
1564//     invalid accesses) and unpoison it for llvm.lifetime.start (the memory
1565//     could be poisoned by previous llvm.lifetime.end instruction, as the
1566//     variable may go in and out of scope several times, e.g. in loops).
1567// (3) if we poisoned at least one %alloca in a function,
1568//     unpoison the whole stack frame at function exit.
1569
1570AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
1571  if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
1572    // We're intested only in allocas we can handle.
1573    return isInterestingAlloca(*AI) ? AI : 0;
1574  // See if we've already calculated (or started to calculate) alloca for a
1575  // given value.
1576  AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
1577  if (I != AllocaForValue.end())
1578    return I->second;
1579  // Store 0 while we're calculating alloca for value V to avoid
1580  // infinite recursion if the value references itself.
1581  AllocaForValue[V] = 0;
1582  AllocaInst *Res = 0;
1583  if (CastInst *CI = dyn_cast<CastInst>(V))
1584    Res = findAllocaForValue(CI->getOperand(0));
1585  else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1586    for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1587      Value *IncValue = PN->getIncomingValue(i);
1588      // Allow self-referencing phi-nodes.
1589      if (IncValue == PN) continue;
1590      AllocaInst *IncValueAI = findAllocaForValue(IncValue);
1591      // AI for incoming values should exist and should all be equal.
1592      if (IncValueAI == 0 || (Res != 0 && IncValueAI != Res))
1593        return 0;
1594      Res = IncValueAI;
1595    }
1596  }
1597  if (Res != 0)
1598    AllocaForValue[V] = Res;
1599  return Res;
1600}
1601