Improve debug info generated with enabled AddressSanitizer.
[oota-llvm.git] / lib / Transforms / Instrumentation / AddressSanitizer.cpp
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 "BlackList.h"
20 #include "llvm/ADT/ArrayRef.h"
21 #include "llvm/ADT/OwningPtr.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/SmallString.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/ADT/Triple.h"
27 #include "llvm/DataLayout.h"
28 #include "llvm/DIBuilder.h"
29 #include "llvm/Function.h"
30 #include "llvm/IRBuilder.h"
31 #include "llvm/InlineAsm.h"
32 #include "llvm/IntrinsicInst.h"
33 #include "llvm/LLVMContext.h"
34 #include "llvm/Module.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/DataTypes.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include "llvm/Support/system_error.h"
40 #include "llvm/Target/TargetMachine.h"
41 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
42 #include "llvm/Transforms/Utils/Local.h"
43 #include "llvm/Transforms/Utils/ModuleUtils.h"
44 #include "llvm/Type.h"
45 #include <algorithm>
46 #include <string>
47
48 using namespace llvm;
49
50 static const uint64_t kDefaultShadowScale = 3;
51 static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
52 static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
53 static const uint64_t kDefaultShadowOffsetAndroid = 0;
54
55 static const size_t kMaxStackMallocSize = 1 << 16;  // 64K
56 static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
57 static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
58
59 static const char *kAsanModuleCtorName = "asan.module_ctor";
60 static const char *kAsanModuleDtorName = "asan.module_dtor";
61 static const int   kAsanCtorAndCtorPriority = 1;
62 static const char *kAsanReportErrorTemplate = "__asan_report_";
63 static const char *kAsanRegisterGlobalsName = "__asan_register_globals";
64 static const char *kAsanUnregisterGlobalsName = "__asan_unregister_globals";
65 static const char *kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
66 static const char *kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
67 static const char *kAsanInitName = "__asan_init";
68 static const char *kAsanHandleNoReturnName = "__asan_handle_no_return";
69 static const char *kAsanMappingOffsetName = "__asan_mapping_offset";
70 static const char *kAsanMappingScaleName = "__asan_mapping_scale";
71 static const char *kAsanStackMallocName = "__asan_stack_malloc";
72 static const char *kAsanStackFreeName = "__asan_stack_free";
73 static const char *kAsanGenPrefix = "__asan_gen_";
74 static const char *kAsanPoisonStackMemoryName = "__asan_poison_stack_memory";
75 static const char *kAsanUnpoisonStackMemoryName =
76     "__asan_unpoison_stack_memory";
77
78 static const int kAsanStackLeftRedzoneMagic = 0xf1;
79 static const int kAsanStackMidRedzoneMagic = 0xf2;
80 static const int kAsanStackRightRedzoneMagic = 0xf3;
81 static const int kAsanStackPartialRedzoneMagic = 0xf4;
82
83 // Accesses sizes are powers of two: 1, 2, 4, 8, 16.
84 static const size_t kNumberOfAccessSizes = 5;
85
86 // Command-line flags.
87
88 // This flag may need to be replaced with -f[no-]asan-reads.
89 static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
90        cl::desc("instrument read instructions"), cl::Hidden, cl::init(true));
91 static cl::opt<bool> ClInstrumentWrites("asan-instrument-writes",
92        cl::desc("instrument write instructions"), cl::Hidden, cl::init(true));
93 static cl::opt<bool> ClInstrumentAtomics("asan-instrument-atomics",
94        cl::desc("instrument atomic instructions (rmw, cmpxchg)"),
95        cl::Hidden, cl::init(true));
96 static cl::opt<bool> ClAlwaysSlowPath("asan-always-slow-path",
97        cl::desc("use instrumentation with slow path for all accesses"),
98        cl::Hidden, cl::init(false));
99 // This flag limits the number of instructions to be instrumented
100 // in any given BB. Normally, this should be set to unlimited (INT_MAX),
101 // but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
102 // set it to 10000.
103 static cl::opt<int> ClMaxInsnsToInstrumentPerBB("asan-max-ins-per-bb",
104        cl::init(10000),
105        cl::desc("maximal number of instructions to instrument in any given BB"),
106        cl::Hidden);
107 // This flag may need to be replaced with -f[no]asan-stack.
108 static cl::opt<bool> ClStack("asan-stack",
109        cl::desc("Handle stack memory"), cl::Hidden, cl::init(true));
110 // This flag may need to be replaced with -f[no]asan-use-after-return.
111 static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
112        cl::desc("Check return-after-free"), cl::Hidden, cl::init(false));
113 // This flag may need to be replaced with -f[no]asan-globals.
114 static cl::opt<bool> ClGlobals("asan-globals",
115        cl::desc("Handle global objects"), cl::Hidden, cl::init(true));
116 static cl::opt<bool> ClInitializers("asan-initialization-order",
117        cl::desc("Handle C++ initializer order"), cl::Hidden, cl::init(false));
118 static cl::opt<bool> ClMemIntrin("asan-memintrin",
119        cl::desc("Handle memset/memcpy/memmove"), cl::Hidden, cl::init(true));
120 static cl::opt<bool> ClRealignStack("asan-realign-stack",
121        cl::desc("Realign stack to 32"), cl::Hidden, cl::init(true));
122 static cl::opt<std::string> ClBlacklistFile("asan-blacklist",
123        cl::desc("File containing the list of objects to ignore "
124                 "during instrumentation"), cl::Hidden);
125
126 // These flags allow to change the shadow mapping.
127 // The shadow mapping looks like
128 //    Shadow = (Mem >> scale) + (1 << offset_log)
129 static cl::opt<int> ClMappingScale("asan-mapping-scale",
130        cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
131 static cl::opt<int> ClMappingOffsetLog("asan-mapping-offset-log",
132        cl::desc("offset of asan shadow mapping"), cl::Hidden, cl::init(-1));
133
134 // Optimization flags. Not user visible, used mostly for testing
135 // and benchmarking the tool.
136 static cl::opt<bool> ClOpt("asan-opt",
137        cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
138 static cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
139        cl::desc("Instrument the same temp just once"), cl::Hidden,
140        cl::init(true));
141 static cl::opt<bool> ClOptGlobals("asan-opt-globals",
142        cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
143
144 static cl::opt<bool> ClCheckLifetime("asan-check-lifetime",
145        cl::desc("Use llvm.lifetime intrinsics to insert extra checks"),
146        cl::Hidden, cl::init(false));
147
148 // Debug flags.
149 static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
150                             cl::init(0));
151 static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
152                                  cl::Hidden, cl::init(0));
153 static cl::opt<std::string> ClDebugFunc("asan-debug-func",
154                                         cl::Hidden, cl::desc("Debug func"));
155 static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
156                                cl::Hidden, cl::init(-1));
157 static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
158                                cl::Hidden, cl::init(-1));
159
160 namespace {
161 /// A set of dynamically initialized globals extracted from metadata.
162 class SetOfDynamicallyInitializedGlobals {
163  public:
164   void Init(Module& M) {
165     // Clang generates metadata identifying all dynamically initialized globals.
166     NamedMDNode *DynamicGlobals =
167         M.getNamedMetadata("llvm.asan.dynamically_initialized_globals");
168     if (!DynamicGlobals)
169       return;
170     for (int i = 0, n = DynamicGlobals->getNumOperands(); i < n; ++i) {
171       MDNode *MDN = DynamicGlobals->getOperand(i);
172       assert(MDN->getNumOperands() == 1);
173       Value *VG = MDN->getOperand(0);
174       // The optimizer may optimize away a global entirely, in which case we
175       // cannot instrument access to it.
176       if (!VG)
177         continue;
178       DynInitGlobals.insert(cast<GlobalVariable>(VG));
179     }
180   }
181   bool Contains(GlobalVariable *G) { return DynInitGlobals.count(G) != 0; }
182  private:
183   SmallSet<GlobalValue*, 32> DynInitGlobals;
184 };
185
186 static int MappingScale() {
187   return ClMappingScale ? ClMappingScale : kDefaultShadowScale;
188 }
189
190 static size_t RedzoneSize() {
191   // Redzone used for stack and globals is at least 32 bytes.
192   // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
193   return std::max(32U, 1U << MappingScale());
194 }
195
196 /// AddressSanitizer: instrument the code in module to find memory bugs.
197 struct AddressSanitizer : public FunctionPass {
198   AddressSanitizer(bool CheckInitOrder = false,
199                    bool CheckUseAfterReturn = false,
200                    bool CheckLifetime = false,
201                    StringRef BlacklistFile = StringRef())
202       : FunctionPass(ID),
203         CheckInitOrder(CheckInitOrder || ClInitializers),
204         CheckUseAfterReturn(CheckUseAfterReturn || ClUseAfterReturn),
205         CheckLifetime(CheckLifetime || ClCheckLifetime),
206         BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
207                                             : BlacklistFile) {}
208   virtual const char *getPassName() const {
209     return "AddressSanitizerFunctionPass";
210   }
211   void instrumentMop(Instruction *I);
212   void instrumentAddress(Instruction *OrigIns, IRBuilder<> &IRB,
213                          Value *Addr, uint32_t TypeSize, bool IsWrite);
214   Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
215                            Value *ShadowValue, uint32_t TypeSize);
216   Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
217                                  bool IsWrite, size_t AccessSizeIndex);
218   bool instrumentMemIntrinsic(MemIntrinsic *MI);
219   void instrumentMemIntrinsicParam(Instruction *OrigIns, Value *Addr,
220                                    Value *Size,
221                                    Instruction *InsertBefore, bool IsWrite);
222   Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
223   bool runOnFunction(Function &F);
224   void createInitializerPoisonCalls(Module &M,
225                                     Value *FirstAddr, Value *LastAddr);
226   bool maybeInsertAsanInitAtFunctionEntry(Function &F);
227   bool poisonStackInFunction(Function &F);
228   virtual bool doInitialization(Module &M);
229   static char ID;  // Pass identification, replacement for typeid
230
231  private:
232   void initializeCallbacks(Module &M);
233   uint64_t getAllocaSizeInBytes(AllocaInst *AI) {
234     Type *Ty = AI->getAllocatedType();
235     uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
236     return SizeInBytes;
237   }
238   uint64_t getAlignedSize(uint64_t SizeInBytes) {
239     size_t RZ = RedzoneSize();
240     return ((SizeInBytes + RZ - 1) / RZ) * RZ;
241   }
242   uint64_t getAlignedAllocaSize(AllocaInst *AI) {
243     uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
244     return getAlignedSize(SizeInBytes);
245   }
246
247   bool ShouldInstrumentGlobal(GlobalVariable *G);
248   void PoisonStack(const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> IRB,
249                    Value *ShadowBase, bool DoPoison);
250   bool LooksLikeCodeInBug11395(Instruction *I);
251   void FindDynamicInitializers(Module &M);
252   /// Analyze lifetime intrinsics for given alloca. Use Value* instead of
253   /// AllocaInst* here, as we call this method after we merge all allocas into a
254   /// single one. Returns true if ASan added some instrumentation.
255   bool handleAllocaLifetime(Value *Alloca);
256   /// Analyze lifetime intrinsics for a specific value, casted from alloca.
257   /// Returns true if if ASan added some instrumentation.
258   bool handleValueLifetime(Value *V);
259   void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> IRB, bool DoPoison);
260
261   bool CheckInitOrder;
262   bool CheckUseAfterReturn;
263   bool CheckLifetime;
264   LLVMContext *C;
265   DataLayout *TD;
266   uint64_t MappingOffset;
267   int LongSize;
268   Type *IntptrTy;
269   Type *IntptrPtrTy;
270   Function *AsanCtorFunction;
271   Function *AsanInitFunction;
272   Function *AsanStackMallocFunc, *AsanStackFreeFunc;
273   Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
274   Function *AsanHandleNoReturnFunc;
275   SmallString<64> BlacklistFile;
276   OwningPtr<BlackList> BL;
277   // This array is indexed by AccessIsWrite and log2(AccessSize).
278   Function *AsanErrorCallback[2][kNumberOfAccessSizes];
279   InlineAsm *EmptyAsm;
280   SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
281 };
282
283 class AddressSanitizerModule : public ModulePass {
284  public:
285   AddressSanitizerModule(bool CheckInitOrder = false,
286                          StringRef BlacklistFile = StringRef())
287       : ModulePass(ID),
288         CheckInitOrder(CheckInitOrder || ClInitializers),
289         BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
290                                             : BlacklistFile) {}
291   bool runOnModule(Module &M);
292   static char ID;  // Pass identification, replacement for typeid
293   virtual const char *getPassName() const {
294     return "AddressSanitizerModule";
295   }
296
297  private:
298   bool ShouldInstrumentGlobal(GlobalVariable *G);
299   void createInitializerPoisonCalls(Module &M, Value *FirstAddr,
300                                     Value *LastAddr);
301
302   bool CheckInitOrder;
303   SmallString<64> BlacklistFile;
304   OwningPtr<BlackList> BL;
305   SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
306   Type *IntptrTy;
307   LLVMContext *C;
308   DataLayout *TD;
309 };
310
311 }  // namespace
312
313 char AddressSanitizer::ID = 0;
314 INITIALIZE_PASS(AddressSanitizer, "asan",
315     "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
316     false, false)
317 FunctionPass *llvm::createAddressSanitizerFunctionPass(
318     bool CheckInitOrder, bool CheckUseAfterReturn, bool CheckLifetime,
319     StringRef BlacklistFile) {
320   return new AddressSanitizer(CheckInitOrder, CheckUseAfterReturn,
321                               CheckLifetime, BlacklistFile);
322 }
323
324 char AddressSanitizerModule::ID = 0;
325 INITIALIZE_PASS(AddressSanitizerModule, "asan-module",
326     "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
327     "ModulePass", false, false)
328 ModulePass *llvm::createAddressSanitizerModulePass(
329     bool CheckInitOrder, StringRef BlacklistFile) {
330   return new AddressSanitizerModule(CheckInitOrder, BlacklistFile);
331 }
332
333 static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
334   size_t Res = CountTrailingZeros_32(TypeSize / 8);
335   assert(Res < kNumberOfAccessSizes);
336   return Res;
337 }
338
339 // Create a constant for Str so that we can pass it to the run-time lib.
340 static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str) {
341   Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
342   return new GlobalVariable(M, StrConst->getType(), true,
343                             GlobalValue::PrivateLinkage, StrConst,
344                             kAsanGenPrefix);
345 }
346
347 static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
348   return G->getName().find(kAsanGenPrefix) == 0;
349 }
350
351 Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
352   // Shadow >> scale
353   Shadow = IRB.CreateLShr(Shadow, MappingScale());
354   if (MappingOffset == 0)
355     return Shadow;
356   // (Shadow >> scale) | offset
357   return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy,
358                                                MappingOffset));
359 }
360
361 void AddressSanitizer::instrumentMemIntrinsicParam(
362     Instruction *OrigIns,
363     Value *Addr, Value *Size, Instruction *InsertBefore, bool IsWrite) {
364   // Check the first byte.
365   {
366     IRBuilder<> IRB(InsertBefore);
367     instrumentAddress(OrigIns, IRB, Addr, 8, IsWrite);
368   }
369   // Check the last byte.
370   {
371     IRBuilder<> IRB(InsertBefore);
372     Value *SizeMinusOne = IRB.CreateSub(
373         Size, ConstantInt::get(Size->getType(), 1));
374     SizeMinusOne = IRB.CreateIntCast(SizeMinusOne, IntptrTy, false);
375     Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
376     Value *AddrPlusSizeMinisOne = IRB.CreateAdd(AddrLong, SizeMinusOne);
377     instrumentAddress(OrigIns, IRB, AddrPlusSizeMinisOne, 8, IsWrite);
378   }
379 }
380
381 // Instrument memset/memmove/memcpy
382 bool AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
383   Value *Dst = MI->getDest();
384   MemTransferInst *MemTran = dyn_cast<MemTransferInst>(MI);
385   Value *Src = MemTran ? MemTran->getSource() : 0;
386   Value *Length = MI->getLength();
387
388   Constant *ConstLength = dyn_cast<Constant>(Length);
389   Instruction *InsertBefore = MI;
390   if (ConstLength) {
391     if (ConstLength->isNullValue()) return false;
392   } else {
393     // The size is not a constant so it could be zero -- check at run-time.
394     IRBuilder<> IRB(InsertBefore);
395
396     Value *Cmp = IRB.CreateICmpNE(Length,
397                                   Constant::getNullValue(Length->getType()));
398     InsertBefore = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
399   }
400
401   instrumentMemIntrinsicParam(MI, Dst, Length, InsertBefore, true);
402   if (Src)
403     instrumentMemIntrinsicParam(MI, Src, Length, InsertBefore, false);
404   return true;
405 }
406
407 // If I is an interesting memory access, return the PointerOperand
408 // and set IsWrite. Otherwise return NULL.
409 static Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite) {
410   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
411     if (!ClInstrumentReads) return NULL;
412     *IsWrite = false;
413     return LI->getPointerOperand();
414   }
415   if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
416     if (!ClInstrumentWrites) return NULL;
417     *IsWrite = true;
418     return SI->getPointerOperand();
419   }
420   if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
421     if (!ClInstrumentAtomics) return NULL;
422     *IsWrite = true;
423     return RMW->getPointerOperand();
424   }
425   if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
426     if (!ClInstrumentAtomics) return NULL;
427     *IsWrite = true;
428     return XCHG->getPointerOperand();
429   }
430   return NULL;
431 }
432
433 void AddressSanitizer::instrumentMop(Instruction *I) {
434   bool IsWrite = false;
435   Value *Addr = isInterestingMemoryAccess(I, &IsWrite);
436   assert(Addr);
437   if (ClOpt && ClOptGlobals) {
438     if (GlobalVariable *G = dyn_cast<GlobalVariable>(Addr)) {
439       // If initialization order checking is disabled, a simple access to a
440       // dynamically initialized global is always valid.
441       if (!CheckInitOrder)
442         return;
443       // If a global variable does not have dynamic initialization we don't
444       // have to instrument it.  However, if a global does not have initailizer
445       // at all, we assume it has dynamic initializer (in other TU).
446       if (G->hasInitializer() && !DynamicallyInitializedGlobals.Contains(G))
447         return;
448     }
449   }
450
451   Type *OrigPtrTy = Addr->getType();
452   Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
453
454   assert(OrigTy->isSized());
455   uint32_t TypeSize = TD->getTypeStoreSizeInBits(OrigTy);
456
457   if (TypeSize != 8  && TypeSize != 16 &&
458       TypeSize != 32 && TypeSize != 64 && TypeSize != 128) {
459     // Ignore all unusual sizes.
460     return;
461   }
462
463   IRBuilder<> IRB(I);
464   instrumentAddress(I, IRB, Addr, TypeSize, IsWrite);
465 }
466
467 // Validate the result of Module::getOrInsertFunction called for an interface
468 // function of AddressSanitizer. If the instrumented module defines a function
469 // with the same name, their prototypes must match, otherwise
470 // getOrInsertFunction returns a bitcast.
471 static Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
472   if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
473   FuncOrBitcast->dump();
474   report_fatal_error("trying to redefine an AddressSanitizer "
475                      "interface function");
476 }
477
478 Instruction *AddressSanitizer::generateCrashCode(
479     Instruction *InsertBefore, Value *Addr,
480     bool IsWrite, size_t AccessSizeIndex) {
481   IRBuilder<> IRB(InsertBefore);
482   CallInst *Call = IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex],
483                                   Addr);
484   // We don't do Call->setDoesNotReturn() because the BB already has
485   // UnreachableInst at the end.
486   // This EmptyAsm is required to avoid callback merge.
487   IRB.CreateCall(EmptyAsm);
488   return Call;
489 }
490
491 Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
492                                             Value *ShadowValue,
493                                             uint32_t TypeSize) {
494   size_t Granularity = 1 << MappingScale();
495   // Addr & (Granularity - 1)
496   Value *LastAccessedByte = IRB.CreateAnd(
497       AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
498   // (Addr & (Granularity - 1)) + size - 1
499   if (TypeSize / 8 > 1)
500     LastAccessedByte = IRB.CreateAdd(
501         LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
502   // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
503   LastAccessedByte = IRB.CreateIntCast(
504       LastAccessedByte, ShadowValue->getType(), false);
505   // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
506   return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
507 }
508
509 void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
510                                          IRBuilder<> &IRB, Value *Addr,
511                                          uint32_t TypeSize, bool IsWrite) {
512   Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
513
514   Type *ShadowTy  = IntegerType::get(
515       *C, std::max(8U, TypeSize >> MappingScale()));
516   Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
517   Value *ShadowPtr = memToShadow(AddrLong, IRB);
518   Value *CmpVal = Constant::getNullValue(ShadowTy);
519   Value *ShadowValue = IRB.CreateLoad(
520       IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
521
522   Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
523   size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
524   size_t Granularity = 1 << MappingScale();
525   TerminatorInst *CrashTerm = 0;
526
527   if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
528     TerminatorInst *CheckTerm =
529         SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
530     assert(dyn_cast<BranchInst>(CheckTerm)->isUnconditional());
531     BasicBlock *NextBB = CheckTerm->getSuccessor(0);
532     IRB.SetInsertPoint(CheckTerm);
533     Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
534     BasicBlock *CrashBlock =
535         BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
536     CrashTerm = new UnreachableInst(*C, CrashBlock);
537     BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
538     ReplaceInstWithInst(CheckTerm, NewTerm);
539   } else {
540     CrashTerm = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), true);
541   }
542
543   Instruction *Crash =
544       generateCrashCode(CrashTerm, AddrLong, IsWrite, AccessSizeIndex);
545   Crash->setDebugLoc(OrigIns->getDebugLoc());
546 }
547
548 void AddressSanitizerModule::createInitializerPoisonCalls(
549     Module &M, Value *FirstAddr, Value *LastAddr) {
550   // We do all of our poisoning and unpoisoning within _GLOBAL__I_a.
551   Function *GlobalInit = M.getFunction("_GLOBAL__I_a");
552   // If that function is not present, this TU contains no globals, or they have
553   // all been optimized away
554   if (!GlobalInit)
555     return;
556
557   // Set up the arguments to our poison/unpoison functions.
558   IRBuilder<> IRB(GlobalInit->begin()->getFirstInsertionPt());
559
560   // Declare our poisoning and unpoisoning functions.
561   Function *AsanPoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
562       kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
563   AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
564   Function *AsanUnpoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
565       kAsanUnpoisonGlobalsName, IRB.getVoidTy(), NULL));
566   AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
567
568   // Add a call to poison all external globals before the given function starts.
569   IRB.CreateCall2(AsanPoisonGlobals, FirstAddr, LastAddr);
570
571   // Add calls to unpoison all globals before each return instruction.
572   for (Function::iterator I = GlobalInit->begin(), E = GlobalInit->end();
573       I != E; ++I) {
574     if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator())) {
575       CallInst::Create(AsanUnpoisonGlobals, "", RI);
576     }
577   }
578 }
579
580 bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
581   Type *Ty = cast<PointerType>(G->getType())->getElementType();
582   DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
583
584   if (BL->isIn(*G)) return false;
585   if (!Ty->isSized()) return false;
586   if (!G->hasInitializer()) return false;
587   if (GlobalWasGeneratedByAsan(G)) return false;  // Our own global.
588   // Touch only those globals that will not be defined in other modules.
589   // Don't handle ODR type linkages since other modules may be built w/o asan.
590   if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
591       G->getLinkage() != GlobalVariable::PrivateLinkage &&
592       G->getLinkage() != GlobalVariable::InternalLinkage)
593     return false;
594   // Two problems with thread-locals:
595   //   - The address of the main thread's copy can't be computed at link-time.
596   //   - Need to poison all copies, not just the main thread's one.
597   if (G->isThreadLocal())
598     return false;
599   // For now, just ignore this Alloca if the alignment is large.
600   if (G->getAlignment() > RedzoneSize()) return false;
601
602   // Ignore all the globals with the names starting with "\01L_OBJC_".
603   // Many of those are put into the .cstring section. The linker compresses
604   // that section by removing the spare \0s after the string terminator, so
605   // our redzones get broken.
606   if ((G->getName().find("\01L_OBJC_") == 0) ||
607       (G->getName().find("\01l_OBJC_") == 0)) {
608     DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G);
609     return false;
610   }
611
612   if (G->hasSection()) {
613     StringRef Section(G->getSection());
614     // Ignore the globals from the __OBJC section. The ObjC runtime assumes
615     // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
616     // them.
617     if ((Section.find("__OBJC,") == 0) ||
618         (Section.find("__DATA, __objc_") == 0)) {
619       DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G);
620       return false;
621     }
622     // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
623     // Constant CFString instances are compiled in the following way:
624     //  -- the string buffer is emitted into
625     //     __TEXT,__cstring,cstring_literals
626     //  -- the constant NSConstantString structure referencing that buffer
627     //     is placed into __DATA,__cfstring
628     // Therefore there's no point in placing redzones into __DATA,__cfstring.
629     // Moreover, it causes the linker to crash on OS X 10.7
630     if (Section.find("__DATA,__cfstring") == 0) {
631       DEBUG(dbgs() << "Ignoring CFString: " << *G);
632       return false;
633     }
634   }
635
636   return true;
637 }
638
639 // This function replaces all global variables with new variables that have
640 // trailing redzones. It also creates a function that poisons
641 // redzones and inserts this function into llvm.global_ctors.
642 bool AddressSanitizerModule::runOnModule(Module &M) {
643   if (!ClGlobals) return false;
644   TD = getAnalysisIfAvailable<DataLayout>();
645   if (!TD)
646     return false;
647   BL.reset(new BlackList(BlacklistFile));
648   if (BL->isIn(M)) return false;
649   DynamicallyInitializedGlobals.Init(M);
650   C = &(M.getContext());
651   IntptrTy = Type::getIntNTy(*C, TD->getPointerSizeInBits());
652
653   SmallVector<GlobalVariable *, 16> GlobalsToChange;
654
655   for (Module::GlobalListType::iterator G = M.global_begin(),
656        E = M.global_end(); G != E; ++G) {
657     if (ShouldInstrumentGlobal(G))
658       GlobalsToChange.push_back(G);
659   }
660
661   size_t n = GlobalsToChange.size();
662   if (n == 0) return false;
663
664   // A global is described by a structure
665   //   size_t beg;
666   //   size_t size;
667   //   size_t size_with_redzone;
668   //   const char *name;
669   //   size_t has_dynamic_init;
670   // We initialize an array of such structures and pass it to a run-time call.
671   StructType *GlobalStructTy = StructType::get(IntptrTy, IntptrTy,
672                                                IntptrTy, IntptrTy,
673                                                IntptrTy, NULL);
674   SmallVector<Constant *, 16> Initializers(n), DynamicInit;
675
676
677   Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
678   assert(CtorFunc);
679   IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
680
681   // The addresses of the first and last dynamically initialized globals in
682   // this TU.  Used in initialization order checking.
683   Value *FirstDynamic = 0, *LastDynamic = 0;
684
685   for (size_t i = 0; i < n; i++) {
686     GlobalVariable *G = GlobalsToChange[i];
687     PointerType *PtrTy = cast<PointerType>(G->getType());
688     Type *Ty = PtrTy->getElementType();
689     uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
690     size_t RZ = RedzoneSize();
691     uint64_t RightRedzoneSize = RZ + (RZ - (SizeInBytes % RZ));
692     Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
693     // Determine whether this global should be poisoned in initialization.
694     bool GlobalHasDynamicInitializer =
695         DynamicallyInitializedGlobals.Contains(G);
696     // Don't check initialization order if this global is blacklisted.
697     GlobalHasDynamicInitializer &= !BL->isInInit(*G);
698
699     StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
700     Constant *NewInitializer = ConstantStruct::get(
701         NewTy, G->getInitializer(),
702         Constant::getNullValue(RightRedZoneTy), NULL);
703
704     SmallString<2048> DescriptionOfGlobal = G->getName();
705     DescriptionOfGlobal += " (";
706     DescriptionOfGlobal += M.getModuleIdentifier();
707     DescriptionOfGlobal += ")";
708     GlobalVariable *Name = createPrivateGlobalForString(M, DescriptionOfGlobal);
709
710     // Create a new global variable with enough space for a redzone.
711     GlobalVariable *NewGlobal = new GlobalVariable(
712         M, NewTy, G->isConstant(), G->getLinkage(),
713         NewInitializer, "", G, G->getThreadLocalMode());
714     NewGlobal->copyAttributesFrom(G);
715     NewGlobal->setAlignment(RZ);
716
717     Value *Indices2[2];
718     Indices2[0] = IRB.getInt32(0);
719     Indices2[1] = IRB.getInt32(0);
720
721     G->replaceAllUsesWith(
722         ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
723     NewGlobal->takeName(G);
724     G->eraseFromParent();
725
726     Initializers[i] = ConstantStruct::get(
727         GlobalStructTy,
728         ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
729         ConstantInt::get(IntptrTy, SizeInBytes),
730         ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
731         ConstantExpr::getPointerCast(Name, IntptrTy),
732         ConstantInt::get(IntptrTy, GlobalHasDynamicInitializer),
733         NULL);
734
735     // Populate the first and last globals declared in this TU.
736     if (CheckInitOrder && GlobalHasDynamicInitializer) {
737       LastDynamic = ConstantExpr::getPointerCast(NewGlobal, IntptrTy);
738       if (FirstDynamic == 0)
739         FirstDynamic = LastDynamic;
740     }
741
742     DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
743   }
744
745   ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
746   GlobalVariable *AllGlobals = new GlobalVariable(
747       M, ArrayOfGlobalStructTy, false, GlobalVariable::PrivateLinkage,
748       ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
749
750   // Create calls for poisoning before initializers run and unpoisoning after.
751   if (CheckInitOrder && FirstDynamic && LastDynamic)
752     createInitializerPoisonCalls(M, FirstDynamic, LastDynamic);
753
754   Function *AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
755       kAsanRegisterGlobalsName, IRB.getVoidTy(),
756       IntptrTy, IntptrTy, NULL));
757   AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
758
759   IRB.CreateCall2(AsanRegisterGlobals,
760                   IRB.CreatePointerCast(AllGlobals, IntptrTy),
761                   ConstantInt::get(IntptrTy, n));
762
763   // We also need to unregister globals at the end, e.g. when a shared library
764   // gets closed.
765   Function *AsanDtorFunction = Function::Create(
766       FunctionType::get(Type::getVoidTy(*C), false),
767       GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
768   BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
769   IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
770   Function *AsanUnregisterGlobals =
771       checkInterfaceFunction(M.getOrInsertFunction(
772           kAsanUnregisterGlobalsName,
773           IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
774   AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
775
776   IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
777                        IRB.CreatePointerCast(AllGlobals, IntptrTy),
778                        ConstantInt::get(IntptrTy, n));
779   appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndCtorPriority);
780
781   DEBUG(dbgs() << M);
782   return true;
783 }
784
785 void AddressSanitizer::initializeCallbacks(Module &M) {
786   IRBuilder<> IRB(*C);
787   // Create __asan_report* callbacks.
788   for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
789     for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
790          AccessSizeIndex++) {
791       // IsWrite and TypeSize are encoded in the function name.
792       std::string FunctionName = std::string(kAsanReportErrorTemplate) +
793           (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
794       // If we are merging crash callbacks, they have two parameters.
795       AsanErrorCallback[AccessIsWrite][AccessSizeIndex] =
796           checkInterfaceFunction(M.getOrInsertFunction(
797               FunctionName, IRB.getVoidTy(), IntptrTy, NULL));
798     }
799   }
800
801   AsanStackMallocFunc = checkInterfaceFunction(M.getOrInsertFunction(
802       kAsanStackMallocName, IntptrTy, IntptrTy, IntptrTy, NULL));
803   AsanStackFreeFunc = checkInterfaceFunction(M.getOrInsertFunction(
804       kAsanStackFreeName, IRB.getVoidTy(),
805       IntptrTy, IntptrTy, IntptrTy, NULL));
806   AsanHandleNoReturnFunc = checkInterfaceFunction(M.getOrInsertFunction(
807       kAsanHandleNoReturnName, IRB.getVoidTy(), NULL));
808   AsanPoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
809       kAsanPoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
810   AsanUnpoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
811       kAsanUnpoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
812
813   // We insert an empty inline asm after __asan_report* to avoid callback merge.
814   EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
815                             StringRef(""), StringRef(""),
816                             /*hasSideEffects=*/true);
817 }
818
819 // virtual
820 bool AddressSanitizer::doInitialization(Module &M) {
821   // Initialize the private fields. No one has accessed them before.
822   TD = getAnalysisIfAvailable<DataLayout>();
823
824   if (!TD)
825     return false;
826   BL.reset(new BlackList(BlacklistFile));
827   DynamicallyInitializedGlobals.Init(M);
828
829   C = &(M.getContext());
830   LongSize = TD->getPointerSizeInBits();
831   IntptrTy = Type::getIntNTy(*C, LongSize);
832   IntptrPtrTy = PointerType::get(IntptrTy, 0);
833
834   AsanCtorFunction = Function::Create(
835       FunctionType::get(Type::getVoidTy(*C), false),
836       GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
837   BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
838   // call __asan_init in the module ctor.
839   IRBuilder<> IRB(ReturnInst::Create(*C, AsanCtorBB));
840   AsanInitFunction = checkInterfaceFunction(
841       M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
842   AsanInitFunction->setLinkage(Function::ExternalLinkage);
843   IRB.CreateCall(AsanInitFunction);
844
845   llvm::Triple targetTriple(M.getTargetTriple());
846   bool isAndroid = targetTriple.getEnvironment() == llvm::Triple::Android;
847
848   MappingOffset = isAndroid ? kDefaultShadowOffsetAndroid :
849     (LongSize == 32 ? kDefaultShadowOffset32 : kDefaultShadowOffset64);
850   if (ClMappingOffsetLog >= 0) {
851     if (ClMappingOffsetLog == 0) {
852       // special case
853       MappingOffset = 0;
854     } else {
855       MappingOffset = 1ULL << ClMappingOffsetLog;
856     }
857   }
858
859
860   if (ClMappingOffsetLog >= 0) {
861     // Tell the run-time the current values of mapping offset and scale.
862     GlobalValue *asan_mapping_offset =
863         new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
864                        ConstantInt::get(IntptrTy, MappingOffset),
865                        kAsanMappingOffsetName);
866     // Read the global, otherwise it may be optimized away.
867     IRB.CreateLoad(asan_mapping_offset, true);
868   }
869   if (ClMappingScale) {
870     GlobalValue *asan_mapping_scale =
871         new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
872                            ConstantInt::get(IntptrTy, MappingScale()),
873                            kAsanMappingScaleName);
874     // Read the global, otherwise it may be optimized away.
875     IRB.CreateLoad(asan_mapping_scale, true);
876   }
877
878   appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndCtorPriority);
879
880   return true;
881 }
882
883 bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
884   // For each NSObject descendant having a +load method, this method is invoked
885   // by the ObjC runtime before any of the static constructors is called.
886   // Therefore we need to instrument such methods with a call to __asan_init
887   // at the beginning in order to initialize our runtime before any access to
888   // the shadow memory.
889   // We cannot just ignore these methods, because they may call other
890   // instrumented functions.
891   if (F.getName().find(" load]") != std::string::npos) {
892     IRBuilder<> IRB(F.begin()->begin());
893     IRB.CreateCall(AsanInitFunction);
894     return true;
895   }
896   return false;
897 }
898
899 bool AddressSanitizer::runOnFunction(Function &F) {
900   if (BL->isIn(F)) return false;
901   if (&F == AsanCtorFunction) return false;
902   DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
903   initializeCallbacks(*F.getParent());
904
905   // If needed, insert __asan_init before checking for AddressSafety attr.
906   maybeInsertAsanInitAtFunctionEntry(F);
907
908   if (!F.getFnAttributes().hasAttribute(Attributes::AddressSafety))
909     return false;
910
911   if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
912     return false;
913
914   // We want to instrument every address only once per basic block (unless there
915   // are calls between uses).
916   SmallSet<Value*, 16> TempsToInstrument;
917   SmallVector<Instruction*, 16> ToInstrument;
918   SmallVector<Instruction*, 8> NoReturnCalls;
919   bool IsWrite;
920
921   // Fill the set of memory operations to instrument.
922   for (Function::iterator FI = F.begin(), FE = F.end();
923        FI != FE; ++FI) {
924     TempsToInstrument.clear();
925     int NumInsnsPerBB = 0;
926     for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
927          BI != BE; ++BI) {
928       if (LooksLikeCodeInBug11395(BI)) return false;
929       if (Value *Addr = isInterestingMemoryAccess(BI, &IsWrite)) {
930         if (ClOpt && ClOptSameTemp) {
931           if (!TempsToInstrument.insert(Addr))
932             continue;  // We've seen this temp in the current BB.
933         }
934       } else if (isa<MemIntrinsic>(BI) && ClMemIntrin) {
935         // ok, take it.
936       } else {
937         if (CallInst *CI = dyn_cast<CallInst>(BI)) {
938           // A call inside BB.
939           TempsToInstrument.clear();
940           if (CI->doesNotReturn()) {
941             NoReturnCalls.push_back(CI);
942           }
943         }
944         continue;
945       }
946       ToInstrument.push_back(BI);
947       NumInsnsPerBB++;
948       if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
949         break;
950     }
951   }
952
953   // Instrument.
954   int NumInstrumented = 0;
955   for (size_t i = 0, n = ToInstrument.size(); i != n; i++) {
956     Instruction *Inst = ToInstrument[i];
957     if (ClDebugMin < 0 || ClDebugMax < 0 ||
958         (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
959       if (isInterestingMemoryAccess(Inst, &IsWrite))
960         instrumentMop(Inst);
961       else
962         instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
963     }
964     NumInstrumented++;
965   }
966
967   bool ChangedStack = poisonStackInFunction(F);
968
969   // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
970   // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
971   for (size_t i = 0, n = NoReturnCalls.size(); i != n; i++) {
972     Instruction *CI = NoReturnCalls[i];
973     IRBuilder<> IRB(CI);
974     IRB.CreateCall(AsanHandleNoReturnFunc);
975   }
976   DEBUG(dbgs() << "ASAN done instrumenting:\n" << F << "\n");
977
978   return NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
979 }
980
981 static uint64_t ValueForPoison(uint64_t PoisonByte, size_t ShadowRedzoneSize) {
982   if (ShadowRedzoneSize == 1) return PoisonByte;
983   if (ShadowRedzoneSize == 2) return (PoisonByte << 8) + PoisonByte;
984   if (ShadowRedzoneSize == 4)
985     return (PoisonByte << 24) + (PoisonByte << 16) +
986         (PoisonByte << 8) + (PoisonByte);
987   llvm_unreachable("ShadowRedzoneSize is either 1, 2 or 4");
988 }
989
990 static void PoisonShadowPartialRightRedzone(uint8_t *Shadow,
991                                             size_t Size,
992                                             size_t RZSize,
993                                             size_t ShadowGranularity,
994                                             uint8_t Magic) {
995   for (size_t i = 0; i < RZSize;
996        i+= ShadowGranularity, Shadow++) {
997     if (i + ShadowGranularity <= Size) {
998       *Shadow = 0;  // fully addressable
999     } else if (i >= Size) {
1000       *Shadow = Magic;  // unaddressable
1001     } else {
1002       *Shadow = Size - i;  // first Size-i bytes are addressable
1003     }
1004   }
1005 }
1006
1007 void AddressSanitizer::PoisonStack(const ArrayRef<AllocaInst*> &AllocaVec,
1008                                    IRBuilder<> IRB,
1009                                    Value *ShadowBase, bool DoPoison) {
1010   size_t ShadowRZSize = RedzoneSize() >> MappingScale();
1011   assert(ShadowRZSize >= 1 && ShadowRZSize <= 4);
1012   Type *RZTy = Type::getIntNTy(*C, ShadowRZSize * 8);
1013   Type *RZPtrTy = PointerType::get(RZTy, 0);
1014
1015   Value *PoisonLeft  = ConstantInt::get(RZTy,
1016     ValueForPoison(DoPoison ? kAsanStackLeftRedzoneMagic : 0LL, ShadowRZSize));
1017   Value *PoisonMid   = ConstantInt::get(RZTy,
1018     ValueForPoison(DoPoison ? kAsanStackMidRedzoneMagic : 0LL, ShadowRZSize));
1019   Value *PoisonRight = ConstantInt::get(RZTy,
1020     ValueForPoison(DoPoison ? kAsanStackRightRedzoneMagic : 0LL, ShadowRZSize));
1021
1022   // poison the first red zone.
1023   IRB.CreateStore(PoisonLeft, IRB.CreateIntToPtr(ShadowBase, RZPtrTy));
1024
1025   // poison all other red zones.
1026   uint64_t Pos = RedzoneSize();
1027   for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1028     AllocaInst *AI = AllocaVec[i];
1029     uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1030     uint64_t AlignedSize = getAlignedAllocaSize(AI);
1031     assert(AlignedSize - SizeInBytes < RedzoneSize());
1032     Value *Ptr = NULL;
1033
1034     Pos += AlignedSize;
1035
1036     assert(ShadowBase->getType() == IntptrTy);
1037     if (SizeInBytes < AlignedSize) {
1038       // Poison the partial redzone at right
1039       Ptr = IRB.CreateAdd(
1040           ShadowBase, ConstantInt::get(IntptrTy,
1041                                        (Pos >> MappingScale()) - ShadowRZSize));
1042       size_t AddressableBytes = RedzoneSize() - (AlignedSize - SizeInBytes);
1043       uint32_t Poison = 0;
1044       if (DoPoison) {
1045         PoisonShadowPartialRightRedzone((uint8_t*)&Poison, AddressableBytes,
1046                                         RedzoneSize(),
1047                                         1ULL << MappingScale(),
1048                                         kAsanStackPartialRedzoneMagic);
1049       }
1050       Value *PartialPoison = ConstantInt::get(RZTy, Poison);
1051       IRB.CreateStore(PartialPoison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
1052     }
1053
1054     // Poison the full redzone at right.
1055     Ptr = IRB.CreateAdd(ShadowBase,
1056                         ConstantInt::get(IntptrTy, Pos >> MappingScale()));
1057     Value *Poison = i == AllocaVec.size() - 1 ? PoisonRight : PoisonMid;
1058     IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
1059
1060     Pos += RedzoneSize();
1061   }
1062 }
1063
1064 // Workaround for bug 11395: we don't want to instrument stack in functions
1065 // with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1066 // FIXME: remove once the bug 11395 is fixed.
1067 bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1068   if (LongSize != 32) return false;
1069   CallInst *CI = dyn_cast<CallInst>(I);
1070   if (!CI || !CI->isInlineAsm()) return false;
1071   if (CI->getNumArgOperands() <= 5) return false;
1072   // We have inline assembly with quite a few arguments.
1073   return true;
1074 }
1075
1076 // Handling llvm.lifetime intrinsics for a given %alloca:
1077 // (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
1078 // (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
1079 //     invalid accesses) and unpoison it for llvm.lifetime.start (the memory
1080 //     could be poisoned by previous llvm.lifetime.end instruction, as the
1081 //     variable may go in and out of scope several times, e.g. in loops).
1082 // (3) if we poisoned at least one %alloca in a function,
1083 //     unpoison the whole stack frame at function exit.
1084 bool AddressSanitizer::handleAllocaLifetime(Value *Alloca) {
1085   assert(CheckLifetime);
1086   Type *AllocaType = Alloca->getType();
1087   Type *Int8PtrTy = Type::getInt8PtrTy(AllocaType->getContext());
1088
1089   bool Res = false;
1090   // Typical code looks like this:
1091   // %alloca = alloca <type>, <alignment>
1092   // ... some code ...
1093   // %val1 = bitcast <type>* %alloca to i8*
1094   // call void @llvm.lifetime.start(i64 <size>, i8* %val1)
1095   // ... more code ...
1096   // %val2 = bitcast <type>* %alloca to i8*
1097   // call void @llvm.lifetime.start(i64 <size>, i8* %val2)
1098   // That is, to handle %alloca we must find all its casts to
1099   // i8* values, and find lifetime instructions for these values.
1100   if (AllocaType == Int8PtrTy)
1101     Res |= handleValueLifetime(Alloca);
1102   for (Value::use_iterator UI = Alloca->use_begin(), UE = Alloca->use_end();
1103        UI != UE; ++UI) {
1104     if (UI->getType() != Int8PtrTy) continue;
1105     if (UI->stripPointerCasts() != Alloca) continue;
1106     Res |= handleValueLifetime(*UI);
1107   }
1108   return Res;
1109 }
1110
1111 bool AddressSanitizer::handleValueLifetime(Value *V) {
1112   assert(CheckLifetime);
1113   bool Res = false;
1114   for (Value::use_iterator UI = V->use_begin(), UE = V->use_end(); UI != UE;
1115        ++UI) {
1116     IntrinsicInst *II = dyn_cast<IntrinsicInst>(*UI);
1117     if (!II) continue;
1118     Intrinsic::ID ID = II->getIntrinsicID();
1119     if (ID != Intrinsic::lifetime_start &&
1120         ID != Intrinsic::lifetime_end)
1121       continue;
1122     if (V != II->getArgOperand(1))
1123       continue;
1124     // Found lifetime intrinsic, add ASan instrumentation if necessary.
1125     ConstantInt *Size = dyn_cast<ConstantInt>(II->getArgOperand(0));
1126     // If size argument is undefined, don't do anything.
1127     if (Size->isMinusOne())
1128       continue;
1129     // Check that size doesn't saturate uint64_t and can
1130     // be stored in IntptrTy.
1131     const uint64_t SizeValue = Size->getValue().getLimitedValue();
1132     if (SizeValue == ~0ULL ||
1133         !ConstantInt::isValueValidForType(IntptrTy, SizeValue)) {
1134       continue;
1135     }
1136     IRBuilder<> IRB(II);
1137     bool DoPoison = (ID == Intrinsic::lifetime_end);
1138     poisonAlloca(V, SizeValue, IRB, DoPoison);
1139     Res = true;
1140   }
1141   return Res;
1142 }
1143
1144 // Find all static Alloca instructions and put
1145 // poisoned red zones around all of them.
1146 // Then unpoison everything back before the function returns.
1147 //
1148 // Stack poisoning does not play well with exception handling.
1149 // When an exception is thrown, we essentially bypass the code
1150 // that unpoisones the stack. This is why the run-time library has
1151 // to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
1152 // stack in the interceptor. This however does not work inside the
1153 // actual function which catches the exception. Most likely because the
1154 // compiler hoists the load of the shadow value somewhere too high.
1155 // This causes asan to report a non-existing bug on 453.povray.
1156 // It sounds like an LLVM bug.
1157 bool AddressSanitizer::poisonStackInFunction(Function &F) {
1158   if (!ClStack) return false;
1159   SmallVector<AllocaInst*, 16> AllocaVec;
1160   SmallVector<Instruction*, 8> RetVec;
1161   uint64_t TotalSize = 0;
1162   bool HavePoisonedAllocas = false;
1163   DIBuilder DIB(*F.getParent());
1164
1165   // Filter out Alloca instructions we want (and can) handle.
1166   // Collect Ret instructions.
1167   unsigned ResultAlignment = 1 << MappingScale();
1168   for (Function::iterator FI = F.begin(), FE = F.end();
1169        FI != FE; ++FI) {
1170     BasicBlock &BB = *FI;
1171     for (BasicBlock::iterator BI = BB.begin(), BE = BB.end();
1172          BI != BE; ++BI) {
1173       if (isa<ReturnInst>(BI)) {
1174           RetVec.push_back(BI);
1175           continue;
1176       }
1177
1178       AllocaInst *AI = dyn_cast<AllocaInst>(BI);
1179       if (!AI) continue;
1180       if (AI->isArrayAllocation()) continue;
1181       if (!AI->isStaticAlloca()) continue;
1182       if (!AI->getAllocatedType()->isSized()) continue;
1183       ResultAlignment = std::max(ResultAlignment, AI->getAlignment());
1184       AllocaVec.push_back(AI);
1185       uint64_t AlignedSize =  getAlignedAllocaSize(AI);
1186       TotalSize += AlignedSize;
1187     }
1188   }
1189
1190   if (AllocaVec.empty()) return false;
1191
1192   uint64_t LocalStackSize = TotalSize + (AllocaVec.size() + 1) * RedzoneSize();
1193
1194   bool DoStackMalloc = CheckUseAfterReturn
1195       && LocalStackSize <= kMaxStackMallocSize;
1196
1197   Instruction *InsBefore = AllocaVec[0];
1198   IRBuilder<> IRB(InsBefore);
1199
1200
1201   Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
1202   AllocaInst *MyAlloca =
1203       new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
1204   if (ClRealignStack && ResultAlignment < RedzoneSize())
1205     ResultAlignment = RedzoneSize();
1206   MyAlloca->setAlignment(ResultAlignment);
1207   assert(MyAlloca->isStaticAlloca());
1208   Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
1209   Value *LocalStackBase = OrigStackBase;
1210
1211   if (DoStackMalloc) {
1212     LocalStackBase = IRB.CreateCall2(AsanStackMallocFunc,
1213         ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
1214   }
1215
1216   // This string will be parsed by the run-time (DescribeStackAddress).
1217   SmallString<2048> StackDescriptionStorage;
1218   raw_svector_ostream StackDescription(StackDescriptionStorage);
1219   StackDescription << F.getName() << " " << AllocaVec.size() << " ";
1220
1221   uint64_t Pos = RedzoneSize();
1222   // Replace Alloca instructions with base+offset.
1223   for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1224     AllocaInst *AI = AllocaVec[i];
1225     uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1226     StringRef Name = AI->getName();
1227     StackDescription << Pos << " " << SizeInBytes << " "
1228                      << Name.size() << " " << Name << " ";
1229     uint64_t AlignedSize = getAlignedAllocaSize(AI);
1230     assert((AlignedSize % RedzoneSize()) == 0);
1231     Value *NewAllocaPtr = IRB.CreateIntToPtr(
1232             IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Pos)),
1233             AI->getType());
1234     replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB);
1235     AI->replaceAllUsesWith(NewAllocaPtr);
1236     // Analyze lifetime intrinsics only for static allocas we handle.
1237     if (CheckLifetime)
1238       HavePoisonedAllocas |= handleAllocaLifetime(NewAllocaPtr);
1239     Pos += AlignedSize + RedzoneSize();
1240   }
1241   assert(Pos == LocalStackSize);
1242
1243   // Write the Magic value and the frame description constant to the redzone.
1244   Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1245   IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1246                   BasePlus0);
1247   Value *BasePlus1 = IRB.CreateAdd(LocalStackBase,
1248                                    ConstantInt::get(IntptrTy, LongSize/8));
1249   BasePlus1 = IRB.CreateIntToPtr(BasePlus1, IntptrPtrTy);
1250   GlobalVariable *StackDescriptionGlobal =
1251       createPrivateGlobalForString(*F.getParent(), StackDescription.str());
1252   Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal, IntptrTy);
1253   IRB.CreateStore(Description, BasePlus1);
1254
1255   // Poison the stack redzones at the entry.
1256   Value *ShadowBase = memToShadow(LocalStackBase, IRB);
1257   PoisonStack(ArrayRef<AllocaInst*>(AllocaVec), IRB, ShadowBase, true);
1258
1259   // Unpoison the stack before all ret instructions.
1260   for (size_t i = 0, n = RetVec.size(); i < n; i++) {
1261     Instruction *Ret = RetVec[i];
1262     IRBuilder<> IRBRet(Ret);
1263
1264     // Mark the current frame as retired.
1265     IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1266                        BasePlus0);
1267     // Unpoison the stack.
1268     PoisonStack(ArrayRef<AllocaInst*>(AllocaVec), IRBRet, ShadowBase, false);
1269
1270     if (DoStackMalloc) {
1271       // In use-after-return mode, mark the whole stack frame unaddressable.
1272       IRBRet.CreateCall3(AsanStackFreeFunc, LocalStackBase,
1273                          ConstantInt::get(IntptrTy, LocalStackSize),
1274                          OrigStackBase);
1275     } else if (HavePoisonedAllocas) {
1276       // If we poisoned some allocas in llvm.lifetime analysis,
1277       // unpoison whole stack frame now.
1278       assert(LocalStackBase == OrigStackBase);
1279       poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
1280     }
1281   }
1282
1283   // We are done. Remove the old unused alloca instructions.
1284   for (size_t i = 0, n = AllocaVec.size(); i < n; i++)
1285     AllocaVec[i]->eraseFromParent();
1286
1287   if (ClDebugStack) {
1288     DEBUG(dbgs() << F);
1289   }
1290
1291   return true;
1292 }
1293
1294 void AddressSanitizer::poisonAlloca(Value *V, uint64_t Size, IRBuilder<> IRB,
1295                                     bool DoPoison) {
1296   // For now just insert the call to ASan runtime.
1297   Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
1298   Value *SizeArg = ConstantInt::get(IntptrTy, Size);
1299   IRB.CreateCall2(DoPoison ? AsanPoisonStackMemoryFunc
1300                            : AsanUnpoisonStackMemoryFunc,
1301                   AddrArg, SizeArg);
1302 }